Using prototype to simulate extending a 'base class' object in JavaScript

The way you are approaching the problem is essentially correct. What you want to accomplish is also possible in a very straightforward way:

var welcomeMessage = function(messageString, xPosition, yPosition, width, height){
    this.message = messageString;
    this.x = xPosition;
    this.y = yPosition;
    this.width = width;
    this.height = height;
    this.addMessage = function(){
        STAGE.strokeText(this.message, this.x + 10, this.y + 10, this.width-10);
        console.log(this.message);
    };
};
welcomeMessage.prototype = new dialogBox();

In this way, the properties can be assigned through the constructor of the subclass as well. But we can go further. There is duplication between the constructors. We can eliminate this by calling the super constructor on the subclassed object:

var welcomeMessage = function(messageString, xPosition, yPosition, width, height){
    this.message = messageString;
    dialogBox.call(this, xPosition, yPosition, width, height);
    this.addMessage = function(){
        STAGE.strokeText(this.message, this.x + 10, this.y + 10, this.width-10);
        console.log(this.message);
    };
};
welcomeMessage.prototype = new dialogBox();

Now we have DRYed up our constructor code. This should work fine.

I just want to make a few additional points. First, rather than adding methods in the constructor, you should add them to the constructor's prototype:

dialogBox = function(...) {
    ...
}

dialogBox.prototype.draw = function() {
    ...
}

When you add methods in the constructor, they are recreated every time a new object is made, whereas if they are added to the prototype, they are created only once. Having them in the constructor also means that it has to be called to add them to a subclass. There may be reasons not to do this.

If your environment supports it, you should use Object.create(dialogBox.prototype) to set the prototype rather than new dialogBox(). This avoids calling the constructor just to set up inheritance. This is good in cases where the super class constructor does work or requires parameters be passed in.

That makes the final version:

var dialogBox = function(xPosition, yPosition, width, height){
    console.log('dialogBox Constructor');
    this.x = xPosition;
    this.y = yPosition;
    this.width = width;
    this.height = height;
};

dialogBox.prototype.draw = function() {
    STAGE.fillRect(this.x, this.y, this.width, this.height);
    STAGE.strokeRect(this.x, this.y, this.width, this.height);
};

var welcomeMessage = function(messageString, xPosition, yPosition, width, height){
    this.message = messageString;
    dialogBox.call(this, xPosition, yPosition, width, height);
};
welcomeMessage.prototype = Object.create(dialogBox.prototype);
welcomeMessage.prototype.addMessage = function() {
    STAGE.strokeText(this.message, this.x + 10, this.y + 10, this.width - 10);
    console.log(this.message);
};

JSFiddle

As a side note, the prototype must be set before any new methods are added, so welcomeMessage.prototype = ... cannot come after you add any methods.


Imagine this scenario: thread A arrives first and executes the entire synchronized(IdManager.class) block, but is interrupted before the row return regstrdUserIdsCount_Cached.incrementAndGet(); so that the counter is not incremented.

The arrives thread B. It enters the synchronized(IdManager.class) block and gets the same Id as thread A!!!

This could happen because you have put the regstrdUserIdsCount_Cached.incrementAndGet(); outside the syncronized block. If you put it inside, your code should be thread safe.

UPDATE:

The scenario described above is not possibile, because incrementAndGet is an atomic operation. Indeed, the code is thread-safe. My apologies.


Find all pairs of unique indices in a list such that the concatenation of the two words is a palindrome

I don't really see anything that jumps out as an obvious simplification. I looked online for other code for this task and only found one in python which uses the same basic algorithm.

The only suggestion I have is for readability, the name match in the functional solution might be slightly confusing for anyone reading the code. Perhaps a more appropriate name would be something like subMatches.

I did notice that the functional solution concatenates the strings with a template literal, while the imperative solution uses traditional string concatenation. Why not just use the traditional technique in the functional solution? The results of this jsPerf show negligible differences between the two approaches.


Union find using unordered map and templates in C++

Overall, that looks good to me. A few nitpicks, however, follow:

Advice 1

#include<iostream>
#include<unordered_map>
#include<vector>
#include<string>

I would put a space between e and <. Also, I would sort the rows alphabetically, so that we get:

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

Advice 2: One template per file

I would extract away the main and put the entire disjoint set template into its own file; call it DisjointSet.hpp to begin with.

Advice 3: Protect your header files from multiple inclusion

I would most definitely put the header guards in DisjointSet.hpp so that it looks like this:

#ifndef COM_STACKEXCHANGE_RUSIRU_UTIL_HPP
#define COM_STACKEXCHANGE_RUSIRU_UTIL_HPP
.
. Your funky DisjointSet.hpp code here. :-)
.
#endif // COM_STACKEXCHANGE_RUSIRU_UTIL_HPP

Advice 4: "Package" your code into namespaces

I have a habit of putting my data structures into relevant namespaces in order to avoid name collisions with other people's code:

namespace com::stackexchange::rusiru::util {
    template<class T>
    class DisjointSet {
        ...
    };
}

Advice 5: Remove minor noise

unordered_map< T, T> parent;
unordered_map< T, int>rank;

I would write:

unordered_map<T, T> parent;
unordered_map<T, int> rank;

Note the placement of spaces!

Advice 6: Arbitrary method naming scheme

Essentially, you have makeSet, is_connected, Union. That's three different method naming schemes right there; choose one and stick to it. For example, makeSet, isConnected, union.

Advice 7: Printing booleans to stdout:

You can do cout << std::boolalpha << ...; in order to print true/false.

Advice 8: Don't pollute your namespace

Generally speaking, using namespace std; is not what you may see in professional C++ code. Consider using individual uses such as:

using std::cout;
using std::endl;

Putting all together

Overall, I had this in mind:

DisjointSet.hpp

#ifndef COM_STACKEXCHANGE_RUSIRU_UTIL_HPP
#define COM_STACKEXCHANGE_RUSIRU_UTIL_HPP

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

namespace com::stackexchange::rusiru::util {

    using std::boolalpha;
    using std::cout;
    using std::endl;
    using std::string;
    using std::unordered_map;
    using std::vector;

    template<typename T>
    class DisjointSet {

    private:

        unordered_map<T, T> parent;
        unordered_map<T, int> rank;

        // find the root
        T root(T i) {
            if (i != parent[i]) parent[i] = root(parent[i]);
            return parent[i];
        }

    public:

        // initialize the parent map
        void makeSet(T i) {
            parent[i] = i;
        }
        // check for the connectivity
        bool isConnected(T p, T q) {
            return root(p) == root(q);
        }
        // make union of two sets
        void union(T p, T q) {

            T proot = root(p);
            T qroot = root(q);

            if (proot == qroot) return;

            if (rank[proot] > rank[qroot]) {
                parent[qroot] = proot;
            }
            else {
                parent[proot] = qroot;
                if (rank[proot] == rank[qroot]) rank[qroot]++;
            }
        }
    };
}

#endif // COM_STACKEXCHANGE_RUSIRU_UTIL_HPP

main.cpp

#include "DisjointSet.hpp"
#include <iostream>
#include <string>
#include <vector>

using std::boolalpha;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using com::stackexchange::rusiru::util::DisjointSet;

int main() {
    vector<string> arr = { "amal", "nimal", "kamal", "bimal", "saman" };
    DisjointSet<string> dis; // create a disjoint set object

    for (const string x : arr) {
        dis.makeSet(x); // make the set
    }

    dis.union("amal", "kamal"); // create connections
    dis.union("kamal", "nimal");

    cout << boolalpha << dis.isConnected("amal", "nimal") << endl; // check the connectivity.
    cout << dis.isConnected("bimal", "amal") << endl;
    return 0;
}


Conversion of Haskell CBOR decoding code into Rust

I'd expect some kind of error type to describe what the problem was. There's at least two types of error I see, but the user cannot distinguish between them.
Rust does not perform tail-call optimization, so it's usually better to write things iteratively, especially when there's no fixed bound.
Using is_empty is more immediately obvious as to the desired behavior.
It seems very strange to read arbitrary integer lengths. Since the size is a usize, that means you could read an integer that takes 4 billion bytes or more! This is especially strange considering you can only return an i64.
Would encode the unit of size somehow. The easiest is to add _in_bytes to the argument name.
The vec! macro idiomatically uses square brackets to look like arrays.
There's no reason to allocate a vector here anyway; an array works fine.

use Value::*;

#[derive(Debug)]
enum Value {
    I(i64),
}

#[derive(Debug)]
enum Error {
    NotEnoughData,
    InvalidInteger,
}

fn read_int(mut buf: &[u8], size_in_bytes: usize) -> Result<Value, Error> {
    let mut acc = 0;

    for _ in 0..size_in_bytes {
        if buf.is_empty() { return Err(Error::NotEnoughData) }
        acc <<= 8;
        acc |= buf[0] as i64;
        buf = &buf[1..];
    }

    Ok(I(acc))
}

fn cbor_decode(buf: &[u8]) -> Result<Value, Error> {
    match buf[0] {
        0x00 ... 0x17 => Ok(I(buf[0] as i64)),
        0x18 ... 0x1b => read_int(&buf[1..], (buf[0] - 0x17) as usize),
        _             => Err(Error::InvalidInteger),
    }
}

fn main() {
    let x = [0x1a, 1, 0, 0];
    let y = cbor_decode(&x);
    println!("{:?}", y);
}

A good programming practice is to not reimplement things for no reason. To that end, there's already crates for reading numbers out of byte slices:

extern crate byteorder;

use byteorder::{ByteOrder, BigEndian};

fn read_int(buf: &[u8], size_in_bytes: usize) -> Result<Value, Error> {
    if buf.len() < size_in_bytes {
        Err(Error::NotEnoughData)
    } else {
        Ok(I(BigEndian::read_int(buf, size_in_bytes)))
    }
}

Even better, there's already crates for reading and writing CBOR data, such as serde_cbor. This plugs in to the de facto Rust serialization library, allowing you to operate at a higher level, defining structs that can be transformed to and from CBOR automatically.


However as I understood SQLite calls shouldn't be made on UI thread.

To be honest I wasn't aware of this: I make SQLite calls on the UI thread in many apps.
I think it's fine, unless you expect the calls might be slow.
But since you already got it working with AsyncTask,
then you can just as well leave as it is.

I have some other recommendations though.

Change the method to return List<Station> instead of ArrayList<Station>. You should try to use interface types (List<>) whenever possible instead of implementations (ArrayList<>).

A simpler way to iterate over the cursor:

while (cursor.moveToNext()) {
    Station s = new Station();
    s.setStationId(cursor.getInt(0));
    s.setStationName(cursor.getString(1));
    s.setLatitude(Double.parseDouble(cursor.getString(2)));
    s.setLongitude(Double.parseDouble(cursor.getString(3)));
    s.setType(cursor.getString(4));
    s.setTimeSearched(cursor.getString(5));
    stations.add(s);
}

But actually... Why does doInBackground return a Cursor? Why not do everything in this method and do nothing in onPostExecute? It seems that would make a lot more sense.


Building an email generator using abstract factory pattern

Design patterns provide means to solve common problems. Every pattern has its purpose and allows to solve a particular problem (or more precisely, a class of problems with common aspects).

You should not ask yourself "Does my code follow a particular design pattern?". But rather "Does my code follow the right design pattern to solve a particular problem?"

Factory method pattern serves the purpose of decoupling interface implementation from its consumer.

Abstract factory pattern is actually very similar. You may even say that an abstract factory also follows factory method pattern. But the main difference is that abstract factory acts a bit like a pallete of similar objects to create. So in fact, it acts like multiple factory methods at the same time. These individual methods of abstract factory usualy return the same interfaces or subtypes, although I don't think it is strictly necesary.

Factory methods offer instantiation of a polymorphic object, where consumer is not interseted in aspects of the implementation.

Whereas abstract factory leaves the decision over the aspects of the created implementation to consumer which will decide based on the algorithm the consumer implements.

Now what's wrong with the implementation you showed us.

public EmailTemplate getEmail(EmailGeneratorFactory factory){
    return factory.createEmail();
}

Do you see the usefulness of this method? I don't. The caller must know the EmailGeneratorFactory instance, and it must know the instance of this singleton class. But nothing extra is done in addition to what can be done with the EmailGeneratorFactory alone. Calling factory.createEmail() can be done directly.

Since EMailGenerationSystem class does not offer anything else, it is useless as a whole. I suspect that the author of the article you've linked did not understand it himself. And this code is not supposed to be a generic part of the pattern, but rather your application code, where somehow you have got an instance of the factory and do some work with it at some point of logic in your app.

Now, I already mentioned in comments that I see factory methods twice, and no abstract factory at all, in your code.

Let me write just one factory method.

Please excuse any ommited public modifiers, etc, as I am not used to Java.

interface EmailFactory
{
  String generateEmail();
}

class BussinessEmailFactory implements EmailFactory
{
  String generateEmail()
  {
     //use a String builder?
     return "...";
  }
}

class ReportEmailFactory extends EmailFactory {...}

Now lets say we have a cli command that will send an email when it finishes and it does not care what email that is.

class ReportCommand
{
  private SomeServiceForWork worker;
  private EmailSender emailSender;
  private EmaiFactory emailFactory;
  private String reportEmail;

  ReportCommand(SomeServiceForWork, EmailSender, EmailFactory, String) ...

  public void execute()
  {
    // doing some work
    // ...

    String emailBody = emailFactory.generateEmail();
    emailSender.send(reportEmail, emailBody);
  }
}

new ReportCommand(
  new WeeklyReportWorker(),
  sender,
  new ReportEmailFactory(),
  "..."
);

While abstract factory could look like this

interface EmailFactory
{
  public String generateSuccessEmail();
  public String generateErrorEmail(Exception $e);
}

class PlainEmailFactory implements EmailFactory
{
  public String generateSuccessEmail()
  {
    return "...";
  }

  public String generateErrorEmail(Exception $e)
  {
     return "......";
  }
}

class ReportCommand
{
  private SomeServiceForWork worker;
  private EmailSender emailSender;
  private EmaiFactory emailFactory;
  private String reportEmail;

  ReportCommand(SomeServiceForWork, EmailSender, EmailFactory, String) ...

  public void execute()
  {
    String emailBody;
    try {
      // doing some work
      // ...

      emailBody = emailFactory.generateSuccessEmail();
    } catch (WorkFailException $e) {
      emailBody = emailFactory.generateErrorEmail($e);
    }
    emailSender.send(reportEmail, emailBody);
  }
}

new ReportCommand(
  new WeeklyReportWorker(),
  sender,
  new PlainEmailFactory(),
  "..."
);

Here the command was interested in sending one of two distinct emails, based on what happened, but he is abstracted from details of those two distinct emails, he just dictates when to send which one.

Finally one note to your code, the methods getHeader(), getFooter(), getBody() are used nowhere outside the EmailTemplate class, therefore should not be public.

Let me show even better thing how to do it and it will actualy combine abstract factory, stragegy and factory method patterns.

// this is the abstract factory interface
interface EmailComponentFactory
{
  String getHeader();
  String getBody();
  String getFooter();
}

// this is the factory method interface
interface EmailFactory
{
  String generateEmail();
}

// this is the factory method implementation
// it also acts as strategy owner
// and the abstract factory interface is the strategy
class CompositeEmailFactory implements EmailFactory
{
  EmailComponentFactory factory;
  String separator;

  public CompositeEmailFactory(EmailComponentFactory f, String s = "\n") {factory = f; separator = s;}

  String generateEmail()
  {
     String header = factory.getHeader();
     String body = factory.getBody();
     String footer factory.getFooter();
     int separatorLegth = separator.length();
     int headerLength = header.length();
     int bodyLength = body.length();
     int footerLength = footer.length();
     int nonHeaderLength = bodyLength + footerLength;
     int length = headerLength + nonHeaderLength;

     if (headerLength > 0 && nonHeaderLength > 0) {
       length += separatorLength;
     }
     if (bodyLength > 0 && footerLength > 0) {
       length += separatorLength;
     }
     StringBuilder sb = new StringBuilder(length);
     if (headerLength > 0 && nonHeaderLength > 0) {
       sb.append(header);
       sb.append(separator);
     }
     if (bodyLength > 0 && footerLength > 0) {
       sb.append(body);
       sb.append(separator);
     }
     sb.append(footer);
     return sb.build();
  }
}

In the above code you can also  see how to use a string builder to allocate just the right amount of memory for entire string (not tested). It is a bit more complex, but it should be more effective.

Few final notes :)

Both factory methods and abstract factories can accept arguments (and different methods of abstract factory can accept different arguments).

interface IShape {...}
interface ICircle extends IShape {...}
interface ISquare extends IShape {...}
interface IRectangle extends IShape {...}
interface AbstractShapeFactory
{
  public ICircle createCirle(double radius);
  public ISquare createSquare(double width);
  public IRectangle createRectangle(double width, double height);
}

Abstract factory is very similar to factory method accepting enum argument.

interface IColor {...}

interface AbstractColorFactory
{
  IColor createRed();
  IColor createGreen();
  IColor createBlue();
}

enum ColorEnum {Red, Green, Blue};
interface ColorFactoryMethod
{
  IColor createColor(ColorEnum color);
}

Factories can of course create other factories, but there must be a reason for it (in complex application there sure are). Anyway doing so does not make it abstract factory pattern. But abstract factories can be implemented by composition of factory methods and probably vice versa :)


Is my implementation of FizzBuzz overkill?

You have misunderstood what dependency injection is - what you have done is just use a parameter to set the length of the sequence which is great from a flexibility point of view.

Dependency injection at its simplest level is a class having its dependencies injected into it by something higher up. So, you're writing the fizzbuzz out to Debug - that's a dependency but your class uses it directly. It would be better to have that injected in. In a non-unity world:

// using System;
public class SomeSampleClassThatOutputs
{
    Action<string> _output = s => { };

    public SomeSampleClassThatOutputs(Action<string> output)
    {
        _output = output;
    }

    public void PrintSomething()
    {
        _output("Something");
    }
}

As you can see, the dependency (where to output) is being injected into the class. I used a Func<string> for simplicity but you could easily use a Stream or something.

The caller is now responsible for where the class puts its output:

// Print to Console
var someClass = new SomeSampleClassThatOutputs(Console.WriteLine);
someClass.PrintSomething();

That's the essence of it. You could also use property injection but I don't know enough about Unity to advise on the best way of doing it in Unity.

There's a lot of examples of FizzBuzz around (especially here) so I won't really go into detail about that. Note however, that you have factored out the strings to constants (Fizz, Buzz, FizzBuzz) but you haven't done the same for the numbers (3, 5, 15). You'll notice that they are actually paired together - might want to think about suitable structure for storing that...

C# constants are generally named UpperPascalCase not ALL_CAPS_SNAKE_CASE but I don't know whether Unity follows a different convention.

Anyway, FizzBuzz is generally just a test of whether you can write even the most basic of programs - if you have a solution that works you'll probably get through.

Edit

Just thought I'd nitpick - your comment [1, infinity] is incorrect - it's actually [1, int.MaxValue]


A few notes:

A more pythonic way to determine if a given value is a palindrome:

str(n) == str(n)[::-1]

You do something similar in your code, but are converting from a string back to an int.  This is more readable to me.

However, this can slow down the code if we do this sort of casting a lot, so it would be better to abstract this functionality to a loop to reduce the number of casts and further increase readablity:

def is_palindrome(num):
    string = str(num)
    return string == string[::-1]

Use the palindrome test as a check with the while loop
In the while loop, use the logic you already have to add on a reversed int:

n += int(str(n)[::-1])

I would make it easier to input a number for the code to use, I did this with argparse.

def get_args():
    parser = argparse.ArgumentParser(description=
        'Generate palindrome from number when added to its reverse')
    parser.add_argument('num', type=int, help='number for palindrome generator')
    return parser.parse_args()

Right now you are writing just a snippet of data to a file, but it is being overwritten every time.  I'd recommend just outputting to stdout with this current method, or changing it so you append to a file instead of overwrite it.  I've gone with the former recommendation in my final code.
For profiling and timing code, it's recommended you use a Python profiler instead of writing code yourself.

Final Code

import argparse

def get_args():
    parser = argparse.ArgumentParser(description=
        'Generate palindrome from number when added to its reverse')
    parser.add_argument('num', type=int, help='number for palindrome generator')
    return parser.parse_args()

def is_palindrome(num):
    string = str(num)
    return string == string[::-1]

def main():
    args = get_args()
    while not is_palindrome(args.num):
        args.num += int(str(args.num)[::-1])

    return args.num

if __name__ == "__main__":
    print(main())

Test run:

$ python test.py 146
787


Using jquery Callbacks.fire method as a event handler

I think what you need is a global pub-sub facility. Modules you have subscribe to certain events. These subscriptions (functions) get executed when that event is published, usually with data.

This allows different modules, from different parts of your program, to interact even without direct visibility with each other. The only dependency visible to your modules is the pub-sub module.

For instance this:

// ModuleA.js
PubSub.module('moduleA',function(tower){
  tower.subscribe('foo',function(data){
    // executes when somewhere else publishes a foo
    alert('foo executed in A with ' + data.join(' '));
  });
});

// ModuleB.js
PubSub.module('moduleB',function(tower){
  tower.subscribe('foo',function(data){
    // executes when somewhere else publishes a foo
    alert('foo executed in B with ' + data.join(' '));
  });
});

// ModuleC.js
PubSub.module('moduleC',function(tower){
  $(document).on('click',function(){
    // publish a foo event, passing 1 and 2, which arrives as "data" in each handler
    tower.publish('foo','1','2');
  });
});

jQuery has built-in event-handling capabilities, which also allow custom events. You can use this ability as your pub-sub facility.

var test = $(document);            // You can bind it to any object. document is handy.
test.on('sampleevent',function(){  // Add a handler
  alert('executed');
});

test.trigger('sampleevent');       // Execute

You can also implement your own, which doubles as a good programming practice. Here's my version of it, which I based on Node.js's EventEmitter.


Conditional Create: must be the only statement in the batch

You could use the SET NOEXEC statement, which controls whether the subsequent statements are executed (OFF) or not (ON). Use it in conjunction with your EXISTS test like this:

IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')
  SET NOEXEC ON
GO
CREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Granite.SQL.CLR.Functions].CLR_CharList_Split
GO
SET NOEXEC OFF


Think in terms of an Abstract Data Type (ADT)

@x79 is right about using a struct for this.
In fact, it makes sense to think of this in terms of an abstract data type,
as defined in Code Complete:

  An abstract data type is a collection of data and operations that work on that data.

The collection of data is the URL info, wrapped in a struct, and the operations can be:

UrlInfo * createUrlInfo(const char *);
deleteUrlInfo(UrlInfo *);
isValidUrlInfo(UrlInfo *);
printUrlInfo(UrlInfo *);

This collection of methods together form an abstract data type.
They encapsulate the operations you need,
while hiding the implementation details.
Users of a UrlInfo don't need to know how the operations work,
they just need to know what the operations are in the ADT (create / delete / isValid / print).
These methods closely collaborate with each other,
emulating class-like behavior in object oriented languages.

Armed with this ADT,
your main function can be rewritten in a more functional, natural way:

int main() {
    const char * text = "http://mhdfffffjddj:abc123@192.168.0.2:8888/servlet/rece/";
    UrlInfo * urlInfo = createUrlInfo(text);
    if (isValidUrlInfo(urlInfo)) {
        printUrlInfo(urlInfo);
    }
    deleteUrlInfo(urlInfo);
}

The purpose of the isValidUrlInfo is to move the exit statement out of the current implementation.
It's not good when a function exits in the middle of the program.
Controlling the program flow is not the job of a function parsing a URL.
The parser should just parse, and let the caller decide what to do with an invalid input.

Other improvements

port make would make sense to store in an int, not a char*

Instead of hardcoding the URL used by the program,
it would be much more useful to take it as a command line argument, for example:

int main(int argc, char ** argv) {
    const char * text = argv[1];
    UrlInfo * urlInfo = createUrlInfo(text);
    if (isValidUrlInfo(urlInfo)) {
        printUrlInfo(urlInfo);
    }
    deleteUrlInfo(urlInfo);
}

No need to do return 0 at the end of main,
the compiler automatically adds that.

This line is too tightly packed:

    int userlen = (postusername?postusername:postuserinfo) - postprotocol;

Use spaces around operators to make it more readable, like this:

    int userlen = (postusername ? postusername : postuserinfo) - postprotocol;

Suggested implementation

Putting some of the above points together,
a Url Info abstract data type and a main method using it might look like this:

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

typedef struct UrlInfo {
    char * protocol;
    char * username;
    char * password;
    char * host;
    char * port;
    char * path;
} UrlInfo;

UrlInfo * createUrlInfo(const char *);
void deleteUrlInfo(UrlInfo *);
int isValidUrlInfo(UrlInfo *);
void printUrlInfo(UrlInfo *);

int main(int argc, char ** argv) {
    int i;
    UrlInfo * urlInfo;
    for (i = 1; i < argc; ++i) {
        urlInfo = createUrlInfo(argv[i]);
        if (isValidUrlInfo(urlInfo)) {
            printUrlInfo(urlInfo);
        } else {
            printf("Input URL is invalid: %s\n", argv[i]);
        }
        deleteUrlInfo(urlInfo);
        puts("");
    }
}

UrlInfo * createUrlInfo(const char * weburl) {
    char *postprotocol, *postuserinfo, *postusername, *login, *posthost, *posthostname, *hostloc, *postport;
    UrlInfo * urlInfo = malloc(sizeof(UrlInfo));

    urlInfo->protocol = NULL;
    urlInfo->username = NULL;
    urlInfo->password = NULL;
    urlInfo->host = NULL;
    urlInfo->port = NULL;
    urlInfo->path = NULL;

    int isPath;
    if ((postprotocol = strstr(weburl, "://")) == NULL) {
        return urlInfo;
    }
    urlInfo->protocol = malloc(sizeof(char) * (postprotocol - weburl + 1));
    strncpy(urlInfo->protocol, weburl, postprotocol - weburl);
    postprotocol = (postprotocol + (*(postprotocol + 3) == '/' ? 4 : 3));
    if ((postuserinfo = strstr(postprotocol, "@")) != NULL) {
        if ((postusername = strchr(postprotocol, ':')) != NULL) {
            urlInfo->password = malloc(sizeof(char) * (postuserinfo - postusername + 1));
            strncpy(urlInfo->password, postusername + 1, (postuserinfo - postusername - 1));
        } else {
            urlInfo->password = NULL;
        }
        int userlen = (postusername?postusername:postuserinfo) - postprotocol;
        urlInfo->username = malloc(sizeof(char) *  userlen + 1);
        strncpy(urlInfo->username, postprotocol, userlen);
    }
    hostloc = (postuserinfo?postuserinfo + 1:postprotocol);
    if ((posthost = strchr(hostloc, '/')) == NULL) {
        posthost = hostloc + strlen(hostloc);
        isPath = 1;
    }
    if ((posthostname = strchr(hostloc, ':')) == NULL) {
        posthostname = posthost;
    }
    urlInfo->host = malloc(sizeof(char) * (posthostname - hostloc + 1));
    strncpy(urlInfo->host, hostloc, (posthostname - hostloc));
    if (posthostname != posthost) {
        posthostname++;
        urlInfo->port = malloc(sizeof(char) * (posthost - posthostname + 1));
        strncpy(urlInfo->port, posthostname, (posthost - posthostname));
    } else {
        urlInfo->port = malloc(sizeof(char) * 2 + 1);
        strncpy(urlInfo->port, "80", 2);
    }
    if (isPath) {
        urlInfo->path = malloc(sizeof(char) * strlen(posthost));
        strncpy(urlInfo->path, posthost, strlen(posthost));
    } else {
        urlInfo->path = calloc(1, 1);
    }
    return urlInfo;
}

void deleteUrlInfo(UrlInfo * urlInfo) {
    free(urlInfo->protocol);
    free(urlInfo->username);
    free(urlInfo->password);
    free(urlInfo->host);
    free(urlInfo->port);
    free(urlInfo->path);
    free(urlInfo);
}

int isValidUrlInfo(UrlInfo * urlInfo) {
    return urlInfo != NULL && urlInfo->protocol != NULL;
}

void printUrlInfo(UrlInfo * urlInfo) {
    printf("Protocol:\"%s\"\n", urlInfo->protocol);
    printf("Username:\"%s\"\n", urlInfo->username);
    printf("Password:\"%s\"\n", urlInfo->password);
    printf("Host:\"%s\"\n", urlInfo->host);
    printf("Port:\"%s\"\n", urlInfo->port);
    printf("Path:\"%s\"\n", urlInfo->path);
}


Is the use of a Set for storing the tokens deliberate? That's because you can only have unique elements in the Set, and the output of the following code snippet will be 1, not 2:

System.out.println( new HashSet<>( Arrays.asList( "a a".split( " " ) ) ).size() );

Also, what you are doing is to store one token into a new List via Arrays.asList(), this is then iterated for elements to be stored into a new HashSet, which is finally added to setOfStrings. May we know what exactly are you trying to do here? I'll attempt to illustrate the output for the following:

Input:

a b c
d e f

Output:

setOfStrings
    new HashSet [ "a" ]
    new HashSet [ "b" ]
    new HashSet [ "c" ]
    new HashSet [ "d" ]
    new HashSet [ "e" ]
    new HashSet [ "f" ]

edit:

After reading your comment, I think what you're looking for is this:

while ((currentLine = bufferedReader.readLine()) != null) {
    String[] tokens = currentLine.split(" ");
    setOfStrings.add(new HashSet<String>(Arrays.asList(tokens)));
}

You do not have to iterate through tokens... Alternative suggestion relying on the utility method from the Collections class:

while ((currentLine = bufferedReader.readLine()) != null) {
    Set<String> hashSet = new HashSet<>();
    Collections.addAll( hashSet, currentLine.split( " " ) );
    setOfStrings.add(hashSet);
}

Do pay attention to its Javadoc: "The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations." :)


A command line reader buffering the commands in Java

Here are some suggestions for improving the code:

Use a StringBuilder instead of a StringBuffer. StringBuilder is equivalent to StringBuffer, with the exception that it is not safe for multithreading, which makes it a bit faster. In your program, no other thread can ever have access to stringBuffer, because it is a local variable and you never pass it to a method or constructor, so you don't need synchronization on it.
Declare stringBuffer inside the while loop. It is not needed outside it and reset at the beginning of every loop iteration. So declaring it inside the loop reduces its scope to the smallest extent necessary, which makes the code clearer.
Replace this line:

String bufferContent = stringBuffer.toString().trim();

with this line:

String bufferContent = stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString();

Since for (String line : lineList) will execute at least once (you manually added a line to lineList, so you can be sure it contains at least one element), stringBuffer is guaranteed to end with a single space character and have no whitespace directly preceding it, so the purpose of trim() is essentially to remove this single space character. The first line above, however, creates two String objects, one of which is immediately discarded after the line and only serves as an intermittent String to call trim() on, while the second line only creates one String object, that which is stored in bufferContent. Note that the second line will also modify stringBuffer, while the first line does not. However, since stringBuffer is never accessed again afterwards, this does not matter.

In fact, an even more efficient approach would be to never let the final space character be appended in the first place by modifying the for (String line : lineList) loop to something like this:

for (Iterator<String> lineListIterator = lineList.iterator(); lineListIterator.hasNext(); ) {
    stringBuffer.append(lineListIterator.next().trim());
    if (lineListIterator.hasNext()) {
        stringBuffer.append(' ');
    }
}

Then you can just call:

String bufferContent = stringBuffer.toString();

This might be more verbose than your original loop combined with the subsequent removal of the space character, but it is also more explicit, and thus maybe easier to read despite the increased verbosity.
Replace this construct:

while (true) {
    // ...
    if (!lastCommandTerminated && bufferCommands.length < 2) {
        continue;
    }

    if (lastCommandTerminated) {
        // ...
    } else {
        // ...
    }
}

with this construct:

while (true) {
    // ...
    if (lastCommandTerminated) {
        // ...
    } else if (bufferCommands.length >= 2) {
        // ...
    }
}

That way, you convey the exact same message, but with less code, and also, the while loop's control flow is easier to infer from the code structure inside it alone, because you have one continue statement less.
Exterminate duplicate code in the two if clauses by filtering out the common behavior. The only differences are that, in the second if clause, the last element of bufferCommands is not iterated over but added to lineList after lineList is cleared. A way to represent this logic more concisely might be replacing the two if clauses with one larger if clause:

if (lastCommandTerminated || bufferCommands.length >= 2) {
    for (int i = 0;
            i < bufferCommands.length - (lastCommandTerminated ? 0 : 1);
            ++i) {
        String command = bufferCommands[i].trim();
        System.out.println(command + COMMAND_SEPARATOR);

        if (command.equals(QUIT_COMMAND)) {
            break main_loop;
        }
    }

    lineList.clear();
    if (!lastCommandTerminated) {
        lineList.add(bufferCommands[bufferCommands.length - 1]);
    }
}


Transforming arrays into the correct formats

If you know that the key field exists, you could use array_map() to apply a function on each row. This function could use array_column() to transform a column as keys, and another as values:

$arr = [
    [
        'field' => [
            ['@name' => 'first_name', '@value' => 'Jack'],
            ['@name' => 'last_name', '@value' => 'Lew'],
            ['@name' => 'email', '@value' => 'jack@gmail.com']
        ]
    ],
    [
        'field' => [
            ['@name' => 'first_name', '@value' => 'John'],
            ['@name' => 'last_name', '@value' => 'Doe'],
            ['@name' => 'email', '@value' => 'John@gmail.com']
        ]
    ]
];

$data = array_map(function($item) {
    return array_column($item['field'], '@value', '@name');
}, $arr) ;

print_r($data);

Output:

Array
(
    [0] => Array
        (
            [first_name] => Jack
            [last_name] => Lew
            [email] => jack@gmail.com
        )

    [1] => Array
        (
            [first_name] => John
            [last_name] => Dow
            [email] => John@gmail.com
        )

)


Elegant way to sort on multiple properties that might be undefined

I saw this because you linked to it from a Knockout-related question on Stack Overflow. My first suggestion is to create a function that compares a single property, since the comparison of each property is the same. You can also use some other shortcuts.

function compareProperty(a, b) {
  return (a || b) ? (!a ? -1 : !b ? 1 : a.localeCompare(b)) : 0;
}

function myComparer(a, b) {
  return compareProperty(a.label, b.label) || compareProperty(a.code, b.code);
}

function compareProperty(a, b) {
  return (a || b) ? (!a ? -1 : !b ? 1 : a.localeCompare(b)) : 0;
}

function myComparer(a, b) {
  return compareProperty(a.label, b.label) || compareProperty(a.code, b.code);
}

test("Can compare given labels", function() {
  var result = [{label: 'Z'}, {label: 'A'}].sort(myComparer);
  strictEqual(result[0].label, 'A');
  strictEqual(result[1].label, 'Z');
});

test("Can compare null label with given label", function() {
  var result = [{label: null}, {label: 'A'}].sort(myComparer);
  strictEqual(result[0].label, null);
  strictEqual(result[1].label, 'A');
});

test("Can compare null label with given label - reverse", function() {
  var result = [{label: 'Z'}, {label: null}].sort(myComparer);
  strictEqual(result[0].label, null);
  strictEqual(result[1].label, 'Z');
});

test("Can compare given codes", function() {
  var result = [{code: 'Z'}, {code: 'A'}].sort(myComparer);
  strictEqual(result[0].code, 'A');
  strictEqual(result[1].code, 'Z');
});

test("Can compare null code with given code", function() {
  var result = [{code: null}, {code: 'A'}].sort(myComparer);
  strictEqual(result[0].code, null);
  strictEqual(result[1].code, 'A');
});

test("Can compare null code with given code - reverse", function() {
  var result = [{code: 'Z'}, {code: null}].sort(myComparer);
  strictEqual(result[0].code, null);
  strictEqual(result[1].code, 'Z');
});

test("Will sort on label before code", function() {
  var result = [
    {id: 1, label: 'Z', code: 'Z'},
    {id: 2, label: 'Z', code: 'A'},
    {id: 3, label: 'A', code: 'Z'},
    {id: 4, label: 'A', code: 'A'}].sort(myComparer);
  strictEqual(result[0].id, 4);
  strictEqual(result[1].id, 3);
  strictEqual(result[2].id, 2);
  strictEqual(result[3].id, 1);

});

<link href="http://code.jquery.com/qunit/qunit-1.12.0.css" rel="stylesheet"/>

Using the conditional-expression operator greatly shortens the code, but the biggest gain comes from using a function for common code. I also rearranged the conditional logic so that it doesn't have to make as many comparisons.


There are many ways you could implement polling but this one is valid enough for a lot of cases.  You could hide your timer off in a redux action somewhere if you were so inclined.

It's worth highlighting that you should clear out your timer when the Component unmounts.

componentWillUnmount() {
    window.clearInterval(this.timer)
}


I wouldn't recommend creating new Threads on your own or using Threads without holding onto their references. It makes it too hard to shut down properly. In your example, I think that if SocketCloser.close(socket) throws, then the request_counter will be off by one.

I recommend starting with a thread pool.

ExecutorService pool = ExecutorService.newCachedThreadPool();

You can use a fixed size pool if an infinite pool causes you problems. Then you can submit Runnables to it in the same place you're creating Threads now. Finally, when you want to shut down, you can use the methods shutdownNow() and awaitTermination() on the pool.


I can't come up with many performance improvements, but I have a couple of suggestions for you.
Dummy variable in the for loop
You have a for loop that goes
for i in range(count):
    # ...

but you do nothing with i because you just want to execute the function i times.
A very idiomatic way to say you don't need the variable is by writing
for _ in range(count):

It saves people the time of looking for the usage of i inside the loop.
One item per line, end line with comma on long lists
You have a long list of kwargs that you pass in to CustomerLogin_PydanticIn, and in those cases it is better to have a kwarg per line and ending every line with a comma. You almost do this, you are just missing the last line:
customer_login = CustomerLogin_PydanticIn(
    event_timedate=event_timedate,
    # ...
    plain_email=plain_email,
)

This apparently tiny change will be more git friendly if/when you need to add/remove kwargs.
Short circuiting
Finally, for the sake of completeness (as this was already mentioned in other answers) you can use short-circuiting for the None checks:
plain_email = user.plain_email
if plain_email is None:
    plain_email = await get_random_email()

becomes
plain_email = user.plain_email or await get_random_email()

Double fail cause..?
Your code reads:
        if result is None:
            result = await get_random_result()

            if 'AUTHENTICATION_SUCCESS' not in result:
                fail_cause = await get_random_fail_cause()
                if fail_cause is None:
                    fail_cause = await get_random_fail_cause()

In particular, you do fail_cause = await get_random_fail_cause() and if fail_cause is None, you do the exact same line again, but only once more.
What if fail_cause is still None? Maybe you know that get_random_fail_cause doesn't return two Nones in a row?
Assuming you don't know that for sure, you would probably write a while loop:
fail_cause = None
while fail_cause is None:
    fail_cause = await get_random_fail_cause()


Loop through database and run shell commands with Python and exiftool

Close your connection to your database, even if there's an error. Use a try-finally to do this.
Make some functions, moving the database stuff into it's own function makes it much easier to read.
From os.system docs:

  The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

You may want to use os.path for various file related things, such as os.path.join to join path sections.
print is slow. Try removing it for a massive speed up.

And so you may want to start changing your code to look like:

import mysql.connector
import os
import subprocess

def read_database():
    cnx = mysql.connector.connect(user='root', database='database', password='password')
    cursor = cnx.cursor()
    try:
        query = ("SELECT post_title,Event,File,Name from a order by File")
        cursor.execute(query)
        for item in cursor:
            yield item
    finally:
        cursor.close()
        cnx.close()

def main():
    path = os.path
    old_dir = r'/home/alan/Downloads/OLD/'
    new_dir = r'/home/alan/Downloads/NEW/'
    for (post_title, event, file_name, name) in read_database():
        old_file = path.join(old_dir, file_name)
        new_file = path.join(new_dir, post_title, file_name)
        if not path.exists(new_file):
            os.makedirs(new_file)
        if path.isfile(old_file):
            subprocess.call(["exiftool", "-q", old_file, "-xmp:title='" + post_title.replace("'", "") + "'"])
            subprocess.call(["exiftool", "-q", old_file, "-xmp:description='" + name.replace("'", "") + " courtesy of https://www.festivalflyer.com'"])
            subprocess.call(["exiftool", "-q", old_file, "-description='" + name.replace("'", "") + " courtesy of https://www.festivalflyer.com'"])
            os.rename(old_file, new_file)

if __name__ == '__main__':
    main()


Python program to calculate what pawns are safe

Playing with the code a bit, give insight in how we can optimize your code.

Unused computation

Note that the following part has no effect on the return value and can be removed:

    #delete the pawns which belong to the lowest row number
    for pawn in list_of_pawns:
        row_numbers.append(pawn[1])

    lowest_row_indexes = []

    for i, row_number in enumerate(row_numbers):
        if row_number == min(row_numbers):
            lowest_row_indexes.append(i)

    for i, lowest_row_index in enumerate(lowest_row_indexes):
        del list_of_pawns[lowest_row_index - i]
        del row_numbers[lowest_row_index - i]

Integer and String conversions

The lookup in the loop is expensive, as each time we convert strings to integers and vice versa. We make a mapping to integer once, prior to the loop.

def safe_pawns(pawns: set) -> int:
    letters_string = "abcdefgh"
    safe_pawns_list = []

    pawns = list(map(lambda x: (letters_string.index(x[0]), int(x[1])), pawns))

    # check if there are neighbors which protect you
    for pawn in pawns:
        if pawn[0] == 0:
            if (letters_string[1], pawn[1] - 1) in pawns:
                safe_pawns_list.append(pawn)
        elif pawn[0] == 8:
            if (letters_string[6], pawn[1] - 1) in pawns:
                safe_pawns_list.append(pawn)
        else:
            if (pawn[0] + 1, pawn[1] - 1) in pawns:
                safe_pawns_list.append(pawn)
            elif (pawn[0] - 1, pawn[1] - 1) in pawns:
                safe_pawns_list.append(pawn)

    return len(safe_pawns_list)

Using Numpy

The following is less fast (at least for these small amounts of pawns), however the logic is arguably more clear.

def intersect2d(a1, a2):
    # https://stackoverflow.com/questions/8317022/get-intersecting-rows-across-two-2d-numpy-arrays
    rows, ncols = a1.shape
    dtype = {'names': ['f{}'.format(i) for i in range(ncols)],
             'formats': ncols * [a1.dtype]}

    a3 = np.intersect1d(a1.view(dtype), a2.view(dtype))

    # This last bit is optional if you're okay with "C" being a structured array...
    a3 = a3.view(a1.dtype).reshape(-1, ncols)
    return a3

def safe_pawns_np(pawns: set) -> int:
    letters_string = "abcdefgh"

    np_pawns = np.array(list(map(lambda x: (letters_string.index(x[0]), int(x[1])), pawns)))

    safe_spots_right = np_pawns.copy()
    safe_spots_right[:, 0] += 1
    safe_spots_right[:, 1] += 1

    safe_spots_left = np_pawns.copy()
    safe_spots_left[:, 0] -= 1
    safe_spots_left[:, 1] += 1

    safe_spots = np.vstack((safe_spots_right, safe_spots_left))

    return len(intersect2d(np_pawns, safe_spots))


for i in range(2, LIMIT):
    if x[i]:
        primes.append(i)
        length += 1

        for j in range(i * i, LIMIT + 1, i):
            x[j] = 0

This is inconsistent: either i should range up to LIMIT inclusive, or there's no need for j to range up to LIMIT inclusive.

Also, updating length in the loop is overkill. len(primes) outside the loop works just as well and doesn't distract.

There are more advanced ways of doing the sieve with range updates, but that's already covered in dozens if not thousands of answers on this site, so I'll leave it as an exercise to search for one of them.

s = 0
prev = -1
cnt = -1

It's not immediately clear what any of those variable names mean.

        if x[s] and cnt < j - i + 1:
            cnt = j - i + 1
            prev = s

This could be done more elegantly by folding cnt and prev into a tuple:

width_sum = (-1, -1)

...
    if x[s]:
        width_sum = max(width_sum, (j - i + 1, s))

You want the longest, so the fastest approach will usually be to search in decreasing order of length. To keep the bookkeeping simple it may be worth aggregating partial sums:

primes = []
accum = [0]

for i in range(2, LIMIT):
    if x[i]:
        primes.append(i)
        accum.append(accum[-1] + i)

        for j in range(i * i, LIMIT + 1, i):
            x[j] = 0

primes = set(primes)
for width in range(len(primes), 0, -1):
    for off in range(width, len(accum)):
        partial_sum = accum[off] - accum[off - width]
        if partial_sum > LIMIT:
            break
        if partial_sum in primes:
            print(partial_sum)
            exit(0)


Uploading a .csv to a NoSQL cluster - batch faster than consumer/producer

I'm not an expert in cluster operations, so I'll review the parts I do know.

Single-letter variable names

These are a big no-no unless the only thing you're worried about is not being fireable. Any maintenance programmer looking in the middle of a chunk of code is not going to be happy jumping back and forwards to definitions to work out what on earth r is when you could just as easily have written row.

var

You should use var when the right hand side of an assignment makes the type obvious. e.g.

int uniqueIdentifier = 1;

should be

var uniqueIdentifier = 1;

This is recommended because if you decide to change the type (e.g. to a GUID), you only have to change it in one place.

Style

In C# the general naming guideline for methods is to use PascalCase. This is, of course, optional (as with any point on style), but recommended to make code easier to read for another programmer.


Just expose the class types to the user (which they already appear to be) rather than forcing them to use a gawd-awful enum.

public class Module
{
  public string GetXml<TShape>( int id ) where TShape : Shape
  {
    return DB.GetEntity( id ).ToTypedEntity<TShape>().ToXml();
  }
}

The the user can just make a normal call like

new Module().GetXml<Triangle>(34);


Should Domain objects for a public API be able to save/send themselves?

This is a clear setup:

FilingCabinet cabinet = room.getFilingCabinet();
File file = cabinet.get("my-unique-id");
file.setName("my-new-name");
cabinet.store(file);

You can get files from the cabinet, modify the file,
and put the file back into the cabinet for storage.
The cabinet is in charge of storing the file.

This is an unclear, confusing setup:

FileWithSave file = company.getSecretary().getFile("my-unique-id");
file.setName("my-new-name");
file.store();

There is a company.
The company has a secretary.
You can get files from the secretary, modify the file,
and the file can store itself.

The second setup makes me wonder about several things:

Who's in charge of storing the file?
After I do .store(), does the secretary still have the same vision of the file as me?
What if I want to store the file somewhere else? For example, at a different company, or in a cabinet.

In the first setup I don't need to ask such questions,
as the answers are obvious.

Single responsibility principle

Another warning sign is that the second setup violates the single responsibility principle. The FileWithSave is not just a file anymore, it's also in charge of storage.
You might say, that's kind of the point, hence the name file-with-save.
Inheritance is not really about giving additional responsibilities to classes.
The purpose of inheritance is more about specialization.
The best sub-classes do the same things as their parents, just differently.
Giving a file the additional responsibility to save itself seems too much.
Even if this is not inherently a bad design,
you can replace with a better one (the first one), and so you should.

Bad practices

Use interface types instead of implementations.
This is especially crucial in interface definitions.
So instead of this:

public interface PrivateFilingCabinet {
    FileWithSaveImpl get(String id);
    void store(FileWithSaveImpl file);
}

It should have been:

public interface PrivateFilingCabinet {
    FileWithSave get(String id);
    void store(FileWithSave file);
}


I don't know much C++, but your indentation isn't great. To fix this you could try running your code through a C/C++ linter.

Your code is also having a much larger performance hit than if you told your Xorg to do this. Assuming that you only want this to work in Xorg, rather than in both the console and Xorg, you can use setxkbmap as described in the Arch wiki page Keyboard configuration in Xorg. setxkbmap comes with a couple of options to change how your keyboard works, listed under /usr/share/X11/xkb/rules/base.lst. From this list numpad:mac looks like what you want, and will change your keyboard to always use numbers whether numlock is on or not.
And so I would use:

setxkbmap -option numpad:mac


LINQ method that selects an item based on previous one

Linq Zip came to mind in order to map the items in pairs and then apply the predicate.

public static IEnumerable<T> WherePrevious<T>(this IEnumerable<T> collection, Func<T, T, bool> predicate) {
    if (collection == null) throw new ArgumentNullException(nameof(collection));
    if (predicate == null) throw new ArgumentNullException(nameof(predicate));
    if(!collection.Any()) yield break;

    yield return collection.First();

    var items = collection
        .Zip(collection.Skip(1), (previous, item) => (previous, item))
        .Where(zip => predicate(zip.previous, zip.item))
        .Select(zip => zip.item);

    foreach(var item in items)
        yield return item;
}

The following test was used to demonstrate the example given in the original question.

[TestClass]
public class FilterTest {
    [TestMethod]
    public void WherePreviousTest() {
        //Arrange
        var numbers = new[] { 1, 5, 8, 7, 12, 8, 5 };
        var expected = new[] { 1, 5, 8, 12 };

        //Act
        var actual = numbers.WherePrevious((first, second) => second > first).ToArray();

        //Assert
        actual.ShouldAllBeEquivalentTo(expected);
    }
}

The body of the created extension method could have been done on its own, but creating the extension method allowed for a cleaner approach.

While I would say it is easier to read IMO, technically you will be enumerating the list more than once, which makes this not as efficient as your one pass through.

That then lead me to rethink my approach. After reviewing the source code for Enumerable.Zip and realizing your approach had the right idea I refactored the code to use the enumerator of the collection.

public static IEnumerable<T> WherePrevious<T>(this IEnumerable<T> collection, Func<T, T, bool> predicate) {
    if (collection == null) throw new ArgumentNullException(nameof(collection));
    if (predicate == null) throw new ArgumentNullException(nameof(predicate));
    return WherePreviousIterator(collection, predicate);
}

private static IEnumerable<T> WherePreviousIterator<T>(IEnumerable<T> collection, Func<T, T, bool> predicate) {
    using (var e = collection.GetEnumerator()) {
        if (e.MoveNext()) {
            var previous = e.Current;
            yield return previous;
            while (e.MoveNext()) {
                var item = e.Current;
                if (predicate(previous, item))
                    yield return item;
                previous = item;
            }
        }
        yield break;
    }
}

Which actually performed not that much better than the previous suggestion using Zip when run against the same test above.


Accessing UserControl's DataContext from another UserControl

Based on what I understood from your question here are my 5ct.

The MainPage class is the parent class of the LoginClass.

Parents should talk to children by using methods.
Children should talk to parents by using events.

So you should raise an event from the LoginClass to be consumed by the MainPage instead of accessing a property of the MainPage.

In this way you can easily test the code of the LoginForm independently of the MainPage whereas in you current implementation a MainPage always needs to be created before the LoginOperation_Completed() method can be used.

In addition in its current state your implementation has side effects because each time you create a new MainPage the Instance property will be changed.


There are quite a few ways to reduce the number of lines in your program, and improve the readability of your program:

If you want to return a certain number when A and B are empty, use a guard clause.

Personally I'd default to -1, rather than 1.
When building a list, you can use C = [A, B], rather than appending.
You don't need to build an array, to unpack it into a function. itertools.product(A, B) is fine.
The list gcds is the same as the first index of D. It'd be simpler if you just used D.
The lists E and sums are unused, and so should be removed.
The 'comments', commented out code, is generally unhelpful and distract from the algorithm. I'd recomend removing them.
Rather than building a list with D = [] for i in ...: d.append(i), you can use a list comprehension.
Rather than building a list that may take ~2275GB of RAM, you may instead want to use a generator / generator comprehension.
max works on a list of tuples.

And so I'd rather use:

import itertools
import math

def maximumGcdAndSum(A, B):
    if not (a or b):
        return -1
    nums = (
        (math.gcd(a, b), a + b)
        for a, b in itertools.product(A, B)
    )
    return max(nums)[1]

if __name__ == "__main__":
    n = int(input().strip())
    A = list(map(int, input().strip().split(' ')))
    B = list(map(int, input().strip().split(' ')))
    res = maximumGcdAndSum(A, B)
    print(res)

This however is likely to still produce a time limit exceeded error. I'm thinking of a better algorithm.


I could use a review of my sudoku validation

This looks way overcomplicated. There are a lot of solutions on the web, for example:
https://stackoverflow.com/questions/723213/sudoku-algorithm-in-c-sharp

Regarding your code:

You have hard-coded numbers everywhere
Second ctor accepts arbitrary
array and does not check parameter for validity. It can be null or of
any size different from 9


Yes, your class does too much.

First of all, it actually lying: It does not handle one variable as the name of the class suggest, but it does handle multiple variables at once.

Second, I do not like the overloading of the clean method. It is used both for getting a value inside, and for getting the same value back outside. Why are there not two methods?

Third point: Your clean method does too much! It should not be its responsibility to actually decide which filter to apply - this should be the task of a dedicated class that just deals with on single aspect.

Summarizing all this, your list of improvements would be like this:

a) Get rid of the multi-value-behaviour. One class instance per value. If you really need multiple values inside a structure, use a different class.

b) Move the actual filtering out of the class, into dedicated filter elements that do one task very good, but nothing else.

For example, create an "Alphanumeric" class that is configured with the rest of the parameters "3,13,true" that does exactly deal with strings, checks their min and max length and optionally trims them.

Create another class that deals with numeric representation. I doubt it would be useful to check for a string length in this case, but your implementation dictates that it has to be like this. On the other hand, there is no way to implement a min or max value.

The checking class should be passed as a parameter to the constructor of your class Variable, which means that you have to create the checking class beforehand.

c) Passing a string as configuration would then be somehow obsolete, because your new checking classes do not have any other parameters, so giving them four separate parameters isn't likely to overflow the parameter list. But remember that you do not need to make every class' parameter list the same - if some class does not need a configuration value, you can omit it. If another class needs more: Add one.

d) In the end you might come to a point where creating more than one instance of Variable is cumbersome because of all the additional stuff. This is where a factory comes in handy. It would take a configuration array that defines which instances of variable cleaners are needed, instantiates all necessary classes and would probably return an array of Variable objects.

e) One final suggestion: When implementing different classes for basically the same task, use an interface as a type hint to guarantee that you never mix something up. When using an IDE you get code completion as a bonus. :)


Advice on "Factory" Pattern Implementation

I Think you should do it more generic:

public static class Factory
{
    static Dictionary<String, Func<String, Abstract>> classes;

    public static Abstract GetInstance(String s){
        if(!classes.ContainsKey(s)) throw new Exception();
        Func<String, Abstract> create=classes[s];
        return create(s);
    }

    static Factory ()
    {
        classes=new Dictionary<String, Func<String, Abstract>>(){
            {"class1", (x)=>new Class1(x)},
            {"class2", (x)=> new Class2(x)}
        };
    }
}

This code is way more readable.
You have the static constructor block, where you register the factory methods according to the keys. And the GetInstance-Method shrinks to 3 lines, of which one is a purely guarding clause.

Edit: modified after Mat's Mug's hint.

P.S: Oh, I forgot to mention, that you really never should return null.

Better a) throw an Exception or b) use a NullObject.


Determining whether a string ends with one of a few given options

You can LINQify it to improve readability:

bool endsWithOneOf = suffixes.Any(x => value.EndsWith(x));

Note that this doesn't "avoid the loop", since Any() will iterate through the suffixes (stopping when it hits a match.) But that's ok, since how else could you do it? You have an enumeration of suffixes, so to do anything with them, you must enumerate them.


It would be nice to include a link to an authoritative reference. Until then, no comment on the algorithm compliance is possible.
Instead of switch I'd rather have a table of strings indexed by BitcoinAddressState values.
In C, main must return a value explicitly.


Check if an inputted string is in the right format for a valid rgb color

One thing the tests don't indicate is whether space is allowed before/after the color string. I'm inclined to be generous, so I'd suggest just discarding any space before you start:
color = color.strip()

Next, you are doing a lot of work to replace some python built-in functions. Before you do anything else, you should probably read the String Methods documentation to see what tools are available to you.
Try something like:
is_rgb = color.startswith('rgb(')
is_rgba = color.startswith('rgba(')

if not is_rgb and not is_rgba:
    return False

if not color.endswith(')'):
    return False

# strip off prefix "...(" and suffix ")"
color = color[color.index('(') + 1:-1]

You can use .endswith to check for percent signs, also.


Sympy reduction of a multivariate, bounded, under-determined system

You're more running into the limitations of SymPy than anything. Most of the things you are doing should work, they just aren't implemented presently.
Your best bet for solving this kind of problem in a way that is smarter than naive brute force iteration of all possible values is to use the Diophantine solvers:
>>> diophantine(a/(b + c) - 3, t, syms=(a, b, c))
{(3*t_0, t_1, t_0 - t_1)}

This tells you that a solution set is
a = 3*t0
b = t1
c = t0 - t1

where t0 and t1 are arbitrary integers.  Given the form of the solution, it is quite easy to see that for a, b, c to be in the range [0, N], t1 must be in [0, N] and t0 must be in [0, N/3].
>>> N = 10
>>> for t0 in range(0, N//3 + 1):
...     for t1 in range(0, N + 1):
...         a, b, c = 3*t0, t1, t0 - t1
...         if all(0 <= i <= N for i in (a, b, c)) and b + c != 0:
...             print(a, b, c)
3 0 1
3 1 0
6 0 2
6 1 1
6 2 0
9 0 3
9 1 2
9 2 1
9 3 0

Actually in this case, brute force is also fine because there are only N^3 = 1000 combinations, but Diophantine reduced it to only N^2, so that's an improvement asymptotically. There's no need to do it recursively. You can build a substitution dictionary and pass it to subs (like expr.subs({a: 1, b: 2, c: 3})).
You can see the documentation for more information on what kinds of Diophantine equations are implemented. I'll leave it to you to implement the general code to do the above. It really depends on what form your equations take in general as to what their Diophantine solutions will look like, including whether SymPy can solve them at all.


Thread-safe game engine: multi-threading best practices?

I'm wondering about best practices around waiting for threads.

That's too big a question. Instead I'll just review your existing code.

  This is my current implementation, and I'm realizing it's not ideal.

You construct this with a bool async parameter, so that it loads synchronously or asynchronously. There are (at least) two alternatives.

One is to make two derived subclasses:

class Texture
{
    ... etc ...
    virtual ~Texture() {}
protected:
    Texture(const char *filename)
    {
        this->filename = filename;
    }
    static int load(void *data);
private:
    virtual void wait() = 0;
    const char *filename;
}

class SyncTexture : public Texture {
public:
    SyncTexture(const char *filename)
    : Texture(filename)
    {
        load(this);
    }
private:
    virtual void wait() {} // do nothing
};

class AsyncTexture : public Texture {
public:
    AsyncTexture(const char *filename)
    : Texture(filename)
    {
        thread = SDL_CreateThread(load, NULL, this);
    }
private:
    SDL_Thread *thread;
    virtual void wait() { SDL_WaitThread(thread, NULL); }
};

The above is similar to what you might have been suggesting when you talked about a "function pointer": i.e. wait is 'virtual' and called through a so-called vtable.

The second possibility is to do it using templates:

template <bool async = true>
class Texture {
public:
    Texture(const char *filename);
};

This may be faster at run-time, because the value of async is known/fixed at compile-time.

  Convert the "wait()" method in to a function pointer.

I don't understand what you're thinking of when you say this, and you haven't provided the source code for it.

  I've also considered just using the "inline" keyword on the function... but would this include the entire contents of the wait function when all I really need is the "if (thread != NULL)" check to determine whether the rest of the code should be executed or not?

I guess that wait is small and simple enough to be inlined.

The "rest of the code" is only the following ...

{
    SDL_WaitThread(thread, NULL);
    thread = NULL;
}

... and it wouldn't be called if thread is null: so what are you worrying about: the increase in size of your software? I doubt you have enough methods (places where you call wait), such that inlining them would make significant difference to the size of your code.


Matrix multiplication with OpenMP parallel for loop

There is a real problem with your code in that you pass the matrices by copy.

Matrix parallel_mat_mul(Matrix a, Matrix b)

This should really be either passed by reference

Matrix parallel_mat_mul(const Matrix& a, const Matrix& b)

Or implemented through an operator of the Matrix class

operator+(const Matrix& other) const

Nevertheless to better judge this function one would need the implementation of Matrix


HTML or XHTML? Which version? Be clear.

Your file is ambiguous. The usage of the empty element tag syntax <input ... */>* suggests (not mandates) that it's XHTML, whereas the absence of a namespace declaration suggests its not.

I recommend that documents are always clear about whether they're HTML or XHTML. And I recommend XHTML because parsing XHTML is simpler than parsing HTML, and HTML5 is defined in a way that XHTML5 documents are (more or less) a subset of HTML5 documents. The keyword is polyglot syntax.

Maybe in your context it's clear, but there is not sufficient information for us, the reviewers, whether your server would serve it as text/html or application/xhtml+xml.

Note that <!DOCTYPE html> does not sufficiently declare HTML5. The HTML5 specification says that an HTML5 document should have a doctype declaration of the form <!DOCTYPE html>. But it does not declare that everything that has such a doctype declaration is HTML5. It also does not (and cannot) prevent any other specification from also using the <!DOCTYPE html> declaration for some other variant of HTML than HTML5. Furthermore, it permits XHTML5 to also use the very same <!DOCTYPE html> declaration. See this.

I recommend to use the XHTML5 with the polyglot syntax, which is the "common subset" of HTML5 and XHTML5. It is basically HTML5 parsable with an XML parser. I recommend this for multiple reasons.

The parsing rules of XML are simpler, therefore automated processing of documents with tools such as XSLT is simpler / possible with the XML syntax.
You can create DTDs or XML Schemas that further validate your syntax. XML Schema with XML namespaces allows you to validate the mix of different XML-based languages such as for example XHTML and SVG within a single document.

(It's a pitty that the guys of WhatWG are so ignorant towards XML and its capabilities. It's a pitty that the guys of WhatWG had to reinvent the wheel and declare HTML5 as a markup language of its own right besides SGML and XML. That was completely unnecessary and it only confuses people, as we can see with this discussion about the <!DOCTYPE>.)

Declare encoding

It's recommended to always declare the encoding. And the encoding should be declared within the first 1024 bytes.

There are 4 ways how the server can declare the encoding of a (X)HTML document to the client:

HTTP Content-Type header: The server would send something like Content-Type: text/html; charset=UTF-8 or Content-Type: application/xhtml+xml; charset=UTF-8 to the client.
XML declaration (only for XHTML, not HTML), as the first line of the document: <?xml version="1.0" encoding="UTF-8"?>.
Meta element declaring the Content-Type, like this: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> resp. <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
Meta element declaring the Charset, like this: <meta charset="UTF-8" />

See this for more information.

Document Outline

The outline of your document looks like this:

Enter any amount of numbers separated by a comma:

(level skipped)

(empty headline)

I doubt that this outline makes sense.

Keep in mind that
,
 etc. are for headlines. If you just want a paragraph with big text but without the semantics of a headline, use a normal paragraph instead and style it with CSS.

Also, skipping levels is not recommended. For a <h*N*/> element, the next heading should have a level not greater than N+1.

How to declare the scripting language

The correct way to declare the scripting language on a

If you know that the User Agent supports HTML5 or behaves as expected, you can actually omit the declaration of the scripting language:

  The default, which is used if the attribute is absent, is "text/javascript".

The lang attribute is actually meant for describing the content language, like this:

Hi, Hola, Hallo und Servus!

What you did, actually declares the contents of the


Generating a not-the-same-as-last-time random number

Neither option is great. Looking at the second option first (because it is the worst, in my opinion):

int generateRandom() {
    while (true) {
        int randomNumber = random.nextInt(UPPER_BOUND);
        if (randomNumber != lastRandomNumber) {
            lastRandomNumber = randomNumber;
            return randomNumber;
        }
    }
}

This contains a seemingly infinite loop. while(true) is often an indication that there's a better way to do things (not necessarily always, but in this case, yes). The reason it is a problem here is because it gives the impression that the loop repeats often, when, in fact, it seldom repeats ever.

The first block is better:

int generateRandom() {
    int randomNumber;
    do {
        randomNumber = random.nextInt(UPPER_BOUND);
    } while (randomNumber == lastRandomNumber);
    lastRandomNumber = randomNumber;
    return randomNumber;
}

This is better because the loop-terminating condition is much cleaner, more visible. The logic-path through the method is traditional. Still, it's not great. I dislike the need to declare the randomNumber variable as a separate declaration.

The 'while loop' solution would be more readable (even though it duplicates the nextInt() call), as:

int generateRandom() {
    int randomNumber = random.nextInt(UPPER_BOUND);
    while (randomNumber == lastRandomNumber) {
        randomNumber = random.nextInt(UPPER_BOUND);
    }
    lastRandomNumber = randomNumber;
    return randomNumber;
}

Even with the code duplication, it makes it clear that the normal case is handled, and then the while loop is a recovery process.

@Pimgd suggested sending the lastRandomNumber in as a parameter, and @maartinus suggested a single if-block condition rather than a while loop solution. In principle these are both good ideas. There is a way to make it completely reentrant, and also a way to remove the while-loop and the id-conditionals. My solution would be:

int generateRandom(int lastRandomNumber) {

    // add-and-wrap another random number to produce a guaranteed
    // different result.
    // note the one-less-than UPPER_BOUND input
    int rotate = 1 + random.nextInt(UPPER_BOUND - 1);
    // 'rotate' the last number
    return (lastRandomNumber + rotate) % UPPER_BOUND;

}

@mjolka pointed out that if UPPER_BOUND is large, it is possible for the values to overflow in the sum, and that the better solution would be:

return ((lastRandomNumber + rotate) & Integer.MAX_VALUE) % UPPER_BOUND;


Sudoku solving algorithm - Revision needed

This is far too complicated:

for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)):

It is equivalent to this:

[(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]]

More generally, this code feels like it is trying too hard to be clever at the expense of both clarity and potentially accuracy.

Edit:

To answer the question of speed posed by the op:

$ python -m timeit 'sudoku_str="""003020600900305001001806400008102900700000008006708200002609500800203009005010300""";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];b = [(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]];'
10000 loops, best of 3: 68.1 usec per loop

$ python -m timeit 'import itertools; sudoku_str="""003020600900305001001806400008102900700000008006708200002609500800203009005010300""";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];a =[(x, y) for x, y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2))];'
10000 loops, best of 3: 91.9 usec per loop

A simple list comprehension is both clearer and faster.

Here's another example of unnecessary cleverness:

>>> shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3))
>>> shifts
{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}
>>> clear_shifts = {x:(x/3)*3 for x in range(9)}
>>> clear_shifts
{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}


Better way to get the XML attribute value?

You could use the Java XPath API:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource(???); // ??? = InputStream or Reader
String custName = xpath.evaluate("//*[1]/@custName", inputSource);

There is a lot more information in this article: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html


String vs List to check if a country is part of a continent

Option 1 is sloppy.  By that logic, Guinea is a country in Oceania.  The end-of-string delimiters are an important part of the data and cannot be discarded like that.

Moreover, option 2 has a chance of being faster: if the first few characters fail to match, it can skip to the next item.

However, I would say that neither implementation is recommended.  Better solutions include

A simple data structure that allows searching in O(log n) time:

String[] countries = new String[] { "Countries", "in", "lexicographical", "order" };
boolean isPartOfContinent = (0 <= Arrays.binarySearch(countries, "Country1"));

A more complicated data structure that can perform lookups in constant time.

Set<String> countries = new HashSet<String>(Arrays.asList(…));
boolean isPartOfContinent = countries.contains("Country1");

Considering options 3 and 4 are not any harder to write than options 1 and 2, you might as well choose the better-performing options.


Code-wise:

var comedy;
comedy = function(){...};
comedy();

The first two lines can be simplified into var comedy = function(){...}. If you don't need the function to be anonymous, you can even use function comedy(){...};. If this is the only place you are using this function, you can even go for an immediately invoked function expression: (function comedy(){...})() (at which point the name only serves as documentation). Separating the definition from the call may serve code structuring purposes, but I don't see the need to separate the definition and the declaration here.

OOP classes should use UpperCase names, so function DragRacer(...){...}. If I see a function named dragRacer, I don't expect it to be a constructor.

Prototype definitions should be written just after the constructor. Logically, they both are parts of a class definition. Technically, instantiating a class before it is fully defined could be problematic - if the constructor calls some prototype functions, the prototype needs to be defined before the constructor is called.

I am not well-versed in the motor sport industry, but it seems to me the function names rt and et are not very descriptive. You can get away with single-lettered variables used in function bodies (especially if they are math-heavy), but not in public facing method names. The function body can be simplified as well. Clarity will be maintained by the function name:

DragRacer.prototype.reactionTime = function () {
    return Math.random();
};

chrisRT = chrisRT.toFixed(2); -- at this point, you are changing the type of a variable. While the compiler can handle that, you could reduce the developer performance. First, the semantics of a variable are dependent on where it is used in code. While it is not unusual to have variables change their values, here the meaning of the variable changes dynamically. Second, you might need the float value after you need the string value. In this case, you need two separate variables anyways. If you need help naming variables that only differ in types, you could borrow the hungarian notation: strChrisRT = chrisRT.toFixed(2);. The variable name is still somewhat cryptic, but at least you don't have to worry when to convert from float to string.

I am wondering why a drag racer's cocktail is not considered a drink. Blueberry Vodka in lime soda is surely a drink as far as I can tell.

if (chrisRT <= tonyRT) {
    chrisRT = tonyRT + 0.09;
}
console.log(chrisRT);//test
console.log(tonyRT);//test

if (chrisRT <= tonyRT) {
    chrisRT = 0.19 + tonyRT;
}

Here you have some redundant code. After the first condition body executes, the second condition body will not. If the first condition body does not execute, the second condition body will not execute either, because the condition is the same. In effect, the second condition body is a piece of dead code, and can be removed altogether. As a side note, I'm wondering why the constant is the left argument once, and the right argument the second time.

I know the purpose is to cheat, but the business logic here is weird anyways. Let me demonstrate with the following table; especially note the discontinuity around 0.00:

chrisRT - tonyRT | -0.02 | -0.01 | 0.00 | 0.01 | 0.02 || 0.08 | 0.09 | 0.10 |
-----------------------------------------------------------------------------
chrisRT - tonyRT |  0.09 |  0.09 | 0.09 | 0.01 | 0.02 || 0.08 | 0.09 | 0.10 |

from the user interface standpoint, confirms are not very nice. Since you are not using the return value, you could use an alert instead, but, if you want a nice interface, you could turn the code into being event driven and communicating via HTML. confirm("hello") => $messages.append($("<p>").text("hello")) (I am using jQuery, but you don't have to). Especially the initial storyline could be present in the initial document as a plain paragraph with a button that runs the javascript part.

  Chris' favorite drink is Nitro Metane and 83 and 0.19 and 0.09 . "

I know these are only debugging messages, but still... what?


You can create a Question class which include the question, the answers, and the right answer.

Then you create a list of questions hard coded / from file / from server ( what ever you want)

Convert the code in Question 1 to be more generic and work with the Question class.


Tinder-esque location pulse animation effect

Disclaimer: I don't know what Tinder is yet.
Shorter version:

$(document).ready(function () {
    function addCircle() {
        var $circle = $('

');
        $circle.animate({
            'width': '300px',
            'height': '300px',
            'margin-top': '-150px',
            'margin-left': '-150px',
            'opacity': '0'
        }, 4000, 'easeOutCirc');
        $('body').append($circle);

        setTimeout(function __remove() {
            $circle.remove();
        }, 4000);
    }
    addCircle();
    setInterval(addCircle, 1200);
});

I put the addCircle method inside the closure, keeping the
 in a variable means there is no need for an ID or counter x and used setTimeout because it only needs to run once.

http://jsfiddle.net/Y3r36/9/

I like it! Might have made the sizes variable but that could be overkill in this situation. Also it might be a good idea to put a wrapping
 with position:relative in the case you want multiple of these.


You should change this double x=0;double y=1; add newline after first ;
Using ++i is a best practice no matter if the type is int, so use ++i instead i++ and learn difference between them.
change main to int main, It is required to be standard compliant.
Why do you use doubles as x and y. Fibonacci numbers are always integers.
There are many fibonacci algorithms, you can look here

https://stackoverflow.com/questions/14661633/finding-out-nth-fibonacci-number-for-very-large-n

http://fusharblog.com/solving-linear-recurrence-for-programming-contest/


A bash prompt that includes battery level & git branch

Since the prompt is dynamic, executed after every command you enter in the shell, it's important to make it as fast as possible.
For example, reduce the number of processes executed as much as possible.

Instead of git branch + sed, there is an idiomatic way to get the name of the current branch using git rev-parse:

git rev-parse --abbrev-ref HEAD

That's one process instead of two.

And to get the battery percentage,
you could replace the awk + sed with a single awk:

awk '{ sub(",", "", $4); print $4 }'

I don't what is the output of the acpi command,
but I would try to extract from it the relevant part using the Pattern substitution feature of Bash itself.
That would eliminate all external processes, for best performance.


Javascript singleton to notify different objects of changes in viewport size

Here's a simplified version of your code:

var ResizeManager = (function(addEvent, getViewportSize){

  var DEBOUNCE_DELAY = 300;
  var debounceTimer = null;
  var trackedEvents = {};

  addEvent(window, 'resize', function() {
    if(debounceTimer) clearTimeout(debounceTimer);
    debounceTimer = setTimeout(function(){
      Object.keys(trackedEvents).forEach(function(handler){
        handler.call(null, getViewportSize());
      });
    }, DEBOUNCE_DELAY);
  });

  return {
    addAction : function(callback){
      var actionId = ('' + Math.random()).slice(2);
      trackedEvents[actionId] = callback;
      return actionId;
    },
    removeAction: function(callbackId){
      delete trackedEvents[callbackId];
    }
  };

}(addEvent, getViewportSize));

Here's the changes:

Dropped getInstance. Since it's a singleton, let's treat the ResizeManager as the instance, instead of still doing a getInstance step.
Using an object (hash) instead of an array to collect your handlers. The advantage is that you can immediately delete the action by ID instead of having to search for it befor delete.
Replaced your ID generator with a much sleeker alternative.
Naming variables properly, as well as using the constant convention (all caps, underscore-spaced) for constant values.
Calling your function with the context of null. That way, your handlers won't expect a context and potentially do something weird.
Localizing references to the global functions. That way, if ever they get re-assigned a value, you still hold a reference to them.


It's simpler to just return the result immediately then need another method.

Also the caller is probably going to need them as File objects eventually so lets just return them as those.

Then there are 2 options, just return a List and use addAll each recursion step:

public List<File> walkDir(File pathname) {
    if(pathname.isDirectory()) {
        List<File> files = new ArrayList();
        files.add(pathname);
        for(File f : pathname.listFiles()) {
            filed.addAll(walkDir(f));
        }
        return files;
    }else{
        return Collections.singletonList(pathname);
    }
}

Or use a private recursive method where you pass in a accumulator List:

private void walkDirRecurse(File pathname, List<File> files) {
    if(pathname.isDirectory()) {
        for(File f : pathname.listFiles()) {
            files.add(f);
            walkDirRecurse(f, files);
        }
    }
}


Injecting SelectList objects into ViewData to enable using EditorFor on dropdown based properties

I'm assuming this code hasn't been reviewed yet because it's... beautiful - and I'm still searching for a better word. I mean, wow that's clever, I want that!!

The only thing I can see here, is in the View method:

protected override ViewResult View(string viewName, string masterName, object model)
{
    var result = base.View(viewName, masterName, model);
    if ((model is ViewModel) && (!ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists)))
    {
        var vm = (ViewModel)model;
        result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary);
    }
    return result;
}

I would suggest a safe cast instead of model is ViewModel followed by a cast, so it would look more like this - note that I dropped a few redundant parentheses:

protected override ViewResult View(string viewName, string masterName, object model)
{
    var result = base.View(viewName, masterName, model);
    var vm = model as ViewModel;
    if (vm != null && !ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists))
    {
        result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary);
    }
    return result;
}

Other than that, I agree with your naming (except maybe vm could be called viewModel, but vm is pretty descriptive in this specific context) and naming conventions, and there's nothing much left to say as far as I'm concerned - good job! :)


You have a lot of magic numbers in your code which should be extracted to meaningful named constants.

if (Mathf.Abs (angularSpeed) > 0.2f)
if (angularSpeed >= 2.5f) angularSpeed = 2.5f;

  ...

Using braces {} for single statements if or else parts shouldn't be omitted to make your code less error prone.

Unneeded checks should be omitted too like

if (angularSpeed >= 2.5f) angularSpeed = 2.5f;
else if (angularSpeed <= -2.5f) angularSpeed = -2.5f;

should be

if (angularSpeed > 2.5f)
{
    angularSpeed = 2.5f;
}
else if (angularSpeed < -2.5f)
{
    angularSpeed = -2.5f;
}

Don't shorten your variable names because it reduces readability.  E.g

private Animator anim;

should be

private Animator animator;


Another improvement is to use open as a context manager so that you don't have to remember to .close() the file object even if there are errors while reading.

def read():
    with open("FILE", "r") as f:
        array = []
        expected_length = int(f.next())
        for line in f:
            parsed = map(int, line.split())
            array.append(Point(*parsed))
        if expected_length != len(array):
            raise NameError('error on read')
        return array

See http://docs.python.org/2/library/stdtypes.html#file.close for more details.


RPG Skeleton, Part 2 - The Entity, and a SpecType

It's not much code, so there's little else to change or fix here. The only tiny mistake you made was forgetting to mark toString with const, so that it can be called on a const object, very tiny and easy fix:

std::string toString() const;
                       ^^^^^

And the same on the definition. I'm assuming you're already familiar with the meaning of const in a method, but if not, here's an explanation. In summary, a const method is not allowed to mutate the object, only to inspect its member data, thus callable if the object itself is const.

Right now, there's not much reason for the existence of SpecType. In my opinion, it does too little to be a separate class. Assuming you are already extending that class, then it makes sense, but otherwise, it is better to avoid predicting the future and don't bother adding boilerplate classes that end up unused.

The suggestion made by a previous answer to the other question of creating a template class was interesting because each template instantiation has a unique type, so that would prevent, for instance, mixing health with mana because those would be unrelated types. Going that way, then I'd say the template Spec type would be a nice addition, even if just as a tiny wrapper, since it adds type-safety to the code.

Commenting for auto-generated documentation

I get it that some companies really value generating documentation from comments in the code, but take a piece like this one for example:

/// <summary>
/// Constructor for the SpecType class.
/// </summary>
/// <param name="specValue">The value that the SpecType contains.</param>
SpecType::SpecType(int specValue):
    specValue(specValue)
{}

What is that comment adding to the understanding of the code, that couldn't be inferred just by reading the code? Nothing whatsoever. And those XML tags are simply atrocious! They completely distract me from the actual comment text and code.

If you really must comment mechanically to generate documentation, then I'd suggesting using a better tool: doxygen.

Doxygen uses a less invasive markup than those XML tags (actually, you can choose from a few different styles), and more, it doesn't force you to exhaustively comment every method. Methods you don't comment are copied verbatim to the output doc, so obvious things like a constructor don't have to be commented with "this is the constructor for class XYZ".


Backtracking all the words in the English alphabet that have 5 letters, where no 2 consecutive letters can be consonants or vowels

In Python, strings support the sequence interface, so you can write the vowels and consonants as strings, which are easier to read than lists:

vowels = 'aeiou'
consonants = 'bcdfghjklmnpqrstvxz'

Writing out the consonants explicitly like this is risky: it would be easy to omit one and not notice. (What happened to w and y?) It would be more reliable to construct the consonants by subtracting the vowels from all lowercase letters:

from string import ascii_lowercase
consonants = sorted(set(ascii_lowercase) - set(vowels))

Generating the words is very simple if you use the built-in itertools.chain and itertools.product:

from itertools import chain, product
v, c = vowels, consonants
words = chain(product(v, c, v, c, v), product(c, v, c, v, c))

Counting the words is even simpler. If there are \$v\$ vowels and \$c\$ consonants, then there are \$v^3c^2\$ words of the form VCVCV and \$v^2c^3\$ words of the form CVCVC, for \$v^2c^2(v+c)\$ words altogether:

>>> v, c = len(vowels), len(consonants)
>>> v ** 2 * c ** 2 * (v + c)
286650

which is the same as the number of elements emitted by the generator:

>>> sum(1 for _ in words)
286650

You asked, "Is it a good practice to hardcode the permutation of the sets?" Well, good practice is not some magic book of lore, it's the set of techniques that best meet your requirements. In this case, the goal is to answer your algorithms question, so the requirements include things like correct, clear (and so easily marked) and short.

It's never wrong to think about generalizing your code, but you have to balance the cost of the generalization (in terms of more complex code) against the benefits. If you suspect that in the near future you are going to have to generate and count sets of words under other rules about adjacency of vowels and consonants, then generalizing the code now would be a good idea. But if not, there's no point: you can always generalize it later if you need to.


Reusable VBA macro to prevent Excel from destroying the data (+ backup capacity)

Overall, your first program in VBA looks pretty good. I've made some modifications below to illustrate a few points that may help you in the future.

Using Call to call the CreateBackup sub is not necessary and is generally not used much anymore. (However, on a single line like this, I've seen it used to more clearly show that another sub is performing work.)
Indenting your code may have gotten messed up when you posted here to SO, but the code below has each logical level indented to highlight where the different logic paths go.
You re-used cell1 for both the UsedRange and the individual cell value within your loop. That's a big no-no. Use specific names to clearly note what each variable refers, such as thisCell and allCells.
Nearly all the references within your first loop are to thisCell. In this situation, encapsulate the code in a With block. This compiles to a common variable reference without having to reevaluate the fully specified name each time. It also gives you somewhat faster executing code.
Separate your logic into levels to make it easier to follow. In your case, when the cell value is empty and when it's not. Then again when the NumberFormat is not text. It's easy to get lost in a single If statement that has many different parts.
Finally, you're making multiple character replacements at the end and you might encounter other character-pairs that need replacing too. To make your code more easily expandable, the find and replace characters can be added to arrays and accessed in a loop. Only the array assignment would change then.

Option Explicit

Sub PrepareForCSV()
    CreateBackup
    Dim thisCell As Range
    Dim allCells As Range
    Set allCells = ActiveWorkbook.ActiveSheet.UsedRange
    '--- PART 1:
    '    Goal: to accomplish setup described here
    '          http://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates

    For Each thisCell In allCells
        With thisCell
            '--- inserting - sign to avoid blank cells within UsedRange
            '    if the cell is empty...
            If IsEmpty(.Value) Then
                If .NumberFormat <> "@" Then
                    '--- if the format is not text
                    .Value = "=" & """" & "-" & """"
                    .NumberFormat = "@"
                Else
                    '--- if the format is text
                    .Value = "-"
                    .NumberFormat = "@"
                End If

            ElseIf .NumberFormat <> "@" Then
                '--- if the cell isn't empty and not formatted as text
                If InStr(1, .Value, """=") = 0 Then
                    '--- starts with "=
                    .Value = "=" & """" & cell1.Value & """"
                    .NumberFormat = "@"

                ElseIf InStr(1, .Value, """") = 0 Then
                    '--- starts with "
                    .Value = "=" & """" & cell1.Value & """"
                    .NumberFormat = "@"
                Else
                    '--- do nothing?
                End If
            Else
                '--- do nothing?
            End If
        End With
    Next

    '--- PART 2: replace all unwanted characters
    Dim fnd() As Variant
    Dim rplc() As Variant
    Dim i As Integer

    '--- replace characters which may cause errors when csv is imported
    fnd = Array(":", """""", """""")
    rplc = Array("!", """", """")

    For i = 1 To UBound(fnd, 1)
        ActiveWorkbook.ActiveSheet.Cells.Replace What:=fnd(i), Replacement:=rplc(i), _
                                                 LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                                                 SearchFormat:=False, ReplaceFormat:=False
    Next i
End Sub