Using a factory class for TextWriter than can be stubbed/mocked

In dependency injection terms, this factory class has a dependency upon a TextWriter instance. I would much prefer to see that dependency be constructor-injected:

private readonly TextWriter _writer;

public TextWriterFactory()
    : this(new StringWriter())
{ }

public TextWriterFactory(TextWriter writer)
{
    _writer = writer;
}

That way you get rid of the hard-coded default StreamWriter. But there are a number of issues with this approach.

TextWriter being an abstract class is nice, but this abstract class implements the IDisposable interface, which makes it a leaky abstraction to use as a dependency.
The class is still tightly coupled with StringWriter, through the new StringWriter() call in the default constructor. This is actually a DI anti-pattern that Mark Seemann calls bastard injection in Dependency Injection in .NET.
You're dealing with an IDisposable here; I'd expect this test code to throw a rather surprising ObjectDisposedException:

var factory = new TextWriterFactory();
factory.SetWriter(new StringWriter());

using (var writer = factory.Create("C:\foo\bar.txt", false))
{
    writer.Write("append=false");
}

using (var writer = factory.Create("C:\foo\bar.txt", true))
{
    writer.Write("append=true");
}

Let's take a step back here.

Your production code has a dependency that hits the file system.

You need an abstraction to wrap it with, and be able to inject an implementation that doesn't hit the file system, so you can test your code; the simplest abstraction remains an interface - it doesn't tie you up with a base class with embedded behavior that you don't want your tests to have to care for.. or worry about.

I would simply wrap the writer with an interface, with the bare minimum members you need for it to work with your code:

public interface IWriter
{
    void Write(string value);
}

Then I would compose an implementation for the production code:

public class Writer : IWriter, IDisposable
{
    private readonly StreamWriter _writer;

    public Writer(string path, bool append)
    {
        _writer = new StreamWriter(path, append);
    }

    public void Write(string value)
    {
        _writer.Write(value);
    }

    public void Dispose()
    {
        _writer.Dispose();
    }
}

Now you can constructor-inject an IWriter instead of a "factory", and your tests can inject a mock implementation, and the mock can know if the Write method was called with the expected value parameter.

Note that I could have done this too:

public interface IWriter : IDisposable
{
    void Write(string value);
}

But that would have been a leaky abstraction - the fact that we're encapsulating a TextWriter that implements IDisposable shouldn't be leaking into the abstraction, because the TextWriter isn't the abstraction, it's an implementation detail: you could just as well write an implementation that doesn't use a StreamWriter and isn't disposable - for example:

public class FileWriter : IWriter
{
    private readonly string _path;
    private readonly bool _append;

    public Writer(string path, bool append)
    {
        _path = path;
        _append = append;
    }

    public void Write(string value)
    {
        if (_append)
        {
            File.AppendAllText(_path, value);
        }
        else
        {
            File.WriteAllText(_path, value);
        }
    }
}

Now your production code can look like this:

public void DoSomething()
{
    _writer.Write(template.FileContent);
}

public void Dispose()
{
    var writer = _writer as IDisposable;
    if (writer != null)
    {
        writer.Dispose();
    }
}

Now, regarding the usability of this code, there's still an itchy spot: I put the string path, bool append parameters in the constructor, because you had them in your Create "factory method".

Ideally you would make them parameters of the Write method: injecting primitives through the constructor is pretty much always a smell.

Also note that C# conventions place the { opening brace on the next line.


Executing a program with a temporary directory and measuring the running time

Well, firstly, don't be afraid of empty lines. This code is quite hard to read.

Secondly, functions is good invention. ;) That code as it is now is a bare piece of code, with no indication of where most of the parameters come from, and it seems that the acceptable solutions is a global, as you have capitalized it? That doesn't make much sense to me.

Just as you have a function called run() to run the program, it would make sense to have a function to run it multiple times, with the tests for that you have.

I'm also not sure why you trap KeyboardInterrupt, without seeming to actually do anything with it, except setting the status, and then testing the status. You could just do exit directly from that exception handler, that would be clearer.

Otherwise it seems fine. Feedback on correctness is impossible when your code isn't a running example. But then again, tests generally work better than code reviews there, although they are not exclusive.


I'm no expert in performance optimization or even threads, so my code review will mostly be some style suggestions, but I do have suggestions how I would implement the the phrase building to be faster - purely from my gut :-)

A nitpick at the beginning: You should try and clean up your indentations. They are all over the place and make reading the code a bit more difficult
You should declare variables to use interfaces where appropriate instead of concrete class. That makes the code more flexible for example in case you get the keys for a different source. In your case declare your map as Map<String,List<String>>.
Avoid global variables. If would be better to have addKeys return the map (and thus be renamed readKeys) and pass it on to parseString as an argument.
In the main function a for loop is probably more appropriate instead of the while.
Try to get rid of the duplicate scan.nextLine(); in the inner while loop, by moving the exiting condition inside the loop.

Now to optimizing the phrase building. There are two main points I would consider here:

Avoid copying data. Currently you convert your string with the placeholders into a StringBuilder and insert the text in place of the placeholder. Both creating the StringBuilder and inserting into them requires allot of data copying internally.
Don't repeat the parsing of the placeholder text. Instead I would parse the text once into a data structure and then generate the random phrases using that structure.

I could write some (pseudo) code to demonstrate, what I mean, but you should be writing it yourself, so I'll wait and see, if you can come up with an implementation based on those two points.


Why does caching of string objects perform faster?

Why skimp on braces?  Putting braces around the if-block in generateString() costs you almost nothing — not even an extra line of code.  Make it a habit to always include explicit braces so that you never write a disaster like this.  (Don't think that it can't happen to you!  Accidents often have more than one contributing factor — so don't be a contributing factor.)

private static String generateString1() {
    String str = new String("abc");
    if (cache.containsKey(str))
        return cache.get(str);
    else {
        cache.put(str, str);
        return cache.get(str);
    }
}

That could be better expressed as:

private static String generateString1() {
    String str = new String("abc");
    if (!cache.containsKey(str)) {
        cache.put(str, str);
    }
    return cache.get(str);
}

If you really don't like braces, putting the action on the same line as the if could also be acceptable:

private static String generateString1() {
    String str = new String("abc");
    if (!cache.containsKey(str)) cache.put(str, str);
    return cache.get(str);
}


GenerateMasterCode
I would break the GenerateMasterCode() method into two methods and would declare the Random as a static field tof the class.
From the Random documentation:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.

Instead of using a char[] to generate the random characters I would use a StringBuilder.
public static string GenerateMasterCode(string startString, int mastercodeLength)
{

    if (startString.Length == masterCodeLength) { return startString; }
    if (startString.Length > masterCodeLength) { return startString.Substring(0, masterCodeLength); }

    return startString + GenerateRandomCharacters(masterCodeLength - startString.Length);
}

private static Random rd = new Random();
private static string GenerateRandomCharacters(int length)
{
    string numericChars = "X123456789";
    int length = numericChars.Length;
    StringBuilder builder = new StringBuilder(length);
    for (int i=0; i < length; i++)
    {
        builder.Append(numericChars[rd.Next(length)]);
    }
    return builder.ToString();
}

GenerateMasterCodes
Right now you query in the while loop all of the MasterCodes although you are only interested in the Campain related MasterCodes. So you should query the MasterCodes which belongs to the Campain before you start with the for loop.
Assigning false to Used can be omitted, because that is the default value of bool.
You can use the var type for the List<MasterCode> as well.
If you don't use that method outside of the class you should consider to make it private.
public static void GenerateMasterCodes(GenerateMasterCode model)
{
    using (ApplicationDbContext _context = new ApplicationDbContext())
    {
        Campaign campaign = _context.Campaigns.Find(model.CampaignId);
        var campainRelatedMasterCodes = _context.MasterCodes.Where(m.CampaignCode == campaign.CampaignCode);
        var masterCodes = new List<MasterCode>();
        for (var i = 1; i <= model.Count; i++)
        {
            var masterCode = new MasterCode
            {
                CampaignId = campaign.CampaignId,
                CampaignCode = campaign.CampaignCode,
                SubmittedOn = DateTime.Now
            };

            // Ensure that no code already exists for that campaign.
            var code = GenerateMasterCode(model.StartString, model.CodeLength);

            while (campainRelatedMasterCodes.Any(m => m.Code == code))
            {
                code = GenerateMasterCode(model.StartString, model.CodeLength);
            }
            masterCode.Code = code;

            masterCodes.Add(masterCode);
        }

        try
        {
            _context.MasterCodes.AddRange(masterCodes);
            _context.BulkSaveChanges();
        }
        catch (Exception ex)
        {
            ...
        }
    }
}


Code to print even and Odd number using two threads

If the only requirement is to have two threads, one printing even numbers and other printing odd numbers, then your solution is unnecessarily complicated. The fact that you share the same data model for both threads forces you to synchronize access to the object making the solution unnecessarily complicated. The assignment did not require numbers being printed in sequence, so the coordination between the threads is unnecessary.

public class Counter implements Runnable {
    private final int start;
    private final int end;
    private final int increment;
    ... add boilerplate constructor ...
    public void run() {
        for (int i = start; i <= end; i += increment) {
            System.out.println(i);
        }
    }
}

Start threads:

new Thread(new Counter(1, 10, 2)).start();
new Thread(new Counter(2, 10, 2)).start();


Take element of a Set collection depending on the value of another element

I think it's pretty messy and inefficient

Let's say that it is getting messy, especially if the number of parameters (and hidden rules) keeps growing.
About being inefficient, I am not sure. Even if the input is very large, the method populateServiceConfigurationData runs in \$O(N)\$, so I don't think it will be a big problem.
My suggestions:

Readability: setting the quantity of the service depends on more than one parameter. So the "rule" to set quantity would be more evident if included in a single function, like setServiceQuantity.
Performance: the input set can be converted to a map, to easily access the parameters. The performance gain is minimal, but it should help to make the code more clear.
Design: using setFieldValue in populateServiceConfigurationData seems unnecessary. The method populateServiceConfigurationData can be completely independent to setFieldValue. More on this later.

public void populateServiceConfigurationData(Service service, Set<ConfigurationMap> configurationParams) {
    // Convert the input set to a map
    Map<String, String> params = configurationParams.stream()
            .collect(Collectors.toMap(ConfigurationMap::getKey, ConfigurationMap::getValue));

    if (params.containsKey("type")) {
        service.setType(Integer.valueOf(params.get("type")));
    }

    if (params.containsKey("gateway_id")) {
        service.setGatewayId(params.get("gateway_id"));
    }

    if (params.containsKey("comissions")) {
        service.setCommissions(params.get("comissions"));
    }

    setServiceQuantity(service, params);
}

private void setServiceQuantity(Service service, Map<String, String> params){
    boolean isPublishService = params.get("type").equals("20");
    String quantity = isPublishService ? params.get("publications_amount") : params.get("service_quantity");
    service.setQuantity(Integer.valueOf(quantity));
}

(Note: not tested, it's just to give an idea)
Now the logic for setting each property of the service is clear and can be easily extracted into functions like setServiceQuantity.
One issue is that populateServiceConfigurationData needs to know how to set the properties into the service (for example, parsing type to Integer). If you don't like this approach, the setters can be replaced with setFieldValue (as before) or let service do the parsing in its own methods.
The method setFieldValue looks fine, the only thing I can suggest is to use else if since only one condition will match per invocation.


Is This a Sufficient Demonstration of the Effects of Exception Handling

The while loop you are using is impacting performance.  Sleep that check a bit beforehand to give your scenarios some time to think.

do { Thread.Sleep(3000); } while (!tasks.All(t => t.IsCompleted));

You may want to suggest some best practices reading to your team, throwing an exception should be reserved for an exceptional circumstance.  Use of the throw for rethrowing an exception is correct to keep the stack trace information complete, but again, should be seldom and when they do finally bubble up to the top, the exception information should be captured in a way that they are not just ignored.

http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx

https://stackoverflow.com/questions/409563/best-practices-for-exception-management-in-java-or-c

http://www.codethinked.com/how-do-you-deal-with-exceptions


jQuery plugin for easy CSS3 transformation

I like the demo, from a once over:

the functionNames make my eyes glaze over, data tables variables should be sorted and tabbed in my mind:

  var functionNames = [
    { name: "matrix",      type: functionParamTypes.length},
    { name: "matrix3d",    type: functionParamTypes.length},
    { name: "perspective", type: functionParamTypes.angle },
    { name: "rotate",      type: functionParamTypes.angle },
    { name: "rotate3d",    type: functionParamTypes.angle },
    { name: "rotateX",     type: functionParamTypes.angle },
    { name: "rotateY",     type: functionParamTypes.angle },
    { name: "rotateZ",     type: functionParamTypes.angle },
    { name: "scale",       type: functionParamTypes.number},
    { name: "scale3d",     type: functionParamTypes.length},
    { name: "scaleX",      type: functionParamTypes.number},
    { name: "scaleY",      type: functionParamTypes.number},
    { name: "scaleZ",      type: functionParamTypes.length},
    { name: "skew",        type: functionParamTypes.angle },
    { name: "skewX",       type: functionParamTypes.angle },
    { name: "skewY",       type: functionParamTypes.angle },
    { name: "translate",   type: functionParamTypes.length},
    { name: "translate3d", type: functionParamTypes.length},
    { name: "translateX",  type: functionParamTypes.length},
    { name: "translateY",  type: functionParamTypes.length},
    { name: "translateZ",  type: functionParamTypes.length}
  ];

It is preferred to have 1 single comma-separated var statement:

var $this = $(this),
    existingTransformation = $this.css("transform");

It is preferred to have either all single or all double quoted strings, I would suggest single quoted strings
You have some missing and some unnecessary semicolons, please check out http://jshint.com/
Other than that, a fun piece of code


+ (double)runProgram:(id)program usingVariables:(NSDictionary *)variables {
    NSMutableArray *stack;
    if ([program isKindOfClass:[NSArray class]]) {

Checking the type of incoming parameters is a little suspicious. Do you really want to allow other parameters and just ignore them?

        stack = [program mutableCopy];

This process would actually be easier if you didn't create a copy, but instead create an empty NSMutableArray and add the filtered objects to it.

        for (int i=0; i<stack.count; i++) {

Presumably, you are using this because you need the indexes to replace the objects. If you stop making a copy, you should be able to replace this a foreach loop over the program.

            /* replace variable values with NSNumber values */
            NSNumber *variableValue = [variables valueForKey:[stack objectAtIndex:i]];
            if ([variableValue isKindOfClass:[NSNumber class]]) {

Again why are you checking types? Are there other things besides numbers in your variables? If there are, do you just want to ignore them?

                [stack replaceObjectAtIndex:i withObject:variableValue];
            }
            /* all variables should be replaced now */

This comment isn't true here, because its on the wrong side of the brace

        }
    }
    return [self popOperandOffProgramStack:stack];
}


users.toString().contains(user1)

This is not a very optimal way of checking if a user from the file is in your users object. For starters, ArrayList.toString() will generate the String representation every time, and you may run into false positives. For example, if the toString() representation of a TwitterUser contains a comma, which is the delimiter used by ArrayList:

String user1 = user1.toString(); // = "John, Doe"
String user2 = user2.toString(); // = "Jane, Doe"
// Just to make sure we are using the ArrayList implementation
List<String> users = new ArrayList<>(Arrays.asList(user1, user2));
String allUsers = users.toString(); // = "[John, Doe, Jane, Doe]"
allUsers.contains("Doe, Jane"); // = true

Sure, you are actually comparing numeric values, but consider this then:

String user11 = user11.toString(); // = "11"
String user22 = user22.toString(); // = "22"
// Just to make sure we are using the ArrayList implementation
List<String> users = new ArrayList<>(Arrays.asList(user11, user22));
String allUsers = users.toString(); // = "[11, 22]"
allUsers.contains("1"); // = true

The point here is that ideally, your TwitterUser class should be constructed first so that you can use one of its method to test for equivalence, using equals(Object) for example:

public class TwitterUser {

    // ...

    public boolean equals(Object o) {
        // assuming id is a primitive value
        return o instanceof TwitterUser && ((TwitterUser) o).id == id;
    }
}

Again, you should avoid using toString()-based comparison below for testing equivalence due to the 'false positives' point. Furthermore, you should not skimp on braces ({ ... }), and break early once you have a match:

for (TwitterUser i : users) {
    TwitterUser twitterUser = // ...
    if (i.equals(twitterUser)) {
        target = i;
        break;
    }
}

Hold your horses! If you have implemented TwitterUser.equals() to compare by the ID, you wouldn't even need the for-loop:

TwitterUser user = new TwitterUser(Integer.parseInt(user1));
if (!users.contains(user)) {
    users.add(user);
    user.follow(new TwitterUser(Integer.parseInt(user2)));
} else {
    TwitterUser currentUser = users.get(users.indexOf(user));
    currentUser.follow(new TwitterUser(Integer.parseInt(user2)));
}

To make the performance better, you can consider using a Set instead of a List.

To avoid the huge nested if-block after if (file.exists()), consider return-ing early:

public void open() {
    if (!file.exists()) {
        return;
    }
    try {
        // ...
    }
}

Ideally, the File object should be passed to this method so that the method callers know what exact file is being opened here.

edit: If you claim that the processing still tends to infinity, consider reworking your process:

Read all the lines from the file (even if it runs into the millions, it's just two numbers per line).
Use a number of background threads to process the lines concurrently. You'll need a Runnable/Callable implementation, an ExecutorService and a thread-safe Collection implementation. This is probably more suited for another question/answer though...


Use DateTime::createFromFormat method to convert datetime strings to DateTime object:

$date1 = DateTime::createFromFormat('Y-m-d H:i', '2013-09-30 14:20');
$date2 = DateTime::createFromFormat('d/m/Y Hi', '30/09/2013 1420');

Now you can just format your output:

echo 'unix  : ' . $date1->format('U') . "\n";
echo 'human : ' . $date1->format('Y-m-d H:i:s') . "\n";
echo 'dst   : ' . $date1->format('I') . "\n";

And you don't need to adjust timestamp for +1 hour if in DST, DateTime can handle leap years and DST correctly. Set timezone when you create DateTime object, or change timezone after.


Create an object when you need it! in PHP

Your App class seem too broad in purpose.  Right now it:

Acts as a sort of global key-value store.
Acts as a registry of "core" classes used in an application. Something typically just offloaded as an autoloading consideration in modern PHP applications.
Acts as a factory/provider for core class instances. Something that will become extremely unwieldy as your application grows in classes, each with their own sets of dependencies and logic around how they need to be set up.

It almost looks like what you are trying to do is build a dependency injection framework container, however the implementation is slightly off in that you are injecting the entire container into consuming classes rather than using the container to store instantiation logic for dependencies.  That later apporach might look something like:

// set up and configure container
$container = new \System\App();
$container->register('database', function($cont) {
    return new \System\Database();
});
$container->register('user', function($cont) {
    return new \System\User($cont->get('database'));
});

// get user, which would also instantiate new database object if needed
$user = $container->get('user');

If this is truly what you are trying to do, then I would recommend you take a look at popular PHP dependency injection frameworks/containers like PHP-DI or Pimple either for direct use in your applications or for inspiration on how you can approach the problem.

From a global key-value store standpoint, it is hard to understand how this is actually used in your application from what is shown and unclear what value it really has.

What is stored here? If application configuration, should you really provide the level of mutability you do? Would you better be served to have an immutable configuration class that exposes these values?

If storing key-values that are going to be consumed in classes, why not move these items into those classes where you can better enforce class-specific validation rules for setting these keys? Do you really need the flexibility provided by this functionality and the fragility problems this flexibility can introduce?

I would think it trivial to split this portion of functionality away from App if you decide this store truly gives you some value that is not apparent from the code shown.

I don't agree with the approach of injecting this App object along with every single potential instantiated dependency it holds into every consuming class that might need one of the dependencies.  It makes it more burdensome in consuming classes to validate that the dependency you need is actually passed.

For example, say you had a class that needs a PDO object.  A good dependency injection model might look like this:

public function __construct(\PDO $pdo) {
    $this->pdo = $pdo;
}

You enforce the dependency through type-hinting, allowing you to not have to write validation code in your class. Your class gets it's dependency in a proper state.

VS. your current approach which might require validation such as:

public function __construct(\System\App $app) {
    if($app->db instanceof \System\Database === false) {
        throw new Exception('...');
    }
    // validate other dependencies here
    // set dependencies on object as needed
    $this->app = $app;
}

You also obfuscate dependencies to someone reading/working with your classes. With the approach I suggest, the exact dependencies of the class are explicitly stated in the constructor method signature (or in other method signatures if you have static methods or load dependencies after instantiation for some reason). If someone needs to add functionality to the class that requires a new dependency, you actually have to add that dependency to the class.  This may seem like extra work, but, in fact, it is good coding behavior in that you have to be thoughtful and specific in how you consume dependencies.  You avoid someone just introducing new dependencies in your classes by simply adding calls against not-previously-used dependencies stored in App.

So, if you resolve that injecting every dependency that could possibly be needed into every class is not the way you want to go, you can then address the problem with your provider/factory behavior.

If you wanted to only pass required dependencies to consuming classes, your createNewObj() method would quickly become overly complex (it might get this way even with your current dependency injection approach if you need more complex instantiation logic for given classes).

You could imagine some horrible switch construct like:

private function createNewObj($key)
{
    switch($key) {
        case 'user':
            return new \System\User($this->get('db'));
            break;
        case 'db':
            return new \System\Database();
            break;
        // and so on
    }
}

This obviously would be a bad approach.  So how should you approach this?  Each class should have it's own mechanism for instantiation, whether that be a static method on the class itself, or whether it be a wholly separate factory or provider class.

To address the use case in your usage example.  That might look like this:

$users = UserProvider::getAllUsers($database);

Or under DI container approach:

$users = $container->get('users');

Some other thoughts:

Should App::share() be called set()?  This seems like what is happening.
Your App class singleton behavior is improperly implemented. You need a protected/private constructor or perhaps constructor that throws exception to prevent caller from instantiating the class directly.
There is nothing in your App class that can switch between singleton-type behavior for some classes vs. concrete behavior for others.  This would for example only allow a single User object to be created, which may or may not be desired behavior for your application (as it is unclear what User does).
Speaking of which, is User class properly named, or is this actually a provider class? It only has one method, which would seem to return a collection of users, not a singular user.  Should this class even have concrete context?
Don't die() in the middle of your App class, and especially don't die() with message to standard out.  The way this class is designed, you have no idea where it is being used in overall application context.  The code up the call stack is likely more better positioned to handle the error and provide meaningful end user messaging.  Consider using exceptions with this kind of functionality that is so core to your whole application framework.
You have unnecessary nesting in your App::get() method.  Unnecessary conditionals and nesting can lead to more fragile code.

Consider an approach like:

public function get($key){
    if (!$this->has($key) && !$this->isCore($key)) {
        throw new OutOfRangeException('Some message');
    }
    if (!this->isCore($key)) {
        $this->share($key,$this->createNewObj($key));
    }
    return $this->storage[$key];
}

This example also creates an early exit from the function or code path, which is almost always a good thing. Fail fast and fail loudly.

Why are your core classes defined inside a method instead of in class configuration (i.e. class constant), or better yet, in application configuration.  Look at those DI container framework examples I have shown, there is nowhere in there where they are hard coding the classes available to an application.
You are not really doing any validation against parameters passed to your public methods, which for a class as central in your application as this, might be problematic. What if invalid key values are being sent to share()?
$opj = $coreClasses[$key]; Is $opj a good variable name here?  This is really a class name right?
You should consider getting out of the habit of using SELECT * in queries against the database.  This approach oftentimes pulls across more data than necessary (for example if table has timestamps fields or other fields that are not meaningful in wider application context) and it also makes your code potentially fragile to table schema changes.


Indenting a function to recursively find filenames

A good way would be to eliminate duplicate using a default callback that does nothing:

def walker(root, pattern):
    for _, _, files in  ((root, _, (os.path.join(root, filename)
        for filename in files if fnmatch.fnmatch(filename, pattern)))
        for (root, _, files) in os.walk(root)):
            for filename in files:
                yield filename

def find(root, pattern, callback=lambda v:v):
    for filename in walker(root, pattern):
        yield callback(filename)

Afterwards, we simplify the walker to

def walker(root, pattern):
    for (root, _, files) in os.walk(root):
        for filename in files:
            if fnmatch.fnmatch(filename, pattern):
                yield os.path.join(root, filename)

and have a much more readable thing than before.


I'm no security expert, not even close, but I can tell you what I use and have observed. I only use cookies to remember the username. Cookies aren't secure so you want to limit what you save in them. I also use sessions to create persistence by passing the user object on. Is this the right way? I don't know, but it has served me well and does not contradict anything I have read on the subject. As for auto-login, you can do something similar to what SO does. You can create a client side cookie with a unique ID and pair it to an account. If the login computer has that cookie then you can have it automatically login. An added security feature might be to also match IP addresses. Not sure if this is exactly what SO does, but its similar. Again no security expert, so I would gather more opinions and do your research.

If you are going to provide comments about a function then you should use doccomments as they are more useful in that IDEs can recognize them and provide them as auto-complete hints. Additionally, I would not use single letter variables except for incrementals or throwaways. The abstraction can lead to confusion if you are not careful and it makes it more difficult to tell what is going on at a glance.

/** this function is called after sanitizing the user-input
 *
 * @param string $user is username
 * @param string $pass is password
 */

As tsabz pointed out, you should never use globals. They are evil and have no place in this world. Help banish these foul demons by forgetting you ever heard of them. Especially don't use globals for something as important as a database connection. It is insecure. If you must use a variable in a function, then inject that variable into the function via the argument list. In this case that would add a very large list, so you might instead want to compact those values into an array and inject the array instead. However, I'll point out in a few that some of these variables are unnecessary, which will decrease the size of said list.

If you are returning from an if statement, then there is no reason to have an else statement, the else is implied. I would remove it to reduce the amount of indentation, however that is really a preference point and entirely up to you.

if( $q->num_rows == 1 ) {
    //etc...
    return TRUE;
}

//etc...
return FALSE;

There are a couple of different things you can do instead of using $current_user as a global. The easiest way would be to convert it to a session variable so that it can be shared. Another, more practical way would be to return the user object instead of a boolean and then later persist it if necessary. This later method makes sense for a number of reasons. First, it goes along with what the function says it is doing. By signing in I expect either a user object or a failure, not a TRUE/FALSE. Second, it allows you to do away with $signin_stat and $incorrect which were both redundant. You could accomplish the same thing with the boolean return (to illustrate: if( signin() ) { $signin_stat = 1; }). Third, it allows you to change how you persist the user object so you are not reliant on sessions.

$_SESSION[ 'current_user' ] = new User( $uid );
//or
if( $q->num_rows == 1 ) {
    //etc...
    return new User( $uid );
}

//etc...
return FALSE;

Always, always, always use braces. I know it is a feature and you can get away with it, but it can be confusing and can cause issues, especially if you combine two statements on one line like that. Not that an if/else statement is even necessary here. If you want to return a boolean value based on the return of an expression, just return the expression. Here it is a little different because there is no comparison to make this a true expression. Instead you are relying on PHP to automatically convert it to a boolean for the comparison. So you might want to typecast it in the return to get a true boolean.

//braces
if( $q ) {
    return TRUE;
} else {
    return FALSE;
}
//equivalent to above
return ( bool ) $q;

Some of this code is violating the "Don't Repeat Yourself" (DRY) Principle. As the name implies, your code should not repeat itself. If you look at your login function and compare it to your auto-login function you should be able to see the similarities. You could create a new function that accomplishes the shared task, but because you are using regular functions this would make bypassing the normal signin function a security concern. I don't really see a way around this, except to convert to using a class, which is something you might want to consider anyways. Many of the issues I pointed out above would be solved much easier in a class. For instance, you could convert those globals to class properties to the same effect. Then there is also the encapsulation that will allow you to hide properties and methods, such as the $conn property and shared login method I was mentioning. I'm not trying to pressure you into using a class, but I am suggesting you give it a look. Hope this helps.


PHP implementation of "depth-first search" on the graph data structure

It's totally unnecessary to have a Bag class if all you do is reach through to its only field.

Generally, all your classes should either have multiple fields or engage in some kind of non-trivial validation or data-hiding to justify the necessity for a class.


Space and time complexity of operation on lists

scaleV

scaleV is very similar to fmap, it just has different precedence in its arguments, the following definition is simpler and highlights this similarity:

scaleV = (fmap .)

Guards

While they have the same effect of conditionals, they are preferred because they are extensible and nicer to read:

addV v1 v2 = if length v1 == length v2 then Just $ zipWith (+) v1 v2 else Nothing

Becomes:

addV v1 v2
  | length v1 == length v2 = Just $ zipWith (+) v1 v2
  | otherwise = Nothing


There are a number of things that could be improved in this code.

Post complete code

I understand that this code was migrated from Stack Overflow where the rules are a little different, but here on Code Review, we want to see not just one small piece but the whole code.  I can guess what checkEveryting() and solver() might do, but you'll get better reviews here by not making reviewers guess.

Use a better algorithm

The fundamental problem with this code is that the algorithm is very inefficient.  Look at the Related panel to the right and you'll see more than a half dozen other similar programs.  Look over those to get ideas about how this might more efficiently be done.

Make the formatting consistent

The code currently include this:

  if (counter == 81)
  {
    return true;
  }

  if (counter > 200 || counter < -10) {
    return false;
  }

In one case, the opening { is on the same line, and in the other it's on the next line.  It's a small thing, but it's useful to choose a convention and stick with it.

Avoid the use of global variables

I see that counter and board are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable.

Use meaningful variable names

The variable names a, and b are not at all descriptive. Better naming makes your code easier to read, understand and maintain.

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, b is declared but never actually used.  My compiler also tells me that.  Your compiler is probably also smart enough to tell you that, if you ask it to do so.


What is the better way to retrieve value from this cache implementaion?

You could change your CacheUtil class to the following:

public class CacheUtil {
    ...
    public void addCacheEntry(String key, Serializable entry) {
        //add to cache
    }

    public void removeCacheEntry(String key) {
       //remove from cache
    }

    public <T extends Serializable> T getCacheEntry(String key) {
       T entry = // get from cache (probably needs a cast to T)
       return entry;
    }
}

which would allow you to get cached entries by type T without a cast:

    public List<String> fetchList() {
       ArrayList<String> aList = CacheUtil.getInstance().getCacheEntry("aList");
       if(aList == null) {
         aList = fetchFromDB():
         CacheUtil.getInstance().addCacheEntry("aList", new ArrayList<String>(aList));
       }
    }

Notice that I was required to use ArrayList, because List is not Serializable on its own.  You could take this one step farther and have getCacheEntry() return T without extends:

    public <T> T getCacheEntry(String key) {
       T entry = // get from cache (may need a cast)
       return entry;
    }

But Im not sure I'd take that leap.


Spring MVC dynamically adding form elements

Use interface List instead of concrete class for the fieldArrayList
field.
Make the fieldArrayList field private.
@RequestMapping(value="/create", method= RequestMethod.GET). Requests using GET should only retrieve data, not create.
Extract the calls of hsr.getParameterValues and hsr.getParameter methods in separate methods.
Don't use meaningless variable names such as d, s1, s2.
Format code with your IDE. For example, in IDEA you can use the Ctrl+Alt+L hotkey.
Extract attribute and parameter names in constants.
@RequestMapping(value="/create", method=RequestMethod.POST) can be replaced with @PostMapping("/create").


The simplest implementation that comes to my mind would keep the list split into two parts: One the already traversed points in reverse order, so that we can easily backtrack, and rest of unvisited points:

giftWrap :: [Vector2] -> [Vector2]
giftWrap (a:rest) = gw [] a rest
  where
    gw [] b (c:xs) = gw [b] c xs         -- beginning - just add the first point
    gw as@(a:as') b cs@(c:cs')
        | TurnRight <- turn a b c   = gw as' a cs      -- backtrack
        | otherwise                 = gw (b:as) c cs'  -- advance
    gw as b [] = reverse (b : as)

At the end, we need to reverse the result (unless we don't mind having the points reversed).

There is no need to check the case of the first point in the list, as it's always chosen so that it's a left turn.

Using pattern guards simplifies the call to turn.

I also added a small snippet that uses Test.QuickCheck to test the algorithm:

vectors :: Gen [Vector2]
vectors = nub <$> (listOf1 $ Vector2 <$> r <*> r)
  where
    r = fromIntegral <$> choose (-2 :: Int, 2 :: Int)

gwconvex_property :: Property
gwconvex_property = forAllShrink vectors (shrinkList shrinkNothing) $ \xs ->
    let rotate (x:xs) = xs ++ [x]
        vs = hull xs
        vs' = rotate vs
        vs'' = rotate vs'
    in counterexample ("Input: " ++ show vs) $
       counterexample ("Chained: " ++ show (chain vs)) $
       conjoin $ zipWith3 (\a b c -> turn a b c /= TurnRight) vs vs' vs''

main = quickCheck gwconvex_property

Note that the original implementation of giftWrap fails the test, either with

  Non-exhaustive patterns in function giftWrap'

or producing non-convex result, but I didn't have time to explore the details.


Reading and debugging your code and two other answers pops up. (And a third one popped up while writing this answer)

There's a whole lot to say about your code. I will provide comments about your existing code and also comment about a different way to think about the problem.

You have a whole lot of commented code, and you don't write why it has been commented. Either way, I would recommend removing all your commented code before putting it up for review.

The //needs a fix comments here almost made me close the question for not being working code. Your code works (even though it is inefficient) so remove all such commented code:

                /*
                 * if(psuedoIndex == array.length){ //needs a fix. as we
                 * have reached the end of the array. //currentArray[j] =
                 * array[psuedoIndex-1]; currentArray[j] = 0; break; } else{

        if(in ==0){
            tempArr[i] = arr[i];
        }
        else{
            tempArr[i-in] = arr[i];
        }

There is no need to treat in ==0 as a special case here. Your else can take care of that as well. Replace all this with:

tempArr[i-in] = arr[i];

            currentArray = new int[i + 1];
            currentArray = new int[i+1];

Please use consistent spacing. And this applies to all your code. I recommend using spaces around + signs and such.

Compare

for (int j = 0; j <= i; j++) {

vs.

for(int i=0;i<array.length;i++){

I prefer the first version. No need to make code too compact. Itwillonlymakeithardertoread (right?).

if((sum = calculate(currentArray))>largestSum){

Sure, this works, but I think it would be more readable by splitting it on two lines.

int sum = calculate(currentArray);
if (sum > largestSum) {

private int calculate(int [] currentArr){

Non-optimal spacing in both the method declaration and method body.
Unclear method name. calculate what exactly? Rename it to calculateSum, please.
Perfect use-case for a for-each loop.
Here's what I would do:

private int calculate(int[] currentArr) {
    int sumOfElements = 0;
    for (int value : currentArr) {
        sumOfElements += value;
    }
    return sumOfElements;
}

for(int k=0;k<currentArray.length;k++){
    System.out.print(currentArray[k] + "|");
}

There is a Arrays.toString method, use it.

System.out.print(Arrays.toString(currentArray));

A different approach

You're using way too many for-loops for my taste.

Consider your starting array:

int[] array = {-5,1,-3,7,-1,2,1,-4,6};

It starts with a negative number, and as you want to find the sub-array with the largest sum, there's no need to start counting on a negative number.

So, skipping that one we have these left:

int[] array = {1,-3,7,-1,2,1,-4,6};

By starting on \$1\$ and looping until you encounter a negative number, you can see that \$1 + -3 = -2\$, which makes this part unnecessary to check. It will not improve your array. The highest sum we can create out of this is simply \$1\$ for now.

Skipping the \$1\$ and \$-3\$ and we end up with:

int[] array = {7,-1,2,1,-4,6};

Now let's start looping. \$7 + -1 = 6\$ so that's good, let's continue.

\$2 + 1 + -4 = -1\$ OK, that ended up being a not so pleasant experience, but considering the \$6\$ we have from before, we end up with \$5\$ so let's continue.

\$6\$ now that's good. And now the array has ended. Adding this to our previous result and we end up with \$5 + 6 = 11\$ and we have our final result.

There's no need to start the original looping at 2 which will only count 2,1,-4,6 as the 7,-1 in the beginning of the array will give a more positive result than starting from this 2.

By taking this in consideration, you can increase the speed of your algorithm a lot.

The code for this approach can be found and review in my Code Review question

Edit: Another addition. You don't provide a method to retrieve the result without printing it. Your way of returning the result seems to be to simply print it to the console. That's not a good way. You should have provided a method like this: int[] maxSubArraySum(int[] array)


Web crawler that uses Task Parallel Library

From MSDN on Task.Wait:

  If the current task has not started execution, the Wait method
  attempts to remove the task from the scheduler and execute it inline
  on the current thread.

I have a feeling that something similar might be happening with WaitAll, killing performances. I'll have a look and see if I can find documentation about it. As you are using StartNew some of the tasks might be started already so they won't be in-lined.

I would refactor it using async/await so you are sure you are not using and blocking only one thread from the pool:

async static Task<IEnumerable<string>> GetAllPagesLinks(IEnumerable<string> rootUrls, bool hostMatch, bool validatePages)
{
    var result = await Task.WhenAll(rootUrls.Select(url => GetPageLinks(url, hostMatch, validatePages)));

    return result.SelectMany(x => x).Distinct();
}

static async Task<IEnumerable<string>> GetPageLinks(string formattedUrl, bool hostMatch = true, bool validatePages = true)
{
    var htmlDocument = new HtmlDocument();

    try
    {
        using (var client = new HttpClient())
            htmlDocument.Load(await client.GetStringAsync(formattedUrl));

        return htmlDocument.DocumentNode
                           .Descendants("a")
                           .Select(a => a.GetAttributeValue("href", null))
                           .Where(u => !string.IsNullOrEmpty(u))
                           .Distinct();
    }
    catch
    {
        return Enumerable.Empty<string>();
    }
}

async static Task<IEnumerable<string>> GetLinks(string url, bool hostMatch = true, bool validatePages = true, int level = 0)
{
    if (level < 0)
        throw new ArgumentOutOfRangeException(nameof(level));

    string formattedUrl = FormatAndValidateUrl(url);

    if (string.IsNullOrEmpty(formattedUrl))
        return Enumerable.Empty<string>();

    var rootUrls = await GetPageLinks(formattedUrl, hostMatch, validatePages);

    if (level == 0)
        return rootUrls;

    var links = await GetAllPagesLinks(rootUrls, hostMatch, validatePages);

    var tasks = await Task.WhenAll(links.Select(link => GetLinks(link, hostMatch, validatePages, --level)));

    return tasks.SelectMany(l => l);
}

Haven't had a chance to test it, but just get the gist.


Ruby code forces the answer using a loop and a branch to guess my favorite ice cream flavor

There is no need to write the gets and the string comparison code twice. The following code is equivalent:

puts "What is my favorite ice cream flavor?"
while gets.chomp.capitalize != "Vanilla"
   puts "Wrong answer; what is my favorite ice cream flavor?"
end
puts "Now that's my jam"


Your code looks mostly good to me.

One thing: Functions can help increase readability of your code, and reduce the amount of duplicate code. Additionally, they make testing and (re-)using your code easier. Your main method should only be an entry point, it shouldn't really contain any logic itself.

Your main method might look like this:

public static void main(String[] args) {
    int[] array = new int[] { 4, 1, 8, 5, 2, 0, 4, 3, 7, 9 };

    printArray(array);
    int[] sortedArray = sortArray(array);
    printArray(sortedArray);
}

Then just create those functions.

Misc

You have some unnecessary newlines after }.
temp could be renamed swap, making it more obvious what is happening.
arr could be named array (arr may be fine in this context, but generally, you do not want to shorten your variable names, as it is less readable).


Multithreaded non-blocking tiny echo server

There seems to be a few misconceptions about blockings calls and the purpose of non-blocking sockets. You wrote in a comment:

I thought this was a good idea for the server to be as responsive as possible for any number of clients connected (isn't that correct?).

Yes, this is a good idea, but no, your implementation does not make it faster. If anything, it will be slightly slower than using blocking sockets.
How is this slower?
Neither your server thread nor your handler threads does anything else than managing their socket. So there is absolutely nothing to be gained from having non-blocking sockets. Besides by using an active loop (while True without sleeping) your threads will eat-up 100% CPU and will never enter a state where it is favorable for the OS to deschedule it, leaving room for other threads, leading to other threads waiting longer before being scheduled.
This is normaly not an issue when a program can make use of multiple cores to spawn several threads concurently. But this is Python, and the GIL prevents us from having more than one thread at once. This means that as long as a thread is handling message from/to clients, the server thread is waiting to be scheduled. And the active loops are not helping for it to be scheduled faster.
But why non-blocking sockets in the first place?
Non-blocking sockets and/or sockets using timeouts are meant to be used in a context where there is other tasks to perform. Either because a single thread performs both the "server" and "handler" part:
def non_blocking_server(port, hostname='localhost'):
    try:
        sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error as e:
        logging.critical(e)
        logging.critical('Could not open socket. Exiting.')
        sys.exit(1)

    try:
        sockfd.bind((hostname, port))
        sockfd.listen(10)
        sockfd.setblocking(False)
    except socket.error as e:
        logging.critical(e)
        logging.critical('Could not start up server. Exiting.')
        sockfd.close()
        sys.exit(2)

    connected = {}
    receiving = {}
    sending = {}
    while True:
        with suppress(BlockingIOError):
            client, client_addr = sockfd.accept()
            logging.info('Connection from client {!r}'.format(client_addr))
            connected[client] = client_addr
            receiving[client] = b''

        still_receiving = {}
        for client, data in receiving.items():
            try:
                buf = client.recv(BUFFER_SIZE)
                if buf:
                    still_receiving[client] = data + buf
                else:
                    logging.info('Client: {} sent {} bytes.'.format(connected[client], len(data)))
                    sending[client] = (memoryview(data), 0)
            except BlockingIOError:
                still_receiving[client] = data
        receiving = still_receiving

        still_sending = {}
        for client, (message, sent_bytes) in sending.items():
            try:
                sent = client.send(message[sent_bytes:])
                sent_bytes += sent

                if sent:
                    still_sending[client] = (message, sent_bytes)
                else:
                    logging.info('Server sent {} bytes to client: {!r}'.format(sent_bytes, connected[client]))
                    client.close()
                    del connected[client]
            except BlockingIOError:
                still_sending[client] = (message, sent_bytes)
            except ConnectionResetError:
                # in case client disconnected before we send the echo
                logging.info('Client {!r} disconnected before sending echo.'.format(connected[client]))
                logging.info('Server sent {} bytes to client: {!r}'.format(sent_bytes, connected[client]))
                client.close()
                del connected[client]
        sending = still_sending

It would be a shame if a message from the first client was partially received and we would need to wait for a second client to connect before being able to receive and handle the rest. Here non-blocking sockets allow us to perform all three operations (accepting connections, receiving messages, sending messages) sequencially in a single thread without being dependent on external resources (such as client connection or network availability).
An other use case would be to check for incomming connection and/or handle them alongside more heavyweight computation in a loop. It allows to fine tune when things are done instead of relying on the OS to schedule threads for us.
Using threads as non-blocking facility.
So, after having said that non-blocking sockets in threads is bad, let's analyze the alternative of having blocking sockets in threads. In this scenario each thread is suspended while waiting for the blocking system call to finish. This has 2 advantages:

A thread no longer uses 100% CPU while waiting for an event;
The OS can more easily give priority to actually active threads and/or resume threads whose system call just finished faster.

And since you’re using threads, the OS is free to give resources where they are needed which usually manifests itself as "schedule the thread whose blocking call just finished".
Using threads also call for more readable code as it usually will make you write separate entities for separate kind of actions (a server and a handler, for instance).
Misconception of the "blocking" part of sending/receiving data
From the code you wrote, it seems that you think you will get a BlockingIOError if no more data can be read/sent. This is false, it only means that the network is not (yet) available.
In case of a read, a BlockingIOError can mean that:

the client didn't start sending data;
the client stopped sending data (but may be sending more in the future);
the data has been sent by the client but is not yet arrived on the server;
who knows.

When reading data, you have a few possibilities to know when to stop reading but it's a protocol that must be established between the client and the server:

the client can shutdown its write end of the socket, then the server will be notified by a recv that doesn't block but return 0 bytes;
the client can send a fixed-sized payload as a header to its message indicating the length of the incomming message;
the client can send a fixed-length message, filling missing data with whatever makes sense;
the client can end its message with a specific delimiter;
…

In case of a send a BlockingIOError is usually a sign that the network interface is used by another thread and that you should wait before sending your data.
Code review
With that in mind, you might have understood that your get_client_msg and send_client_msg are not quite doing the proper thing. But that's not an issue since we’re removing the non-blocking part of the sockets anyway.
You also have a few functions pertaining to handling the client socket where you pass said socket as parameter. The only reason that you left them in the EchoServer class is to be able to use self.connected_clients[connfd]. Instead, create a new class dedicated to handling a client, and pass the address as a parameter of this class alongside the socket.
Also, to simplify thread management, both classes can inherit from threading.Thread. A first rewrite would look like:
import socket
import logging
import threading
import sys

class EchoHandler(threading.Thread):
    BUFFER_SIZE = 1024
    # size limit in bytes for the client message to be received
    MAX_MSG_SIZE = 1024 * 5

    def __init__(self, sockfd, address):
        super().__init__()
        self.sockfd = sockfd
        self.address = address

    def run(self):
        msg = self.get_client_msg()
        logging.info('Client: %r sent %d bytes.', self.address, len(msg))

        sent_bytes_size = self.send_client_msg(msg)
        logging.info('Server sent %d bytes to client: %r', sent_bytes_size, self.address)

        self.sockfd.close()

    def get_client_msg(self):
        data = b''
        while True:
            buffer = self.sockfd.recv(self.BUFFER_SIZE)
            data += buffer
            if not(buffer) or len(data) >= self.MAX_MSG_SIZE:
                return data

    def send_client_msg(self, msg):
        total_sent = 0
        message = memoryview(msg)

        while True:
            try:
                sent_bytes = self.sockfd.send(message[total_sent:])
                total_sent += sent_bytes

                if sent_bytes == 0:
                    return total_sent
            except ConnectionResetError:
                # in case client disconnected before we send the echo
                logging.info('Client %r disconnected before sending echo.', self.address)
                return total_sent

class EchoServer(threading.Thread):
    def __init__(self, port, hostname='localhost'):
        super().__init__()

        try:
            self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as e:
            logging.critical(e)
            logging.critical('Could not open socket. Exiting.')
            sys.exit(1)

        try:
            self.sockfd.bind((hostname, port))
            self.sockfd.listen(10)
        except socket.error as e:
            logging.critical(e)
            logging.critical('Could not start up server. Exiting.')
            self.sockfd.close()
            sys.exit(2)

    def run(self):
        while True:
            client_connfd, client_addr = self.sockfd.accept()
            logging.info('Connection from client %r', client_addr)
            self.connected_clients[client_connfd] = client_addr

            EchoHandler(client_connfd, client_addr).start()

    def __del__(self):
        self.sockfd.close()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    EchoServer(50000).start()

But this is starting to look a lot like socketserver:
import logging
import socketserver

class EchoHandler(socketserver.BaseRequestHandler):
    BUFFER_SIZE = 1024
    # size limit in bytes for the client message to be received
    MAX_MSG_SIZE = 1024 * 5

    def finish(self):
        self.request.close()

    def handle(self):
        msg = self.get_client_msg()
        logging.info('Client: %s sent %d bytes.', self.client_address, len(msg))

        sent_bytes = self.send_client_msg(msg)
        logging.info('Server sent %d bytes to client: %r', sent_bytes, self.client_address)

    def get_client_msg(self):
        data = b''
        while True:
            buf = self.request.recv(self.BUFFER_SIZE)
            data += buf
            if not buf or len(data) >= self.MAX_MSG_SIZE:
                return data

    def send_client_msg(self, msg):
        total_sent = 0
        message = memoryview(msg)

        while True:
            try:
                sent_bytes = self.request.send(message[total_sent:])
                total_sent += sent_bytes

                if sent_bytes == 0:
                    return total_sent
            except ConnectionResetError:
                # in case client disconnected before we send the echo
                logging.info('Client %r disconnected before sending echo.', self.client_address)
                return total_sent

class EchoServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True

    def process_request(self, request, client_address):
        logging.info('Connection from client %r', client_address)
        super().process_request(request, client_address)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    with EchoServer(('localhost', 50000), EchoHandler) as server:
        server.serve_forever()

This is more to the point because all the boilerplate is already handled by Python.


Decode FEN string into separate variables for the 6 categories

Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.

To be certain that the code is correct, carefully read the specification and related documents.
Forsyth–Edwards Notation
PGN-SPEC
Portable Game Notation
Algebraic notation (chess)
Chess
For a code review, compare the specification and the code implementing it side-by-side.

In chess, there are pieces placed on squares which are organized into ranks and files to form a board. There doesn't appear to be any references to these basic concepts, apart from board, in decodeFen. Therefore, comparison of code to specification is difficult.
"PGN is "Portable Game Notation", a standard designed for the representation of chess game data using ASCII text files. PGN data is represented using a subset of the eight bit ISO 8859/1 (Latin 1) character set." Therefore,
var board [8][8]int8

is incorrect. Characters are not type int8 (8-bit signed integers). Characters are type byte (8 bits).
var board [8][8]byte

The code
for _, char := range row { ... }

expects a UTF-8 encoded string. UTF-8 encoding is not the same as ISO 8859/1 encoding.
Go is a safe, statically typed language. The code
board[r][col_ind] = int8(char)

is a failed attempt to correct errors when ISO 8859/1 encoding is decoded as UTF-8 encoding.
The decodeFen code is a "stream-of-conciousness" code that is hard to read and prove correct. The code is missing fundamental concepts like functions to encapsulate complexity and implementation details. For example, organize decodeFen as a series of calls to parse functions for each FEN field.

As an example, consider the FEN piece placement field. Here's a first draft:
pieces.go:
package main

import (
    "errors"
    "fmt"
    "strings"
)

type Board [8][8]byte

const (
    whitePieceLetters = "PNBRQK"
    blackPieceLetters = "pnbrqk"
    pieceLetters      = whitePieceLetters + blackPieceLetters
)

func isPiece(p byte) bool {
    for i := 0; i < len(pieceLetters); i++ {
        if p == pieceLetters[i] {
            return true
        }
    }
    return false
}

var (
    ErrRankOutOfRange = errors.New("rank out of range")
    ErrFileOutOfRange = errors.New("file out of range")
    ErrPieceInvalid   = errors.New("piece invalid")
)

func parseFENPieces(board *Board, pieces string) error {
    ranks := strings.Split(pieces, "/")
    if len(ranks) != len(board) {
        return ErrRankOutOfRange
    }
    for r, rank := range ranks {
        f := 0
        for i := 0; i < len(rank); i++ {
            piece := rank[i]
            if piece >= '0' && piece <= '9' {
                for j := byte(0); j < piece-'0'; j++ {
                    if f >= len(board[0]) {
                        return ErrFileOutOfRange
                    }
                    board[r][f] = '-'
                    f++
                }
            } else {
                if f >= len(board[0]) {
                    return ErrFileOutOfRange
                }
                if !isPiece(piece) {
                    return ErrPieceInvalid
                }
                board[r][f] = piece
                f++
            }
        }
        if f != len(board[0]) {
            return ErrFileOutOfRange
        }
    }
    return nil
}

func main() {
    fens := []string{
        // https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
        "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
        "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1",
        "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2",
        "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2",
    }
    var board Board
    for _, fen := range fens {
        fields := strings.Split(fen, " ")
        if len(fields) > 0 {
            pieces := strings.Split(fen, " ")[0]
            fmt.Println(pieces)
            err := parseFENPieces(&board, pieces)
            fmt.Println(err)
            for i := range board {
                fmt.Printf("%c\n", board[i])
            }
        }
    }
}

Playground: https://play.golang.org/p/-pPnCs2GMao
Output:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
<nil>
[r n b q k b n r]
[p p p p p p p p]
[- - - - - - - -]
[- - - - - - - -]
[- - - - - - - -]
[- - - - - - - -]
[P P P P P P P P]
[R N B Q K B N R]

Use chess terminology to match the specification.
The chess board data structure is ubiquitous. Give it a type:
type Board [8][8]byte

In Go, arguments are passed by value. For an array, the value is the entire array. Therefore, for efficiency, we use a pointer (8 bytes or 4 bytes) rather than an array (64 bytes).
Input must be valid. Make no assumptions about external input. Report errors.
Don't use magic values: 49 is '0', 57 is '9'.
And so forth.


Unless your elements serve a legitimate purpose (ie. they have content), then you should avoid using empty elements whenever possible.  Instead, I recommend using a linear-gradient as a background on a content element.

Sass makes this easy to generate:

$colors: #C3E279, #F7FEC8, #FFD069, #F27669, #DC9CBE, #C59AE0, #969DCC;
$stops: ();
$current-stop: 0%;
@each $c in $colors {
    $stops: append($stops, $c $current-stop, comma);
    $current-stop: $current-stop + (100% / length($colors));
    $stops: append($stops, $c $current-stop);
}

body:before { /* or some other element*/
  content: '';
  height: 5px;
  display: block;
  background: linear-gradient(to right, $stops);
}

Output:

body:before {
  content: '';
  height: 5px;
  display: block;
  background: linear-gradient(to right, #C3E279 0%, #C3E279 14.28571%, #F7FEC8 14.28571%, #F7FEC8 28.57143%, #FFD069 28.57143%, #FFD069 42.85714%, #F27669 42.85714%, #F27669 57.14286%, #DC9CBE 57.14286%, #DC9CBE 71.42857%, #C59AE0 71.42857%, #C59AE0 85.71429%, #969DCC 85.71429%, #969DCC 100.0%);
}

http://sassmeister.com/gist/9665cd09dfab6b3e05e0


JOIN and sprintf rather than two queries and echo

Escaping Variable Part of Query

Check out this and this post about correctly using the wordpress database class to avoid SQL injection. Even if the variable data is not directly user supplied, I would always use prepared statements or at least escape data as defense in depth, and to prevent second order SQL injection.

Your code should look something like this:

$getImageIdQuery = "
SELECT image_map
FROM wp_posts
WHERE ID = %d";

$sql = $wpdb->prepare( $getImageIdQuery, $exerciseID );
$imageID = $wpdb->get_results($sql);

Same goes for the other query (the added benefit is that this way, you don't need sprintf because the SQL code and the PHP code are already separated).

Escaping Variable Part of Output

I would also sanitize all variable data when echoing it to the user. Right now, anybody who can create posts can include arbitrary javascript via the_title. This might actually be ok, but still, to be save I would write it like this:

echo '
';
echo '
' . esc_html(the_title()) . '
';
echo '
';
echo "id. ".jpg") . "/>";

Foreach

You have two foreach statements which do not do anything. but their side-effect is that your are always only working on the last entry retrieved by the query.

Instead of returning all matching entries, you should only retrieve this one entry and remove your foreach loops (you can use get_row (if needed in combination with limit and order by)).

Misc

I would use more spaces to make the code more readable (for example around .). See also the wordpress style guide.
use single and double quotes consistently (for example "<img src=" vs '
'; both should use single quotes)

sprintf

I don't really like using sprintf, but if you want to, it would look like this:

echo '
';
echo sprintf('
%s
', esc_html(the_title()));
echo '
';
echo sprintf("", esc_url($blogUrl . "/image/medium/".$row->id. ".jpg"));

%s is a placeholder for any string (you would use %d for numbers), and it will be replaced by the rest of the arguments for sprintf.

The advantage is that you do not have PHP variables/function calls inside your HTML/SQL/etc.

join

You can read about join here and a bit more in-depth here.

Your query should look something like this:

SELECT imagemap.id FROM imagemap JOIN wp_posts ON imagemap.exercise = wp_posts.image_map WHERE wp_posts.ID = $exerciseID

What it basically does is combine the two tables (based on the ON clause).

For example, if the tables looked like this:

imagemap:
id exercise
1  1
2  2
3  2
4  3

wp_posts:
pid image_map
6   1
7   1
8   2

the combined table would look like this:

id exercise pid image_map
1  1        6   1
1  1        7   1
2  2        8   2
3  2        8   2

and then the where clause is applied (I called wp_posts.ID pid for the example).


Here's my interface, so call me ...maybe

Going back to your original code.
I think a little bit of reflection will get you out of the try catch block situation.

public bool HasExplicitCallStatement()
{
    var theObject = ((dynamic) Context.Parent);
    if(theObject.GetType().GetMethod("CALL") != null)
    {
        var call = theObject.CALL();
        return call != null && call.Symbol.Text == Tokens.Call;
    }

    return false;
}


Using built-in type Decimal or Entity type Advance, to hold AdvanceAmount

This question is very, very similar to another question you recently asked, so this answer will basically (hopefully!) clarify my other answer.
KISS: Keep It Simple, Stupid.
These classes represent database records. With Entity Framework you would define the relationships like this (I'd drop the Info suffix):
public class Deduction
{
    // primary key:
    public int Id { get; set; }

    public string Name { get; set; }
    public decimal LoanInstalmentAmount { get; set; }
    public decimal UniformInstalmentAmount { get; set; }
    public decimal InsuranceInstalmentAmount { get; set; }

    // foreign keys:
    public int AdvanceId { get; set; }
    public int EmployeeId { get; set; }

    // navigation properties:
    public virtual Advance Advance { get; set; }
    public virtual Employee Employee { get; set; }
}

public class Advance
{
    // primary key:
    public int Id { get; set; }

    public decimal Amount { get; set; }
    public DateTime EnteredDate { get; set; }

    // navigation property:
    public virtual ICollection<Deduction> Deductions { get; set; }
}

EF works with conventions - it determines that a property called Id is mapped to your  primary key, and that a property called [AnotherEntityTypeName]Id is a foreign key property when there's a virtual navigation property of that other entity type - just with the types involved and the names of the properties, EF is "smart" enough to determine that there's a one-to-many relationship between Deduction and Advance. Now as @Malachi pointed out, the question is is this really what you want?
Only you can answer that. We review code, not database schemas.

Per your other question I see that you're not using Entity Framework. I don't see how that would impact the design of your POCO classes though; at the end of the day they're just classes that convey data between the database and your app, and if you're using ADO.NET then you have full control over how the classes get instantiated and loaded with data, so the classes you're using can be anything your sweet heart desires. Ok anything your business logic needs.

For example, the below code returns an IEnumerable<Deduction>, where Deduction is defined as above, eager-loading the related Advance when it exists:
public IEnumerable<Deduction> GetAllDeductions()
{
    var sql = "SELECT * FROM dbo.Deductions d LEFT JOIN dbo.Advance a ON d.AdvanceId = a.Id"
    using (var connection = new SqlConnection(_connectionString)
    {
        connection.Open();
        using (var command = new SqlCommand(sql, connection))
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                var deduction = new Deduction();
                Advance advance;

                // assuming column names... this is just an example
                if (reader["EnteredDate"] != null)
                {
                    advance = new Advance()
                    advance.Id = reader["AdvanceId"];
                    advance.Amount = reader["Amount"];
                    advance.EnteredDate = reader["EnteredDate"];
                }

                deduction.Id = reader["Id"];
                deduction.Name = reader["Name"];
                deduction.LoanInstalmentAmount = reader["LoanInstalmentAmount"];
                deduction.UniformInstalmentAmount = reader["UniformInstalmentAmount"];
                deduction.InsuranceInstalmentAmount = reader["InsuranceInstalmentAmount"];

                deduction.Advance = advance;

                yield return deduction;
            }
        }
    }
}

This boilerplate-level gruntwork could all be automated with EF and look like this instead:
public IEnumerable<Deduction> GetAllDeductions()
{
    using (var context = new MyDbContext(_connectionString))
    {
        return context.Deductions.Select(e => e).Include(e => e.Advance).ToList();
    }
}

ViewModels
What you seem to want to display is different. It's a ViewModel, something that does not represent database records, but something meant to be displayed.
Then you create another class to represent just that. It's possible that such a class looks very similar to the entity types; it's also possible that it contains properties from two or more entity types:
public class DeductionInfo // or DeductionViewModel
{
    public int Id { get; set; } // only if the View needs it

    public string Name { get; set; }
    public decimal LoanInstalmentAmount { get; set; }
    public decimal UniformInstalmentAmount { get; set; }
    public decimal InsuranceInstalmentAmount { get; set; }
    public decimal AdvanceAmount { get; set; }
}

You'll have a service whose job is to get the data, prepare your ViewModels and spit out these DeductionInfo instances so that your View can display them.
Bottom line: the View doesn't care about the database schema, and doesn't need to know about your entity types. It works with a ViewModel that only contains the data that it needs.
An alternative could be to create a complex type (basically, the DeductionInfo class above), and to have the service fetch the data directly into that type, and return that type for the view to consume: you only select the data you need, and you consume it directly. Works just as well. Which is best? You decide!


Reduce columns to produce product keycodes

I would do something like this. It is untested and may have typos but it should give you some idea of how to break the logic up.  I would:

Express variable to what they mean
Use a class

Hope this helps

require 'CSV'

class CSVTranslator
  def self.write file_path, options={}
    new(file_path, options).translate
  end

  def initialize source_file, options={}
    @source_file = source_file
    @destination_file = options.fetch(:to) { "#{File.basename(source_file, '.csv')}_coded.csv" }
  end

  def translate
    CSV.open(destination_file, 'a+') do |out|
      out << headers
      each_row { |row| out << row }
    end
  end

  private

  attr_reader :source_file, :destination_file

  def headers
    %w(First Last Company Address address2 City State Zip Country phone_number email_address keycode)
  end

  def each_row
    CSV.foreach(source_file, headers: true) do |line|
      yield code_line_by_product(line)
    end
  end

  def code_line_by_product(line)
    new_line = {}
    english_language = false
    keycode = ""

    line.each do |header, value|
      if header.include?('#')
        english_language ||= value.include?('English')
        keycode = value.first if value.first != '1'
      else
        new_line[header] = value
      end
    end

    new_line['keycode'] = keycode unless english_language || keycode.blank?

    new_line
  end
end

CSVTranslator.write 'test.csv', to: 'test_coded.csv'


As far as I can tell, your algorithm is something like \$\mathcal{O}(n!)\$, because you compare all possible pairs of files. It is possible to do this in \$\mathcal{O}(n)\$.

You just have to iterate over the files and order them into a hashmap (i.e. dictionary) based on their header hash. Then, resolve the possible conflicts of two files with the same header, but different content, which takes \$\mathcal{O}(k)\$, where \$k\$ is the number of files with the same header. So in the worst case (all files have the same header), this algorithm is \$\mathcal{O}(2n)\$.

from collections import defaultdict
import sys

def hash_content(file_name, length=-1):
    with open(file_name) as f:
        return hash(f.read(length))

def group_by_header(*file_names):
    file_groups = defaultdict(list)
    for file_name in file_names:
        file_groups[hash_content(file_name, length=10)].append(file_name)
    return file_groups

def group_by_content(*file_names):
    file_groups = group_by_header(*file_names)
    for file_names in file_groups.values():
        if len(file_names) > 1:
            while file_names:
                file_name = file_names.pop()
                file_groups[hash_content(file_name)].append(file_name)
    return filter(None, file_groups.values())

if __name__ == "__main__":
    file_names = sys.argv[1:]
    print group_by_content(*file_names)

This code has two caveats:

It assumes hash is collision-free (a fair assumption). We could pass the string content directly as a key and let python do the hashing. Then we would also get a strategy for the rare case that two strings have the same hash without being equal. But this way we avoid storing the possibly large file-contents as strings.
This uses the fact that dict.values() returns a list and not an iterator, so we can modify the dictionary in the loop here. This breaks in Python 3.x, but you specifically tagged this as Python 2.7. You can remedy this by introducing a new dictionary:

def group_by_content(*file_names):
    header_hashs = group_by_header(*file_names)
    content_hashs = defaultdict(list)
    for hash_, file_names in header_hashs.items():
        if len(file_names) > 1:
            while len(file_names):
                file_name = file_names.pop()
                content_hashs[hash_content(file_name)].append(file_name)
        else:
            content_hashs[hash_] = file_names
    return (val for val in content_hashs.values() if val)


Marking a new dataTable row as consumed or cancelled

I think you did well to wrap shared code in if (data.wasConsumed || data.wasCancelled) { ... } to avoid code duplication.
However, thanks to that check, you don't need an else if inside,
a simple else will do:

if (data.wasConsumed) {
   rowClass = ".consumed";
} else {
   rowClass = ".cancelled";
}

And for a more compact writing style, a ternary will be handy here:

var rowClass = data.wasConsumed ? ".consumed" : ".cancelled";

On the other hand,
if later you extend your code with one more condition,
for example if (data.wasConsumed || data.wasCancelled || data.wasForwarded) { ... } then you will need to bring back the if-else,
of course.

If at this point you already plan such extension soon, then your current conditions are fine as they are.

The parameter iDataIndex appears to be unused. As such, is better to omit it from the parameter list of the function. It's also a strange name anyway. (The "i" prefix is sometimes (poorly) used as an indicator of an index variable into an array, but then there's the "index" too for the same purpose, and much better.)


Listing Docker Images without registry URI

It looks like the purpose of the second command is to skip the REPOSITORY:TAG table header, which would always be the first line of the docker images output.  You can therefore combine the first two awk commands as:

awk 'NR > 1 { printf("%s:%s\n", $1, $2) }'

To keep just the trailing part of the REPOSITORY field, you could do gsub('.*/', '', $1).  Note that that is not the same as awk -F '/' '{print $3}', but likely better.

Therefore, I would write the solution as

docker images | awk 'NR > 1 { gsub('.*/', '', $1); printf("%s:%s\n", $1, $2); }'


I'm not absolutely certain (I haven't run it through an assembler or checked against an instruction chart), but I believe this may be a byte shorter:

    xor dl, dl
    xor si, si
    mov cx, 2000h
again:
    lodsb       ; load value, increment SI
    add dl, al  ; set z flag based on result of addition
    loop again  ; decrement CX, jump if NZ, *without* affecting flags

    jz good     ; Z flag still has result of addition above
    hlt
good:


My take at OOP module/prototyping JavaScript


Stable custom alphabetical order using List.Sort

First of all, I would take advantage of the fact that the other commonly used implementation of sorting in .Net is stable: the OrderBy() extension method from LINQ. Though it requires IComparer interface for custom sorting, it won't accept the Comparer delegate you're using.

If you wanted to keep using List.Sort(), then I think your implementation is mostly okay, with the following caveats:

It has the potential to balloon the time complexity of the sort from \$\mathcal{O}(n \log n)\$ to \$\mathcal{O}(n^2 \log n)\$. This is becuse every call to your comparison delegate can take \$\mathcal{O}(n)\$ time, due to the calls to IndexOf().
It doesn't work correctly if some words in the list repeat themselves. For example “Good, good, Good” would be sorted as “Good, Good, good”.

Neither of these might matter to you, but I think it's good to be aware of them.

Your comparison doesn't work correctly for pairs where one word is the start of another (like “HOW” and “HOWEVER” from the sample list), it returns 0 for those, even though the words are not the same.

Some small specific comments about your code:

All your code is inside a single method. That's usually frowned upon, but I think it's probably okay when you have this little code. The same goes for separation of concerns.

int numOfWords = int.Parse(firstLine.Split(" ".ToCharArray())[0]);
string alphabet = firstLine.Split(" ".ToCharArray())[1].ToUpper();

I would avoid the repetition of firstLine.Split(" ".ToCharArray()) by extracting its result to a separate variable.

Also, you don't actually need that ToCharArray(), since Split() is a params method.

string[] firstLineParts = firstLine.Split(' ');

int numOfWords = int.Parse(firstLineParts[0]);
string alphabet = firstLineParts[1].ToUpper();

wordsCopy.Add(words[words.Count - 1]);

I think creating wordsCopy would be simpler if you used the constructor of List that can copy existing collection:

List<string> wordsCopy = new List<string>(words);

words.Sort(delegate(String x, String y)

You can use the lambda syntax here. That way, you don't have to (but can, if you want) specify the types of parameters:

words.Sort((x, y) =>

x.ToUpper().Equals(y.ToUpper())

ToUpper() is culture-specific, which can cause problems in some cultures (particularly Turkish).

But you probably don't need to care about that if you only ever expect to run this program on your computer.


Implementing EXCEPT functionality for social networking exercise

Formatting
Using indentation and line breaks would make your code easier to read. There is no real "standard" so go with what you feel is clearest. I usually go with something that resembles C indentation a bit. Others use a more Java-like indentation. Doesn't matter, as long as it makes it more readable.
SELECT
    H1.name,
    H1.grade,
    H2.name,
    H2.grade
FROM
(
    SELECT *
    FROM Likes L1
    WHERE L1.ID2 NOT IN
    (
        SELECT L2.ID1
        FROM Likes L2
    )
) F
INNER JOIN Highschooler H1
    ON F.ID1 = H1.ID
INNER JOIN Highschooler H2
    ON F.ID2 = H2.ID;

F and other aliases
It's good practice for aliases to get meaningful names. Making the code shorter is all well and good, and in your case doing a self-JOIN they are necessary; but, your subquery being aliased as F doesn't say much about what it represents.

MySQL limitations
There are several things you could do in other RDBMS that MySQL doesn't allow. You could have made a Common Table Expression, declared a Table Variable, and even used EXCEPT; except, none of those are supported by MySQL. I'm afraid, given the tool, this is about as good as it will get. Perhaps someone else will know of a better way. Only other thing I could think of is using a temp table, but that's totally overkill for something simple like this.


Finding ideal sport based on weighted attributes

Perhaps you could represent the weightings of each trait as a tuple of multipliers, which are applied to the input values.

Here you have a list of weightings, to which it's trivial to add entries.

from operator import itemgetter, mul
from itertools import groupby, starmap

print("Welcome to What's your ideal sport! "
      "Answer the following questions on a scale from 1-10.")

traits = ('leg', 'arm', 'core', 'mental', 'reaction')

questions = ["How good is your leg strength / speed? ",
             "How good is your arm strength? ",
             "How strong are your abs? ",
             "How intelligent are you? ",
             "How fast are your reactions? "]

responses = [int(input(q)) for q in questions]

print("weights: ")
for t, a in zip(traits, responses):
    print("%s strength = %d" % (t, a))

weightings = [
    # sport, (legs, arms, core, mental, reactions)
    ('soccer',     (5, 2, 1, 1, 1)),
    ('chess',      (1, 1, 1, 10, 1)),
    ('football',   (3, 4, 3, 1, 1)),
    ('tennis',     (1, 4, 2, 1, 3)),
    ('swimming',   (3, 3, 3, 1, 1)),
    ('basketball', (2, 5, 1, 2, 1)),
    ('track',      (6, 2, 1, 1, 1)),
    ('gymnastics', (3, 3, 3, 1, 1))
]

def calcscore(weights, answers):
    ''' calculate the score for a given set of weights and answers, by
        multiplying each answer by the matching weight and adding them
        all together.
    '''
    return sum(weight * answer for (weight, answer) in zip(weights, answers))
    # more esoteric implementation.
    #return sum(starmap(mul, zip(weights, answers)))

# results prior to sorting
result = [(name, calcscore(traits, responses)) for (name, traits) in weightings]

# sorted results prior ordered by score descending
sresult = sorted(result, key=itemgetter(1), reverse=True)

# group and take first group. It should never be empty.
grouper, group = next(groupby(sresult, key=itemgetter(1)))

print('results:')
print("with score %d" % grouper)
print("we have the sports")
for name, score in group:
    print('%s - %d' % (name, score))

Some of the values in the weightings should probably be zero rather than one. To represent an absence of this trait from the calculation. It will be straightforward for the op to modify these themselves. I am demonstrating the concept.


MinutesPerDay - Does .NET have anything for it?

Since these are constants, I would declare them as such. Also, making the calculation explicit would be more informative.

private const int MinutesPerDay = 24 * 60;
private const int MinutesPerWeek = 7 * MinutesPerDay;
private const int MinutesPerMonth = 30 * MinutesPerDay;


Add dash between more than two consecutive numbers and comma between other numbers in array

Sorry but no comments (yet) on the LINQ.

Your first conditional has a logic error.  You should be checking if orderedArray is null before you check if its length is 0.

The method has a leap of faith that someone is inputting an array sorted in ascending order.  There is nothing in your code to prevent otherwise.

What if someone wanted to pass in a List or IEnumerable?  Restricting input to an array is fairly limiting.

The variable groupedArray is not an array, so the name is misleading.  A quick reworking of all of the above is:

private static string AddDashesBetweenConsecutiveNumbers(IEnumerable<int> values)
{
    // Avoid Count() since it requires full list enumeration.
    // FirstOrDefault() would return default(int) or 0, which is not null.
    // Any() will find the first one without a full list enumeration.
    if (values == null || !values.Any())
    {
        return string.Empty;
    }

    // If the input values is already sorted, this will be fast.
    // If the input values is not already sorted, good thing we do it here.
    var orderedValues = values.OrderBy(x => x);

    var groupedValues = orderedValues.Select((x, i) => new { Difference = i - x, Value = x })
            .GroupBy(x => x.Difference)
            .Select(group => group.Select(a => a.Value))
            .Select(arr => arr.Count() > 2
                        ? $"{arr.First()}-{arr.Last()}"
                        : string.Join(", ", arr));

    return string.Join(", ", groupedValues);
}

I'm sure you are capable of writing a non-LINQ version if you desired.  I include a version below.

private static string AddDashesBetweenConsecutiveNumbers2(IEnumerable<int> values)
{
// Avoid Count() since it requires full list enumeration.
// FirstOrDefault() would return default(int) or 0, which is not null.
if (values == null || !values.Any())
{
    return string.Empty;
}

// If the input values is already sorted, this will be fast.
// If the input values is not already sorted, good thing we do it here.
var orderedValues = values.OrderBy(x => x);

return string.Join(", ", GetGroupedIntegers(orderedValues));
}

private static IEnumerable<string> GetGroupedIntegers(IOrderedEnumerable<int> orderedValues)
{
var sublist = new List<int>();

Func<string> getSubListOutput = () =>
{
    switch (sublist.Count)
    {
        case 1:
            return sublist.First().ToString();
        case 2:
            return sublist.First().ToString() + ", " + sublist.Last().ToString();
        default:
            return sublist.First().ToString() + "-" + sublist.Last().ToString();
    }
};

foreach (var value in orderedValues)
{
    if (sublist.Count == 0 || sublist.Last() == value - 1)
    {
        sublist.Add(value);
    }
    else
    {
        yield return getSubListOutput();
        sublist = new List<int>() { value };
    }
}

yield return getSubListOutput();
}

Got to run to a meeting, but another flaw in both your original and my answer is that there is no check for distinct integers, but that can easily be done.

UPDATE:
Corrected code as per comments.


Just some generic notes about the JavaScript code: I'd extract out a setOpacity function and create a fadeOut and a fadeIn function too.

function setOpacity(opacity) {
    fading_div.style.opacity = opacity / 100;
    fading_div.style.filter = 'alpha(opacity=' + opacity + ')';
}

function fadeOut(opacity) {
    setOpacity(opacity);
    if (opacity == 1) {
        fading_div.style.display = 'none';
        done = true;
    }
}

function fadeIn(opacity) {
    setOpacity(opacity);
    if (opacity == 1) {
        fading_div.style.display = 'block';
    }
    if (opacity == 100) {
        done = true;
    }
}

...
setTimeout("fadeIn(" + i + ")", i * 5);
...

It eliminates the in and out magic constants and lots of conditions which checks their values.

Using variable name suffixes like opacity_value looks a little bit redundant (since variables stores values), so I've renamed them. The same is true for the function_opacity function.

I've changed the second for loop too to use fewer arithmetic operations, I think the following is easier to read:

for (var i = 1; i <= 100; i++) {
    setTimeout("fadeOut(" + (100 - i) + ")", i * 5);
}


First of all, you have the following construct:

if yn == "n":
    exit()
else:
    lots
    of
    code

But if yn equals "n", the exit() will have been executed, and you won't reach any other lines anyway. So you can just write

if yn == "n":
    exit()

lots
of
code

This is like an 'early return' (except not in a function, but in the main body of code).

Second, you have

x =int( random.choice(range(1,100)))
...
a = str(x)
...
print "What is " + a + " x " + b + "?"

The spacing on the line with x = is off. It should be

x = int(random.choice(range(1, 100))

That is: no spaces next to ( and ). A space on each side of the =, and a space after the ,.

Furthermore, you should really use string formatting, allowing you to write

print "What is {} + {}?".format(x, y)

This way you don't need intermediate variables a and b.

I assume ua means user_answer here:

print "What is " + a  + " x " + b + "?"
ua = int(raw_input("What is the answer? "))

Why not just write

problem = "What is {} x {}? ".format(x, y)
user_answer = int(raw_input(problem))

You're basically asking a question, and then "What is the answer to the question?". Better to just ask the question alone.

Instead of writing xy, you could write solution or answer.

Another thing of note: the score (I assume that's what you mean with s) gets reset to 0 each time you get a new problem statement, but the score (t) is only printed at the end of the rounds.

That is, you have (pseudo-code)

while play_again:
    ...
    s = 0
    answered = ...
    while answered != solution:
        answered = ...
        s -= 1  # You had s = s - 1, that is equivalent to s -= 1
    s += 1
    t = str(s)
print "Your score is " + t

While instead I think you mean

s = 0
while play_again:
    ...
    answered = ...
    while answered != solution:
        answered = ...
        s -= 1  # You had s = s - 1, that is equivalent to s -= 1
    s += 1
t = str(s)
print "Your score is " + t

Note that the last two lines can be replaced with

print "Your score is {}".format(s)

(Also note: if the user inputs something different from y or n on the first go, you get a NameError: t is referenced before it is assigned because you never enter the while loop).


Python Calculator Test Driven Development

TDD
It's quite hard to review TDD as it's more of a way to do work than an observable product. What I mean is that whether you did TDD or not, the unit tests would mostly be the same.
One minor thing I'd point out is that the c variable name isn't good. One strong point of TDD/Unit Testing IMO is that it can act as a documentation of your code, so it should be explicit. Name it calculator; you won't be losing much space doing so.
Calculator class
Regarding the class itself, there are two things I'd like to review.
Nesting makes the code hard to read. In your case it's not so bad because methods are very short, but it's a good habit you should take.
Instead of :
if isinstance(x, self.number_types) and isinstance(y, self.number_types):
    return x + y
else:
    raise ValueError

I would do
if not isinstance(x, self.number_types) and not isinstance(y, self.number_types):
    raise ValueError

return x + y

This way if you had to add code in your method, you wouldn't need to hang in a else statement for the whole flow.
Second, it's fine that you throw a ValueError, but I think you should add a message otherwise we can't know why the calculator crashed.
Exceptions
With regards to the comments, I'd like to talk a little bit more about your exception handling. Should it be raised in the UI or in the class itself?
The boring answer would be "It depends". In my opinion, there are advantages to both cases.

If the exception is raised in UI, it is raised as soon as possible, which means you don't have to work with potentially invalid data in your application flow.

If the exception is raised in the class itself, you are 100% sure that wherever/however you call your calculator, the input will be validated.

So, what is better? I'd say it's better if the exception is raised in the class, as you'll be sure you won't ever have to repeat your validation if you reuse your calculator elsewhere. But, if I think about the MVC.Net's way of working, for example, it validates the user input on client and server side. This way, there is a quick validation that is made to make sure everything makes sense, then in the server validation (in your case, you class), the input is thoroughly validated then used.
For the sake of "having the best code possible", I'd say do the validation in both and see for yourself what is your gain :)