I was going to edit my other answer, but instead I'm going to take a different approach - I mean, I'll push it to the extreme ;)

Warning
I'll push it to the extreme is to be taken literally. This solution doesn't aim at solving the simple age calculator problem, rather at showing how one would architect a SOLID application - if the goal is just to calculate the difference between two dates, this is absolute overkill. If the goal is to learn how to write good OOP using a trivial/simple problem as an excuse...
Buckle up, you're in for a ride.

static void Main(string[] args)
As you know by now, this is your application's entry point. When this static method returns, the program ends. To terminate your program, simply use return; in this method, or structure your program flow so that normal exit simply causes the main thread (imagine a cursor running each instruction sequentially - or step through your code in the debugger) to reach the bottom of the Main method.
This method being static, if you're going to call anything outside of it, it's going to have to be static as well. If you're writing procedural code, it doesn't matter.
If you want object-oriented code, the Main method will probably have a very high level of abstraction, and will read like pseudo-code, if not like plain English.
The method revolves around the idea that it's a program's birth, life, and death.
Dependency Injection (DI) disciples (guilty!) call this entry point, the composition root. This is where you instantiate the application (and its dependencies), and run it.
Simplified to the extreme:
static void Main(string[] args)
{
    var app = new MyApplication();
    app.Run();
}

What's in the Run() method?
public class MyApplication
{
    public MyApplication()
    {
        // initialisation here
    }

    public void Run()
    {
        // app logic here
    }
}

Notice that the Run method is not static. It exists only as a member of the interface of an object defined by this MyApplication class - in other words, you need an instance of MyApplication to call this method.
In this case the application logic part will feature our main loop, from which we will exit based on a condition.
public void Run()
{
    var keepRunning = true;

    while(keepRunning)
    {
        // application logic
        keepRunning = false; // exit
    }
}

At this point, we've reached a point of no return. Anything else we code in the Run method will impact maintainability, testability, and readability. Better keep it to a minimum.

The key resides in delegating the work. The MyApplication class cannot do its work alone without using the new keyword, which would increase coupling, and without doing the work all by itself, which would decrease cohesion. Since we want low coupling and high cohesion, we'll start by avoiding the use of static methods and of the new keyword.

Why?
Good code is testable code. You'll want to be able to write tests for the code you write - whether you write these tests or not, writing testable code will tend to produce code that is more cohesive and less coupled.
See also: https://stackoverflow.com/a/3085419/1188513

IUserInteraction
We know we want to use the console to interact with the user, but in order to test our application logic, we'll want to be able to substitute the user's input for whatever our tests need.
public interface IUserInputProvider
{
    string GetUserInput(string prompt);
    T GetUserInput<T>(string prompt, IUserInputValidator<T> validator);
}

With that - and that only, we already have enough to go back to the MyApplication class:
public class MyApplication
{
    private readonly IUserInputProvider _inputProvider;

    public MyApplication(IUserInputProvider inputProvider)
    {
        _inputProvider = inputProvider;
    }

    public void Run()
    {
        var keepRunning = true;

        while(keepRunning)
        {
            var prompt = "Enter your birth date:";
            var input = _inputProvider.GetUserInput(prompt); // no validation for now
            // ...

            keepRunning = false; // exit
        }
    }
}

I'll get back to the IUserInputValidator<T> later.

Mocking
GetUserInput is a method that returns a string. Nothing more, nothing less. We know that we want to call Console.ReadLine(), but that's an implementation detail that the MyApplication class does not need to know about.
If we were to write a test to see if the Run method effectively exits when the user enters "y", we would not bring up a console and wait for someone to enter "y" - instead we would set up a mock - a "fake" implementation of the IUserInputProvider interface that returns "y" when we ask it to GetUserInput.

Implementation
The concrete implementation we're going to be using will use the console. Nothing prevents making another concrete implementation that pops up a dialog window instead - as long as we use a prompt and return a string, anything can work. This means the implementation(s) can be modified in every possible way, the only assumption the MyApplication class makes is that there's a GetUserInput method that takes a string prompt and returns a string.
This could be an implementation:
public class ConsoleUserInputProvider : IUserInputProvider
{
    public string GetUserInput(string prompt)
    {
        Console.WriteLine(prompt);
        return Console.ReadLine();
    }

    public T GetUserInput<T>(string prompt, IUserInputValidator<T> validator)
    {
        string input;
        T result;

        var isValidInput = false;
        while(!isValidInput)
        {
            input = GetUserInput(prompt);
            isValidInput = validator.Validate(input, out result);
        }

        return result;
    }
}

Where IUserInputValidator is yet another abstraction that exposes a bool Validate(string input) method.
Let's make it a generic interface:
public interface IUserInputValidator<T>
{
    bool Validate(string input, out T result);
}

One could implement it like this:
public class BirthDateValidator : IUserInputValidator<DateTime>
{
    public bool Validate(string input, out DateTime result)
    {
        return DateTime.TryParse(input, out result);
    }
}

Or like this:
public enum YesNoResult
{
    Unknown,
    Yes,
    No
}

public class YesNoValidator : IUserInputValidator<YesNoResult>
{
    private readonly IDictionary<string, YesNoResult> _values;

    public YesNoValidator(IDictionary<string, YesNoResult> values)
    {
        _values = values;
    }

    public bool Validate(string input, out YesNoResult result)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ArgumentException("input", "input string is empty.");
        }

        var lowerCase = input.Substring(0, 1).ToLower();

        var isValue = values.TryGetValue(lowerCase, out result);
        if (!isValue)
        {
            result = YesNoResult.Unknown;
        }

        return (result != YesNoResult.Unknown);
    }
}

As you can see, this approach produces very focused and specialized code - code that does one thing, so well, that it can't possibly even need to change. And yet it remains extensible - you could decorate any Validator implementation with, say, a ValidationLoggerDecorator that can log all failed validations:
public class ValidationLoggerDecorator<T> : IUserInputValidator<T>
{
    private readonly IUserInputValidator<T> _validator;
    private readonly ILogger _logger;

    public ValidationLoggerDecorator(IUserInputValidator<T> validator, ILogger logger)
    {
        _validator = validator;
        _logger = logger;
    }

    public bool Validate(string input, out T result)
    {
        var isValid = _validator.Validate(input, out result);

        if (!isValid)
        {
            _logger.Info(string.Format("Validation failed for input '{0}'.", input));
        }

        return isValid;
    }
}

Let's step back and take a look at what we've got here:

The code remains focused on a single responsibility - following the Single Responsibility Principle.

The extensibility depicted with the decorator example, is a side-effect of the Open/Closed principle: a class is closed for modification, open for extension.

The fact that the MyApplication class can work with any implementation of the IUserInputProvider interface, regardless of what dependencies that implementation might have, is a side-effect of the Liskov Substitution Principle.

Following the Interface Segregation Principle makes our interfaces be very focused as well, ideally exposing only a single member. This point greatly influences cohesion.

The fact that all implementations ("concrete" classes) depend on abstractions, and that these dependencies are injected into their constructor, is following the Dependency Inversion Principle*.

Together, these 5 points spell SOLID.

The IUserInputValidator we're passing to the GetUserInput() method, must come from somewhere. But if we create a new BirthDateValidator() our class will be tightly coupled with that specific implementation, and it will become very hard to test the GetUserInput() method and control validation from the outside.
The MyApplication class can receive the validators it needs in its constructor, and we can extract some of the logic from the Run method, into their own private methods:
public class MyApplication
{
    private readonly IUserInputProvider _inputProvider;
    private readonly IUserInputValidator<DateTime> _dateValidator;
    private readonly IUserInputValidator<YesNoResult> _confirmationValidator;

    public MyApplication(IUserInputProvider inputProvider,
                         IUserInputValidator<DateTime> dateValidator,
                         IUserInputValidator<YesNoResult> confirmationValidator)
    {
        _inputProvider = inputProvider;
        _dateValidator = dateValidator;
        _confirmationValidator = confirmationValidator;
    }

    public void Run()
    {
        var keepRunning = true;

        while(keepRunning)
        {
            var date = GetBirthDate();
            // ...

            keepRunning = !GetExitConfirmation();
        }
    }

    private DateTime GetBirthDate()
    {
        var prompt = "Enter your birth date:";
        var input = _inputProvider.GetUserInput(prompt, _dateValidator);

        return DateTime.Parse(input);
    }

    private bool GetExitConfirmation()
    {
        var prompt = "Exit (Y|N)?";
        var input = _inputProvider.GetUserInput(confirmPrompt, _confirmationValidator);

        return input == YesNoResult.Yes;
    }
}

Notice how the constructor could easily get bloated with possibly as many validators as there are things we want to get from the user. 3 constructor parameters is probably ok. More than that though, and I would be tempted to extract the validators into their own object, so as to keep the message clear: the MyApplication class needs validators - it doesn't do validation.
Let's extract them anyway to see what we get:
public class UserInputValidation
{
    private readonly IUserInputValidator<DateTime> _dateValidator;
    private readonly IUserInputValidator<YesNoResult> _confirmationValidator;

    public UserInputValidation(IUserInputValidator<DateTime> dateValidator,
                               IUserInputValidator<YesNoResult> confirmationValidator)
    {
        _dateValidator = dateValidator;
        _confirmationValidator = confirmationValidator
    }

    public IUserInputValidator<DateTime> DateValidator { get { return _dateValidator; } }
    public IUserInputValidator<YesNoResult> ConfirmationValidator { get { return _confirmationValidator; } }
}

Because the actual calculation algorithm would, by itself, be a reason to change, it's best to encapsulate it in its own class.
@svick's answer could be an implementation of some IAgeCalculator interface.
The MyApplication class now looks like this:
public class MyApplication
{
    private readonly IUserInputProvider _inputProvider;
    private readonly IAgeCalculator _calculator;
    private readonly UserInputValidation _validation;

    public MyApplication(IUserInputProvider inputProvider,
                         IAgeCalculator calculator,
                         UserInputValidation validation)
    {
        _inputProvider = inputProvider;
        _calculator = calculator;
        _validation = validation;
    }

    public void Run()
    {
        var keepRunning = true;

        while(keepRunning)
        {
            var date = GetBirthDate();
            DisplayAge(date);

            keepRunning = !GetExitConfirmation();
        }
    }

    private DateTime GetBirthDate()
    {
        var prompt = "Enter your birth date:";
        var input = _inputProvider.GetUserInput(prompt, _validation.DateValidator);

        return DateTime.Parse(input);
    }

    private void DisplayAge(DateTime date)
    {
        var result = _calculator.GetDifferenceInYearsAndDays(date, DateTime.Today);
        var message = string.Format("Your age: {0} years and {1} days", result.Item1, result.Item2);
        _inputProvider.ShowMessage(message);
    }

    private bool GetExitConfirmation()
    {
        var prompt = "Exit (Y|N)?";
        var input = _inputProvider.GetUserInput(confirmPrompt, _validation.ConfirmationValidator);

        return input == YesNoResult.Yes;
    }
}

The above assumes a ShowMessage method was added to the IUserInputProvider interface; this method is implemented like this:
public void ShowMessage(string message)
{
    Console.WriteLine(message);
}

Now, the Main method can serve its purpose: compose the application!
static void Main(string[] args)
{
    var input = new ConsoleInputProvider();
    var calculator = new AgeCalculator();
    var logger = LogManager.GetLogger("logger"); // gets a NLog logger
    var dateValidator = new ValidationLoggerDecorator(new BirthDateValidator(), logger);
    var yesNoValues = new Dictionary<string, YesNoResult>
                          {
                              { "y", YesNoResult.Yes },
                              { "n", YesNoResult.No }
                          };
    var confirmationValidator = new YesNoValidator(values);
    var validation = new UserInputValidation(dateValidator, confirmationValidator);

    var app = new MyApplication(input, calculator, validation);
    app.Run();
}

As you can see, inversion of control makes it easy to change our minds and swap the dateValidator for a simple BirthDateValidator, or to write a unit test that will only test how date validation operates, or only how age gets calculated, independently of everything else, without requiring user intervention, and with every dependency under full control.
Of course the composition root for this trivial application is instantiating the objects manually (a.k.a. poor man's DI), and it's quite manageable. For a bigger application, you could leave this daunting task to your favorite IoC container, leaving your Main method looking something like this (here using Ninject):
static void Main(string[] args)
{
    var kernel = new StandardKernel(new MyApplicationNinjectModule());
    var app = kernel.Get<MyApplication>();
    app.Run();
}

The entire application's dependency graph gets resolved in a single method call - Ninject isn't the fastest at that, but its nice syntax and great extensibility make it a solid candidate to consider. If you don't know what a StandardKernel does, the above code might seem automagical if I tell you that it does the exact same thing as the previous snippet.
And that's long enough.


Cache DOM lookups

When iterating over the elements with class name mySlide in the for loop, there is a look-up for the dots container (i.e. $('#dots')). Bearing in mind that the example only contains four slide elements, that could lead to excess DOM queries. It is good to store references like that and then utilize the reference:

const dotsContainer = $('#dots');

//later: (e.g. in for loop)
dotsContainer.append('');

Consistency

Why mix native JavaScript (e.g. getting the elements with class name mySlide: document.getElementsByClassName('mySlide');) and then use jQuery later on (e.g. getting elements with class name dot: $('.dot')?

That first block to loop over the elements with class name mySlide could be re-written in jQuery style:

const dotsContainer = $('#dots'); //cache the DOM lookup for later
let slides = $('.mySlide');//document.getElementsByClassName('mySlide');
slides.each(function(i, element) { //for (let i = 0; i < slides.length; i++) {
    $(element).css({left: 100 * i + "%"});//slides[i].style.left = 100 * i + "%";
    dotsContainer.append('');
});

Closure simplification

Some of the closures can be simplified - for instance:

$('.dot').each(function () {
  $(this).removeClass('is-active');
});

can be simplified to:

$('.dot').removeClass('is-active');

And the same is true for the DOM-ready callback:

$(document).ready(function () {
    changeSlide();
});

Can be simplified to:

$(document).ready(changeSlide);

jQuery DOM-ready syntax:

As of jQuery 3.0, only $(handler) is recommended; the other syntaxes still work but are deprecated.1

So that ready callback registration can be simplified to:

$(changeSlide);

Many of these tips are explained in more detail in this article from a couple years avo. It does start off by making one question how much jquery is really needed these days- a valid question. For more on that topic, check out you might not need jquery.

(function ($) {

  let pointer = 0;
  //store instead of looking up each time
 const dotsContainer = $('#dots');
  let slides = $('.mySlide');//document.getElementsByClassName('mySlide');
  slides.each(function(i, element) { //for (let i = 0; i < slides.length; i++) {
    $(element).css({left: 100 * i + "%"});//slides[i].style.left = 100 * i + "%";
    dotsContainer.append('');
  });

  $('.dot').each(function (i) {
    $(this).on('click', function () {
      $('#slider').css('left', -100 * i + '%');
      pointer = i;
      changeDot();
    });
  });

  function changeDot() {
    $('.dot').removeClass('is-active');
    $('.dot').eq(pointer).addClass('is-active');
  }

  function changeSlide() {
    $('#slider').css('left', -100 * pointer + '%');
    changeDot();
    pointer++;
    if (pointer > (slides.length - 1)) pointer = 0;
    setTimeout(changeSlide, 3000);
  }

  $(changeSlide);

})(jQuery);
body {
  background: #28262b;
  color: white;
  font-family: 'Roboto', serif-sans;
}

#slider-wrap {
  width: 700px;
  height: 500px;
  background: #39373a;
  border: 1px solid #17151c;
  text-align: center;
  margin: 0 auto;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
}

#slider {
  height: 500px;
  left: 0;
  position: relative;
  transition: all 300ms ease-in-out;
}

.mySlide {
  position: absolute;
  text-align: center;
  z-index: 100;
  top: 0;
  left: 0;
  height: 500px;
}

.photo {
  position: relative;
  width: 700px;
  height: 100%;
}

.description {
  position: absolute;
  bottom: 0;
  left: 0;
  text-align: center;
  padding: 20px 0;
  width: 100%;
  height: 100px;
  background: rgba(0,0,0,.7);
}

#dots {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px;
}
.dot {
  display: block;
  border: 2px solid white;
  border-radius: 50%;
  margin: 0 10px;
  width: 15px;
  height: 15px;
}
.dot:hover {
  cursor: pointer;
  background: #616161;
}

.is-active {
  background: white;
}
.dot.is-active:hover {
  background: pink;
  border-color: pink;
}

        test1

        test2

        test3

        test4

1http://api.jquery.com/ready/


Here are my comments, in decreasing order of severity:

1) BUGS

Hash function: your hash function does not refer in any way to the bucket (changing) capacity.  The main problem with that is that the function may produce values that are outside of the index bounds of the bucket array (current function may even produce negative values) and then your add() method would throw an exception. but even if you protect from such cases, the function needs to refer to the current capacity in order to spread the values as evenly as possible across the buckets.
Load factor: The code does not refer to the DEFAULT_LOAD_FACTOR: nor does it allow the user to override this value, and more importantly, it doesn't consider this when deciding if the bucket array  needs to be enlarged.  In fact, the whole logic of this decision seems to me to be wrong: when all entries in the bucket are full, you decide to enlarge the size. so theoretically, on the 11th add() call, you would enlarge the size.  This logic needs to be redesigned and it needs to be based on the total number of Entity instances in all the buckets and of course on the load factor.

Note: depending on the hash function implementation, you may need to rehash the entire hash table because if the hash function depends on the capacity, then it may produce different results for existing keys when the capacity changes.  So, the simple System.arraycopy() might not suffice.  This is actually what is done in the JDK implementation.

2) Performance

Adding a new Entity to the linked list involves going through the entire list.  This seems inefficient.  Perhaps you can save the last node in a separate array that has same length as bucket?
The usage of bucketItr seems redundant.  First of all, you copy bucket into bucketItr every time add() is called.  System.arraycopy() is efficient but that doesn't mean it need not be used judiciously. Moreover, the first line in iterator() initializes bucketItr from scratch, making the copy operation in add() completely redundant. but moreover, I don't see the reason for this array at all.  couldn't you loop on bucket in MapItr and just ignore null entries?

3) Best Practices

References to generic type Entity<K,T> should be parameterized: Throughout the code, you refer to the Entity raw type, without the <K, T> generic parameters.  While it seems that this should not produce a bug, (since add() method only accept args of the correct types, this is still considered bad practice (and indeed produces compile warning).
The use of Objects.nonNull() is redundant.  why not use the simple and clear node != null? and while we are there, you first assign node to result and then ask about null. so theoretically, you could return null result.

4) Naming Conventions

an array of buckets should be named buckets or perhaps bucket_array don't you think?


Refractoring OOP vs. Functional Programming Approach

Here are some points:

  and wanted to learn more about classes in python

If you write some piece of code to learn something, delete it and rewrite it.

  construct[o]r and method export_activity could be refactored into one function

If you have a class with a single method converting to a function is what you should do by default. By by default I mean unless you have a really solid reason to do otherwise.

  I was curious if doing so would be beneficial to the program in any way.

Simplicity is second only to (actually needed) functionality. (As XP people say Do the simplest thing that could possibly work.) You do not have to justify making your program simpler by appealing to a higher value.

Some more specific points:

The sections of code where you read an option from the database is the same almost word for word. If you find yourself writing the same code twice or more tellingly *Copy&Paste*ing some snippet you should put it in a function and call it instead. This way you will save yourself a lot of effort. As a general rule you should write everything once and only once.

Your constructor does too much. Anything other that assigning fields should not be done in a constructor. But your constructor is too long even for a method. Extract every snippet of code that is doing something in a function so that when you (or someone else) read it again instead of trying to guess what you are trying to do by reading how you do it you would just read what you are trying to do. This way you (or others) may skip reading the extracted function altogether if they are not interested.

Clean up of resources (files, connections, cursors etx) are usually done by initializing them in with blocks. If the resource does not support with blocks out-of-the box but cleaning-up consists of calling .close() on it, you can wrap the resource in contextlib .closing The clean-up should otherwise be done in finally blocks to ensure they are executed even if an exception is thrown; at least in long running programs, server or desktop applications.

When you decide to catch an exception, catch the most specific exception you expect. Look what else are you catching when you say catch Exception. Here root exception of all mysql.connector errors (apparently mysql.connector.Error) is more suitable.

If you are not going to do anything useful (recover, wrap&rethrow etc) do not catch exceptions. You can do print(err) somewhere else.

In a script put your code in a function, for example main, and call it if __name__ == "__main__": main(). That way you can debug your code in repl, or import it in other scripts/programs as a module. This also allows further refactorings, which I won't elaborate but you can see in the code below.

If a method has many parameters and you are calling it many times with same parameters you can use functools.partial to reduce the noise. (see below)

Also cursor.fetchone() apparently returns tuple and I'm assuming you do not want to pass a tuple as notify_email parameter so you are probably missing a [0] after the fetchone() when reading the admin_email.

Caveat: I am not a python programmer. And haven't tried the program below.
Also the refactored code still needs some Inversion of control refactoring, but ignore this if you do not already know what that means from other languages.

def get_option(cnx, blog_id, option_name):
    table_name = 'wp_' + str(blog_id) + '_options'
    query_ = "SELECT option_value FROM " + table_name + " WHERE option_name=%s"
    with closing( cnx.cursor() ) as cursor_:
        cursor_.execute(query_, (option_name,))
        return cursor_.fetchone()[0]

def get_timespan():
    date_to = datetime.datetime.now()
    # if it monday lets get activity since saturday
    if date_to.weekday() is 0:
        date_from = date_to - datetime.timedelta(days=2)
    # else just get the activity from the past day
    else:
        date_from = date_to - datetime.timedelta(days=1)
    return (date_from, date_to)

def export_blog_activity(blog_id, cnx, mandrill_client):
    notify_email = get_option(cnx, blog_id, 'admin_email')
    encoded_result = get_option(cnx, blog_id, 'wysija')
    decoded_result = phpserialize.unserialize(encoded_result.decode('base64', 'strict'))
    sender_email = decoded_result['from_email']
    date_from, date_to = get_timespan()
    mandrill_client.exports.activity(notify_email, date_from, date_to, None, sender_email,'Sent')

def main():
    # database name and credentials
    # these should eventually be parsed from command line arguments
    database_config = {
        'user': 'root',
        'password': 'password',
        'database': 'wpmudb'
    }
    # Mandrill API Key
    # this should also be parsed from command line
    mandrill_api_key = 'xxxxx_xxxxxxxxxxxxxxxx'
    mandrill_client = mandrill.Mandrill(mandrill_api_key)
    with closing(mysql.connector.connect(**database_config)) as cnx:
        export_activity = functools.partial(export_blog_activity, mandrill_client = mandrill_client, cnx=cnx)
        with closing( cnx.cursor() ) as cursor_:
            # Get all blogs but blog_id 1 since the main site needs no report
            query = "SELECT blog_id FROM wp_blogs WHERE blog_id != '1'"
            cursor_.execute(query)
            for row in cursor_:
                export_activity(row[0])

if __name__ == "__main__":
    try:
        main()
    except mysql.connector.Error as e:
        print "Sql error:", e


Whenever you're dealing with a tile map like this, you should make your best effort to avoid writing code for each direction, replacing it with generalized operations.

The most basic such generalization is to use vectors like [-1, 0] instead of code specific to a direction.

You can create tables of all direction-specific things, like this:

var left  = {vector: [-1, 0], name: "left",  reference: "to the left"};
var right = {vector: [ 1, 0], name: "right", reference: "to the right"};
var up    = {vector: [0, -1], name: "up",    reference: "above you"};
var down  = {vector: [0,  1], name: "down",  reference: "below you"};
var directions = [left, right, up, down];

Now your search function can avoid all repetition:

var WALL = 2;
var FOUNTAIN = 3;

function searchArea() {
  // Search the area around the current position for hidden doors
  var foundThing = "";
  directions.some(function (direction) {
    if (detectWall(direction) === WALL) {
      foundThing = "Hidden Door " + direction.reference;
      return true;  // functions like 'break' in a .some(...)
    }
  });
  if (!foundThing) {
    directions.some(function (direction) {
      if (detectWall(direction) === FOUNTAIN) {
        foundThing = "You are close to a fountain";
        return true;
      }
    });
  }
  status.textContent = foundThing;
}

I moved the tile types into constants WALL and FOUNTAIN so that the code is more readable.

I used some to loop over the array, so instead of break as in a for loop, I used return true (some loops until the provided function returns true, and we don't use the return value of some) and an if statement to skip over the second search. This could be cleaned up some; in particular if you had many things to search for it would be good to have a generalization of "search for many things and stop on the first one" just like we are now generalizing over directions. But this is good enough for this simple case.

Note also that I replaced innerHTML with textContent. Never use innerHTML unless there is no possible substitute for it; if you don't know exactly what you're doing it's a great way to get security bugs.

Here's the revised detectWall:

var tileSize = 20;
function detectWall(direction) {
  var x = Math.floor(player.x / tileSize) + direction.vector[0];
  var y = Math.floor(player.y / tileSize) + direction.vector[1];
  return mapArray[y][x];
}

I have removed the parseInt calls and replaced them with a more direct way to get the result, Math.floor. Note that the vector elements have magnitude 1 instead of a tile size; this allows it to be reused in more ways, such as in your player motion control.

I have pulled out the tile size value into a constant. This is a good thing to do everywhere, so that if you decide you want different tile sizes you only have to change it in one place.

A common additional thing to do is to check whether the computed tile position is out of the bounds of mapArray and if so return a specific value. For example, return the WALL value, so that all of the edges of the map act like walls. I haven't done this here because I don't know how your bounds are defined.


Printing a directory's contents in a loop

Storing a list of file names and iterating over it

FILES="$PWD/file1
$PWD/file2
$PWD/file3"

So you're setting FILES to a newline-separated list of files. That's a bad idea because your script will choke if a file name contains a newline. In some circumstances, where you control the file names, that can be ok, but don't do it unless you really have no better way. Since you're writing a bash script, you never need to do this. Store the file names in an array instead:

FILES=("$PWD/file1" "$PWD/file2" "$PWD/file3")

Then, to iterate over the array:

for i in "${FILES[@]}"; do …

If you had a shell without arrays and decided to use a newline-separated list of file names, then you would need some extra effort to split the lines at newlines only. The IFS variable specifies where to split words in unquoted variable substitutions, so you need to set it to contain only a newline (the default value also contains the ordinary space character and the tab character). Also, the shell performs globbing (filename generation from wildcards) on the results of unquoted variable substitutions, so you need to turn that feature off. Here's a POSIX-compliant way of iterating over the pieces of a newline-delimited string:

IFS='
'
set -g
for i in $FILES; do …

Since you never change directories, you could store just the files' base names instead of full paths. If you control the file names, you then don't need to be so careful with special characters in the names.

Always use double quotes around variable substitutions

I see a lot of places where you write unquoted variable substitutions, e.g. basename $i. Do you really want to split $i into words, then perform globbing on the result? If you don't, then use double quotes: "$i". Only leave off the double quotes if you intend to perform word splitting and filename generation (as in the for loop example above), and then be mindful of the assumptions you're making on the value of the variable.

On the same note, if there was a risk that $i began with a -, you would need to call basename -- "$i" to avoid $i being interpreted by basename as an option. This is not going to happen with your script since $i is an absolute path, beginning with /.

I also recommend not using the backquote command susbsitution, which behaves strangely with nested quotes sometimes. Use $(…), which has an intuitive syntax.

    menu="${menu}\n${count}. $(basename -- "$i")"

Incidentally, note that this puts the characters \n into menu, not a newline. The \n is expanded by echo -e below.

Testing for a number

        if ! echo "$1" | grep -q '^[0-9]\+$'

No need to call grep for that! Here's a simple bash construct:

        if [[ $1 = *[^0-9]* ]]; then … # non-numeric

Here's a POSIX construct:

        case $1 in
          *[!0-9]*) …;; # non-numeric
        esac

Here documents

To insert a multiline string in a script, use a here document. It's more readable.

usage()
{
     cat <<EOF
$(basename -- "$0") -c ID [-l TIME]
-c ID     numeric id for the choice
-l TIME   print output every TIME seconds
-h        print this menu

ID could be:
$menu
EOF
}

It's conventional to use upper case for argument descriptions in the symbolic syntax. Clearly indicate the options that take an argument in the left-hand column. Don't use obscure abbreviations that barely save a few characters like o/p (I think you meant “output”, but I'm not sure).

Parsing the command line

Use the shell builtin getopts rather than the external command getopt. If you have bash, you have getopts. If you don't have getopts, then you're running an embedded shell which may lack other features, so check that the other features you want to use are supported.

To test if there are any arguments, check the number of arguments, in $#.

if [ $# -eq 0 ] || [ "$1" = "-h"]; then …

Actually, you don't need any special handling for -h. Treat it like any other option.

I'm not going to go over getopts usage, there are plenty of examples around.

Before the main loop

set -- $args
…
set -- $list

Remember what I wrote about unquoted substitutions above? Each of these commands performs word splitting and filename generation.

[ "x$choice" = "x" ] && choice=`seq $count`
[ "x$repeatTime" = "x" ] && repeatTime=0

You need to initialize choice and repeatTime before the argument parsing, unless you intended to allow them to be pulled from the environment.

The main loop

while [ true ]

This is a strange way of writing while true. You could also write while [ false ] or while ! [ ! true ]. Keep it simple.

                eval temp=\${${a}}
                cat $SYSPATH${temp}

In bash, you can avoid the use of eval. Also, remember to double quote variable substitutions unless you have a good reason not to.

                cat "$SYSPATH${!a}"


There's nothing wrong with your implementation. There must therefore be something wrong with how you're declaring or populating gp.
Doing it like this:

double gp[4] = {36.987814, -122.107887, 38.989185, -122.116728};
printf("%.6f\n", getDist(gp));

gives the expected answer of 222606.439993


I'm not sure whether you used using namespace std; in the header, or only committed the lesser evil of needlessly importing many names into the global namespace in a header. Anyway, as you are implementing some new library-code, open your own namespace and confine your code to it.
Please read Why is “using namespace std;” considered bad practice?

Let's take a look at your data-structure:

You are using a std::vector, so you have its re-allocation-behavior of roughly doubling the space on demand, and keeping the maximum ever reserved. Not a bad choice.
You store your number as single digit characters. That's workable, but you should really think about storing 0 as 0 not '0'. It makes math easier. Still, I'll keep with that.
Binary operators should, for those where the language allows it, be free functions or at least friend-functions to reduce coupling and enable conversion on the left hand side.
That holds even if you later add overloads to remove those conversions for efficiency.
If you provide some binary operator, it's convenient and customary to also provide the corresponding compound-assignment-operator.

And now your interface:

A conversion (single-argument-ctor or operator Type) should only be implicit if it is lossless and is expected to succeed for all valid inputs.
But "A" is a valid string but will not be accepted.
Use std::string_view instead of constant reference to std::string as input. Thus the caller isn't forced to use a std::string with the possible dynamic allocation (and copy) that entails.

Let's take a look at your ctor:

How does DEBUGF work? Maybe it's a debug-tracing-macro, but what's the first argument for then? Oh well, it's not that important.
You know exactly how long the input is, so why don't you .reserve() space for it to avoid reallocations?
You know calling std::isdigit() with a negative value != EOF is undefined behavior? Cast to unsigned char first!
You optimized your ctor for bad input, as you do a first pass solely to verify the input, and then a second pass to finally store it. Combine the passes into one.
You should probably eliminate leading zeroes. That also makes everything easier.

ubigint::ubigint(std::string_view that) {
    auto pos = that.find_first_not_of('0');
    if(pos != that.npos)
        that = that.substr(pos);

    ubig_value.reserve(that.size());

    for(auto it = rbegin(that); it != rend(that); ++it) {
        if(!isdigit((unsigned char)*it))
            throw invalid_argument ("ubigint::ubigint(" + that + ")");
        ubig_value.push_back((unsigned char)*it);
    }
}

Now, your addition:

While it is often recommended to implement operator+ as a free function in terms of operator+= to avoid repetition, your class doesn't qualify, as it would result in (maybe severe) loss of efficiency. You might want to do it the other way around instead.
Still, that doesn't mean that your try is good. Your first loop repeatedly tests both inputs lengths. Why don't you use std::max(a, b)?
You are using / and % to calculate the carry and the value. While it works, it's highly inefficient. You know the carry is at most one, so use an if-statement and subtraction.
Point 2 comes back to bite you there. See how biasing the numbers with '0' creeps everywhere into the calculations?
The following if-else if-statement is just painful. You are doing the same for both cases, just with a different input-variable. Merge that.
The end really gets me scratching my head. Why do you convert the perfectly usable ubigint into a std::string and then back on returning?
I haven't seen .size() and operator[] in your interface, but adding them is a good idea, so I pretend you already did so. You might want to overhaul your data-structure first though, to be 0 instead of '0'-based.

ubigint operator+ (const ubigint& a, const ubigint& b) {
    if(a.size() > b.size())
        return b + a;

    bool carry = false;
    ubigint result;
    result.reserve(b.size() + 1);
    std::size_t i = 0;
    for(; i < a.size(); ++i) {
        auto c = a[i] + b[i] + carry - '0';
        if(c <= '9') {
            carry = false;
        } else {
            c -= 10;
            carry = true;
        }
        result.push_back(c);
    }

    while(carry && i < b.size()) {
        auto c = b[i] + carry;
        if(c <= '9')
            carry = false;
        else
            c -= 10;
        result.ubig_value.push_back(c);
    }

    if(!carry)
        std::copy(b.begin() + i, b.end(), std::back_inserter(result));
    else
        result.ubig_value.push_back(c);
    return result;
}


Evaluating an XPath with document.evaluate() to get an array of nodes

I don't see a method to directly turn it into an array -- Array.from doesn't work, eg.  The best I could achieve was a little cleanup:

var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null);

var node, nodes = []
while (node = result.iterateNext())
  nodes.push(node);

console.log(nodes);


In DRY Python code, when should I catch/raise exceptions?

Your Option 1 and Option 2 are almmost exactly the same (except that Option 2 is more confusing)

This is because if you don't catch an exception, it will just rise to the top, where it will halt your program. Catching and immediately re-raising it is (almost) the same as never catching it at all.

The only difference can be seen here:

In [1]: def f(a, b):
   ...:     return a / b
   ...:

In [2]: def g(a, b):
   ...:     try:
   ...:         return f(a, b)
   ...:     except ZeroDivisionError as e:
   ...:         raise ZeroDivisionError(e)

When calling g(2, 0), the traceback shows us the place where the error was last raised, which is in the function g:

In [3]: g(2, 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-3-9920cf4d7d78> in <module>()
----> 1 g(2, 0)

<ipython-input-2-a48ddeb59e34> in g(a, b)
      3         return f(a, b)
      4     except ZeroDivisionError as e:
----> 5         raise ZeroDivisionError(e)
      6

ZeroDivisionError: integer division or modulo by zero

When defining a third function h, that does not re-raise the exception, this does not happen and we see the full context of calling f from within h:

In [4]: def h(a, b):
   ...:     return f(a, b)
   ...:

In [5]: h(2, 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-b455367d475f> in <module>()
----> 1 h(2, 0)

<ipython-input-4-7bfa64a165c7> in h(a, b)
      1 def h(a, b):
----> 2     return f(a, b)

<ipython-input-1-44ecddb27ac3> in f(a, b)
      1 def f(a, b):
----> 2     return a / b

ZeroDivisionError: integer division or modulo by zero

Finally note that if you use just a raise (without the explicit exception type and passing it the exception), it will also behave like the function h:

In [6]: def k(a, b):
   ...:     try:
   ...:         return f(a,b)
   ...:     except ZeroDivisionError:
   ...:         raise
   ...:

In [7]: k(2, 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-7-545f9b93e361> in <module>()
----> 1 k(2, 0)

<ipython-input-6-5891fde4d79f> in k(a, b)
      1 def k(a, b):
      2     try:
----> 3         return f(a,b)
      4     except ZeroDivisionError:
      5         raise

<ipython-input-1-44ecddb27ac3> in f(a, b)
      1 def f(a, b):
----> 2     return a / b

ZeroDivisionError: integer division or modulo by zero

So re-raising the exception in this way just obfuscates where the exception originally occurred. This can be a good or a bad thing, but I would not recommend using it unless that is your intention.


Bubble sort with counting swaps and comparsions

Here's a refactored version using a State monad to handle the threading of the counters.

We start with the type of counters, the notion of being Instrumented (i.e. a computation with counters) and some basic combinators increasing the counters.

import Control.Monad.State

data Counters = Counters
  { swaps       :: !Int
  , comparisons :: !Int
  }

type Instrumented = State Counters

incrSwaps :: Instrumented ()
incrSwaps = do
  cnts <- get
  put $ cnts { swaps = swaps cnts + 1 }

incrComparisons :: Instrumented ()
incrComparisons = do
  cnts <- get
  put $ cnts { comparisons = comparisons cnts + 1 }

We can then write down a comparison operator which records the fact it was called by increasing the appropriate counter:

cmpGT :: Ord a => a -> a -> Instrumented Bool
cmpGT x y = do
  incrComparisons
  return $ x > y

Using the same idea, we can port your definition of bubble. Two things to be careful about: you need to use do blocks now and you shouldn't forget to call incrSwaps in the branch where you performed a swap:

bubble :: Ord a => [a] -> Instrumented (Bool, [a])
bubble []  = return (True, [])
bubble [x] = return (True, [x])
bubble (x : y : zs) = do
  xgty <- cmpGT x y
  if xgty
  then do
    incrSwaps
    rec <- snd <$> bubble (x : zs)
    return $ (False, y : rec)
  else do
    fmap (x :) <$> bubble (y : zs)

bsort is not that different (I don't post lastAndInit :: [a] -> (a, [a]) here as it's not important, it's in the gist)

bsort :: Ord a => [a] -> Instrumented [a]
bsort []  = return []
bsort xxs = do
  (hasNoSwaps, bubbled) <- bubble xxs
  if hasNoSwaps
  then return xxs
  else do
    let (y, ys) = lastAndInit bubbled
    next <- bsort ys
    return $ next ++ [y]

Finally, bsort' corresponds to the combination of an initial state and runState:

initialCounters :: Counters
initialCounters = Counters 0 0

bsort' :: Ord a => [a] -> ([a], Counters)
bsort' xs = bsort xs `runState` initialCounters


You should make a class. This lets you consolidate the implementation to be consistent, and simplifies a number of the details. You can also implement __str__ and __repr__ to make it easier to print them.  Use string formatting for this

class LogicalOperator(object):

    def __init__(self, name, symbol, functor):
        self.name = name
        self.symbol = symbol
        self.functor = functor

    def __call__(self, a, b):
        return bool(functor(a, b))

    def __str__(self):
        return self.name

    def __repr__(self):
        return "{}, {}".format(self.name, self.symbol)

Inheriting from namedtuple makes this easier (thanks to Caridorc for pointing out in the comments).

from collections import namedtuple

class LogicalOperator(namedtuple('LogicalOperator', 'name symbol functor')):
    # no __init__ now
    # rest is unchanged

This way you've separated your concerns. The class encapsulates "what is a logical operator and how do I make it print pretty", and then we use it as necessary to get value and formatting for it.

Then we can still create all of our logical operators, but we do it with classes and a tuple instead of a dict and tuples.

ops = (
    LogicalOperator('AND', '∧', operator.and_),
    LogicalOperator('OR', '∨', operator.or_),
    LogicalOperator('NOT', '¬', lambda a, _: not a),
    LogicalOperator('NOR', '↓', lambda a, b: not (a or b)),
    LogicalOperator('XOR', '↮', operator.xor),
    LogicalOperator('XNOR', '↔', lambda a, b: not (a ^ b)),
    LogicalOperator('NAND', '↑', lambda a, b: not (a and b))
)

A better way to pad strings is to use string.rjust. An even better way is to use the Format Specification Mini-Language.

Then we can put it all together.

if __name__ == '__main__':
    column_width = 25
    table = list(itertools.product([False, True], repeat=2))
    for op in ops:
        print(op)
        print("-"*column_width)
        for left, right in table:
            print("|{:^5}|{:^5}|{:^5}|".format(left, right, op(left, right)))
        print("-"*column_width)

Also, you could use more whitespace throughout.  Makes it easier to read.


Invariants

for read in data.itertuples():
    for ref in ref.itertuples():
        x = np.isnan(read[3:]).argmax(axis=0)

x doesn't change in the inner loop, so you can move it out of the inner loop, and not execute it repeatedly.

for read in data.itertuples():
    x = np.isnan(read[3:]).argmax(axis=0)
    for ref in ref.itertuples():

These following two lines are identical, apart for the end-points of the slices:

if np.isclose(read[4:  6     ],ref[7:  9    ],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x:
if np.isclose(read[4:read_pos],ref[7:ref_pos],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x:

You already have a variable for the end-points.  Why not use it for the first line as well, and only have one case?

read_pos = 3+x-1 if x > 2 else 6
ref_pos  = 6+x-1 if x > 2 else 9

Once you've found your target, you can't ever add it again ...

if not read[1] in checklist:
   match.append([read[1], ref[5]])
   checklist.add(read[1])

... but you don't break out of your inner search, which is now pointless.

If I haven't made any errors, this should be a litte faster:

match = []
checklist = set()

for read in data.itertuples():

    x = np.isnan(read[3:]).argmax(axis=0)

    if x >= 2  and  read[1] not in checklist:

        read_pos = 3+x-1 if x > 2 else 6
        ref_pos  = 6+x-1 if x > 2 else 9

        for ref in ref.itertuples():

            if np.isclose(read[4:read_pos],ref[7:ref_pos],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x:
                match.append([read[1], ref[5]])
                checklist.add(read[1])
                break

    if read[1] not in checklist:
        match.append([read[1], "not found"])
        checklist.add(read[1])


Replace the content of a file by zero-bytes and keep the same filesize

Here are some suggestions that may help you improve your code.

Use return rather than exit()

The effect of using exit(0) or exit(1) is going to be identical to return 0 or return 1 but with one difference: exit() is a library call and would therefore require #include <stdlib.h> (which this program does not have) while return does not require any particular #include.  Also note that exit(0) implicitly flushes and closes files, as does return 0.  Further, the equivalent to return 0; is provided by the compiler if omitted (since C99), so technically, the last two lines of the program:

fclose(f);
exit(0);

could both be omitted with no change to the function of the program.  If, however, you decided to move this part of the function to a separate function, I'd suggest keeping fclose(f); and using return 0; rather than exit(0);.  Tastes vary on this point.

Don't cram multiple statements per line

Lines such as this:

if ((f = fopen(argv[1], "rb+")) == NULL) { perror("Error opening the file"); exit(1); }

tend to be more readable if formatted as separate lines:

if ((f = fopen(argv[1], "rb+")) == NULL) {
    perror("Error opening the file");
    return 1;
}

Check return values

The code does check for the return value of fopen, which is good, but does not check the return values for fseek, ftell and fwrite which can also fail.

Use named constants

The number 1024 appears multiple times in the code.  If one wanted, for instance, a 2k buffer instead, one would have to change it all three places.  Using a named constant instead simplifies maintenance and makes the code easier to read as well.

Understand the bounds of standard C

The C language is very expressive and has a great number of handy library functions for doing things like reading and writing files.  However, what exactly the underlying operating system does to manage files on disk is outside the domain of C and squarely in the domain of the OS and hardware designers.  There is, in short, no guarantee that this code will physically overwrite the same sectors of physical media, and more importantly, no provision in standard C for doing so.  To take just one example, if I run a virtual Windows machine on a system that actually runs on a cluster of Linux machines, there might not actually even be any physical media.


Whether it makes sense to break this up is somewhat contextually dependent on whether you anticipate reusing this pattern elsewhere, IMO.  If it's a one-off it might be cleaner to simply do it in-place as in your first example; I don't think the second example is particularly easier to follow, since your execute method still contains a lot of logging-related code either way, and it has the undesirable side effect of adding more state to your object that could otherwise be locally scoped.

However, if you do plan on reusing this logging logic, a neat way to separate its implementation details from the function that you're trying to log is putting it in a decorator:

import functools

def logged(logger_name):
    logger = logging.getLogger(logger_name)

    def decorator(func):
        @functools.wraps(func)
        def wrapped_func(self, *args, **kwargs):
            start_time = time.time()
            logger.debug("%s starting execution" % self)
            ret = func(self, *args, **kwargs)
            exec_time = time.time() - start_time
            logger.debug(
                "%s returned %s after %.4f seconds" % (self, ret, exec_time)
            )
            return ret
        return wrapped_func
    return decorator

class HTTPRequest(object):
    def __init__(self, url, method, **kwds):
        self.logger = logging.getLogger(__name__)
        self.url = url
        self.method = method
        self.request_kwds = kwds
        self.logger.debug("Created instance %s" % self)

    @logged(__name__)
    def execute(self):
        response = HTTPResponse(
            request=self,
            request_response=requests.request(
                url=self.url,
                method=self.method,
                **self.request_kwds
            )
        )
        response.raise_for_status()
        return response

Now all of the logging logic is completely removed from the body of execute, and it lives in that one little @logged decoration, which you can reuse with any other method on any other object (note that the decorator is written to assume it's being applied to an instance method, because it uses a self parameter in its logging).  Note that it always measures the overall execution time of the decorated function starting before it's called and ending after it returns (I'm not sure if raise_for_status() blocks long enough for it to make a meaningful difference that the stopwatch ends after you return the response rather than after you create it).

There are a lot of potential further directions to take this -- for example, you could create a logging superclass/mixin that also encapsulates the logging in __init__, or that handles logging-related state that needs to persist in between method calls (e.g. if you want to do any sort of aggregation), and thereby have the ability to make your logging significantly more sophisticated without exposing any of that complexity in the rest of your code.  So this approach scales in lots of interesting ways, but again, whether it's worthwhile depends on whether you actually need that scaling.

Making all these things work in a thoroughly typesafe way is also doable but adds a decent amount of complexity that I won't even go into here.

A simpler approach that's less extensible but sticks a lot closer to your original implementation while still getting most of the code out of execute would be to use a higher order function within the class (similar to the decorator approach but with less magic):

class HTTPRequest(object):
    def __init__(self, url, method, **kwds):
        self.logger = logging.getLogger(__name__)
        self.url = url
        self.method = method
        self.request_kwds = kwds
        self.logger.debug("Created instance %s" % self)

    def measure_request_time(self, func, *args, **kwargs):
        self.logger.debug("%s starting request" % self)
        start_time = time.time()
        ret = func(*args, **kwargs)
        self.execution_time_seconds = time.time() - start_time
        self.logger.debug(
            "%s received response %s after %.4f seconds"
            % (self, ret, self.execution_time_seconds)
        )
        return ret

    def execute(self):
        self.response = measure_request_time(
            HTTPResponse,
            request=self,
            request_response=requests.request(
                url=self.url,
                method=self.method,
                **self.request_kwds
            )
        )
        self.response.raise_for_status()
        return self.response


CakePHP view with interleaved PHP and HTML

Why not go with a template like Twig or Blade which would make the syntax a lot cleaner, while retaining most of all the controls. Also, remember that the view is for showing data, try to maintain as much logic OUT of the view as possible.

Here's an untested version of your code with Blade:

    @foreach($list as $l)

        @if($l['flag_count'] > 0)
            {{ $l['flag_count'] }}
        @else
            {{ $l['flag_count'] }}
        @endif

        {{ $this->Html->link("Edit", $l['edit_route']) }}

            {{ $l['translation']['english'][ $l['Content']['content_type'] . "_name" ] }}

        @if($l['translation']['english'] != $current_language_id)

                {{ $l['translation']['translate_to'][ $l['Content']['content_type'] . "_name" ] }}

        @endif

        @if('range' === $l['Content']['content_type'])

                display on home?

        @endif

    @endforeach


If you have always at most 4 player and the number of positions is smaller than 100 (like your 16 start positions), then checking all possible position and players takes 1004, which is small enough. but if you looking for faster solution (harder implementation) You can use Maximum Weighted Matching by Edmound, First you should create a graph, you can draw graph, by setting

Vertices = players position Union available position as nodes.
Edges = draw edge between each player and all available positions

For setting weight to edges you should do it in reverse, In fact first find the maximum distance (between all possible (player , position) pair, name it MaxDistance, now set your graph edges as MaxDistance - EdgeDistance + 1, here EdgeDistance is distance between player and desired position.

You can find good implementation of Edmond's algorithm in c++ in Lemon package.


qos method call using DateTime and Stopwatch

StopWatch is definitely better for timing stuff, but the semantics of the two versions are different. With DateTime you have this:

private int ExecTransWithStats(int connection_id, string name, string parameters_string, byte[] bytes)
{
    DateTime nowTime = DateTime.Now;
   ...

and with StopWatch you have that:

private Stopwatch workingTime = Stopwatch.StartNew();
private int ExecTransWithStats(int connection_id, string name, string parameters_string, byte[] bytes)
{
    long nowTime = workingTime.ElapsedMilliseconds;
  ...

Bug?

The stopwatch starts as soon as the instance is created, it looks like you're misusing the stopwatch.

long nowTime = workingTime.ElapsedMilliseconds;

That's not how a stopwatch works. That will give you the number of milliseconds elapsed between the instantiation of your class and the moment ExecTransWithStats gets called. I doubt this is what you are expecting.


Determining expiration date based on list of months in which to refresh

I suggest you to improve naming:

months instead of listOfMonths because its not list, and its better not to include variable type description into name
date instead of curDate - its better to avoid abbreviations, also current method should not care whether moth is current or not - it just search previous month from given months
Possibly I would rename method to something like GetPreviousMonth

Also I don't see any need to have nullable type for months sequence. It should have integers. If month exist in list, then you can avoid sorting - so do this check first. Thus you are not going to add/remove month, then saving ordered sequence to array is little better:

public static DateTime GetCheckDate(IEnumerable<int> months, DateTime date)
{
    if (month == null || !months.Any() || months.Contains(date.Month))
        return date.AddDays(1 - date.Day);

    var orderedMonths = months.OrderByDescending(m => m).ToArray();
    if (date.Month > orderedMonths.First())
        return new DateTime(date.Year, orderedMonths.First(), 1);

    if (date.Month < orderedMonths.Last())
        return new DateTime(date.Year - 1, orderedMonths.First(), 1);

    return new DateTime(date.Year, orderedMonths.First(m => m < date.Month), 1);
}

But I also prefer readability on first place (performance should be improved only if its a problem) so I would go with Max and Min month instead of sorting them and keeping in mind what is Last and what is First:

public static DateTime GetCheckDate(IEnumerable<int> months, DateTime date)
{
    if (month == null || !months.Any() || months.Contains(date.Month))
        return date.AddDays(1 - date.Day);

    if (months.Max() < date.Month)
        return new DateTime(date.Year, months.Max(), 1);

    if (date.Month < months.Min())
        return new DateTime(date.Year - 1, months.Max(), 1);

    return new DateTime(date.Year, months.Where(m => m < date.Month).Max(), 1);
}

If I would continue making it more readable, then following extension methods would be useful:

public static DateTime FirstDayOfMonth(this DateTime date, int month = 0)
{
    return new DateTime(date.Year, month == 0 ? date.Month : month, 1);
}

public static DateTime PreviousYear(this DateTime date)
{
    return date.AddYears(-1);
}

Now whole method is very easy to understand:

public static DateTime GetCheckDate(IEnumerable<int> months, DateTime date)
{
    if (month == null || !months.Any() || months.Contains(date.Month))
        return date.FirstDayOfMonth();

    if (months.Max() < date.Month)
        return date.FirstDayOfMonth(months.Max());

    if (date.Month < months.Min())
        return date.PreviousYear().FirstDayOfMonth(months.Max());

    return date.FirstDayOfMonth(months.Where(m => m < date.Month).Max());
}


Unit Tests should not have a dependency on the application bundle at runtime which could not be injected on the init phase or by a method arguments

The given Utility class has a static methods which act like a shortcuts to longer syntax calls. This methods calls directly methods on Bundle class object which is cannot be mocked. The solution is to move Bundle -> infoDictionary outside of a method and set it as a static property. Now, in the app the dictionary can reference a dictionary from the app bundle and in test bundle will reference a mocked dictionary. The main purpose of a unit testing this methods will be to validate usage of given dictionary and keys to access demanded values.

Utility methods aka class methods are not dependency injection friendly and that makes them more complicated to test
UtilitiesMock is not a mock, it's more a proxy / facade / wrapper class

Solution:

protocol BundleInfoDictionaryShortcuts {
    static var bundleMainInfoDictionary: [String : Any]? { get set }
}

enum BundleInfoDictionary: String {
    case keyCFBundleShortVersionString = "CFBundleShortVersionString"
    case keyCFBundleVersion = "CFBundleVersion"
}

class Utilities: BundleInfoDictionaryShortcuts {

    static var bundleMainInfoDictionary: [String : Any]? = Bundle.main.infoDictionary

    static func getAppVersion() -> String {

        guard let version = bundleMainInfoDictionary?[BundleInfoDictionary.keyCFBundleShortVersionString.rawValue] as? String else {
            fatalError()
        }
        return version
    }

    static func getAppBuildNumber() -> String {
        guard let number = bundleMainInfoDictionary?[BundleInfoDictionary.keyCFBundleVersion.rawValue] as? String else {
            fatalError()
        }
        return number
    }
}

// File: BundleInfoDictionaryShortcutsTests.swift

class BundleInfoDictionaryShortcutsTests: XCTestCase {
        static let appVersion = "1.0.1"
        static let appBuildNumber = "120"

        override class func setUp() {
            super.setUp()
            Utilities.bundleMainInfoDictionary = [
                BundleInfoDictionary.keyCFBundleShortVersionString.rawValue: appVersion,
                BundleInfoDictionary.keyCFBundleVersion.rawValue: appBuildNumber
            ]
        }

        func testGetAppVersion() {
            XCTAssertEqual(Utilities.getAppVersion(), Self.appVersion)
        }
        func testGetAppBuildNumber() {
            XCTAssertEqual(Utilities.getAppBuildNumber(), Self.appBuildNumber)
        }
    }

// File: BundleInfoDictionaryShortcutsTests.swift

    class BundleInfoDictionaryTests: XCTestCase {
        func testKeys() {
            XCTAssertEqual(BundleInfoDictionary.keyCFBundleShortVersionString.rawValue,"CFBundleShortVersionString")
            XCTAssertEqual(BundleInfoDictionary.keyCFBundleVersion.rawValue,"CFBundleVersion")
        }
    }


Java Max-Stack implementation to return maximum value in the stack

Running time:

The running time is not O(lg(n)) is O(n) since you are building a max heap.

You iterate over  elements (no leaf elements). Knowing this we can conclude that is at least O(n).
The function called buildMaxHeap is actually O(h), h being the height of the node (which you call i). So because the height of any heap is

and because this summation to the infinity ends up being constant:

we get O(n).

Names:

buildMaxHeap doesn't actually builds the max heap so it name is not appropriate. This function is commonly called maxheapify and is to maintain the heap property. Also I would change the name of parameter named clone for something more generic, because in that context it doesn't matter if its a clone or not.

Pop:

Pop doesn't return the element poped, neither I see a top function so this stack is pointless.

Code

This part:

 if ((c + 1) <= j && clone[c] <= clone[c + 1]) {
     c = c + 1;
 }

Can be change to this

 if ((c + 1) <= j && clone[c] < clone[c + 1]) {
     ++c;
 }

Because if both are equal why bother incrementing c ?

This is not that important though I am just nitpicking.

This part could be improved as well:

 if (clone[root] < clone[c]) {
    int t = clone[root];
    clone[root] = clone[c];
    clone[c] = t;
    root = c;
 } else {
    root++;
 }

For the swapping it would be more readable to implement a method named swap. Also if there is no swapping the algorithm should terminate, because the lower subtrees are already max heaps so its pointless. This is the reason why building a max heap starts at floor(n/2).

so this part would end up like this

 if (clone[root] >= clone[c]) break;

 swap(clone, root, c);
 root = c;

Conclusion:

Given the hidden constant factor in your function getMax (cloning the array and the hidden constant factor in building a max heap) its better to do it the straightforward way:

    int max = Integer.MIN_VALUE;
    for(int i = 0; i <= top; ++i)
        max = Math.max(max, stack[i]);

or for Java 8:

    OptionalInt i = Arrays.stream(stack,0, top+1).max();

Additional notes:
This also can be improved with Java generics.


Most concise Python radix function using functional constructions?

From my perspective, I'd say use the generator. It's concise and easily readable to most people familiar with Python. I'm not sure if you can do this in a functional sense easily without recreating some of the toolkit of functional programming languages. For example, if I wanted to do this in Haskell (which I am by no means an expert in, so this may be a horrible way for all I know), I'd do something like:

radix :: Int -> Int -> [Int]
radix x n = takeWhile (> 0) $ iterate (\z -> z `div` n) x

You can certainly recreate takeWhile and iterate, however, this only works due to lazy evaluation. The other option is, as you've said, using log and basically recreating scanl:

def scanl(f, base, l):
    yield base
    for x in l:
        base = f(base, x)
        yield base

def radix(n, r):
    return scanl(operator.__floordiv__, n, (r for x in range((int)(log(n, r)))))

So my answer is going to be "No" (predicated on the fact that someone smarter than me will probably find a way). However, unless you are playing Code Golf, I'd again suggest sticking with the generator version.


Already gave in the wrong placed question, anyway here is my solution: codepad.viper-7.com/zTLliA
Copy&paste is never a good idea.
if (isset($_POST['number']) && is_numeric($_POST['number']) && (($_POST['number'] > 0) && ($_POST['number'] <= 20))) {
    $number = $_POST['number'];
    for ( $counter = 1 ; $counter <=10; $counter++ ) {
        $temp = $number * $counter ;
        echo "$number x $counter = $temp<br />";
    }
} else {
    echo "Please enter a number between 1 and 20";
}

A single for is enough. In the if statement we check if the $_POST['number'] exists, if it's actually a number and if it is between 1 and 20.


This piece of ABAP code should run through multiple tables and run a COUNT in all of them.

Your first query will only keep 1 value for <fs_curr_tab>-table_description so you might as well go for

  SELECT SINGLE ddtext AS table_description
  FROM dd02t
  INTO <fs_curr_tab>-table_description
  WHERE tabname = <fs_curr_tab>-table_id AND ddlanguage = 'EN'.

The AS table_description is not needed since you are not using CORRESPONDING, I also do not like the hardcoded language, I would take the user language. I also prefer EQ over =

  SELECT SINGLE ddtext
  FROM dd02t
  INTO <fs_curr_tab>-table_description
  WHERE tabname EQ <fs_curr_tab>-table_id
    AND ddlanguage EQ sy-langu.

If this is called with a large amount of tables (say over 50), then you should definitely consider reading all the table names at once with FOR ALL ENTRIES IN before the loop.

Finally, this could go horribly wrong if that table does not have an 'ID' column. If it were me I would check first the DD03L table to make sure the table does have an ID column. If I am not mistaken, DBIF_RSQL_INVALID_REQUEST is a non-catchable exception and would send the program straight into an abend.


Converting between Fahrenheit and Celsius

For someone who wasn't conscious when he wrote this code, it looks quite nice :)

Some observations:

Tests should do only one thing

This is OK in most of your tests, but you got a little 'lazy' at the last two tests - make a different test for each should. You could use RSpec's one-liner syntax, just for the fun of it:

 describe "in degrees celsius" do
   subject { Temperature.from_celsius(50) }

   its (:in_celsius) { should == 50 }
   its (:in_fahrenheit) { should == 122 }
 end

Meaningful Names

Again, in most cases, you are doing fine, and there may even be good arguments to say that @f and @c are clear enough in context, but there really is no reason not to call them @fahrenheit and @celsius. temp is also a quirk you should fix...

When things don't change

After you create a Temperature instance, its celsius and fahrenheit values will never change, so there is no reason why you should continue to calculate them - simply store the result in the appropriate member:

  def in_fahrenheit
    return @f if @f
    @f = (@c * (9.0 / 5.0)) + 32
  end

You can even make this shorter, using the ||= operator, which will compute and assign the member if it is not assigned:

  def in_fahrenheit
    @f ||= (@c * (9.0 / 5.0)) + 32
  end

This is looking more and more like a getter function, and really, since it calls for the state of the instance, you don't need to imply there is ever a calculation, simply call it fahrenheit:

def fahrenheit
  @fahrenheit ||= (@celsius * (9.0 / 5.0)) + 32
end

Have a consistent style

In your code you call methods with hashes with three different styles:

Temperature.new({f: temp})
super(c: temp)
Temperature.new(:c => 50).in_celsius.should == 50

All of these styles work, but it is better to choose one, and stick with it. When using a hash in method, my favorite is the second style (Temperature.new(f: temp))

Use language features

Since Ruby 2.0, named parameters are supported, and you are encouraged to use it. It will give you free validation, as any parameter which is not one of those you declared, an error will be issued:

def initialize(celsius: nil, fahrenheit: nil)
  @fahrenheit = fahrenheit
  @celsius = celsius
end

One last point, regarding your Celsius and Fahrenheit classes, I personally don't see any utility in having them, since they add no logic besides a construction convenience, and may even confuse, since their name implies they support only one scale or the other...

So now, your class will look like this:

class Temperature

  class << self
    def from_fahrenheit fahrenheit
      Temperature.new(fahrenheit: fahrenheit)
    end

    def from_celsius celsius
      Temperature.new(celsius: celsius)
    end
  end

  def initialize(celsius: nil, fahrenheit: nil)
    @fahrenheit = fahrenheit
    @celsius = celsius
  end

  def fahrenheit
    @fahrenheit ||= (@celsius * (9.0 / 5.0)) + 32
  end

  def celsius
    @celsius ||= (@fahrenheit - 32) * 5.0 / 9.0
  end
end


Proper use of a generic value type wrapper class

It is unclear how to use this class if I want to subscribe to two different objects that implement, say, Value<double>. There is no way to tell which of the two values has changed. This looks like a pretty major design flaw, unless I am missing something. So you should probably either use regular events (so I can supply different handlers for different values) or provide "source" argument. Personally, I think first option is better. You should also consider using proper event aggregator instead of storing the list of listeners in values themselves.

Also I think you should have an actual property instead of Get() and Set() methods. And you can make listeners field read-only.


Write a class for Team which should have function to prints players details

You should learn about Python's magic (or dunder) methods. They allow your custom class to interact with the built-in functions (by e.g. defining what a + b means for objects of your class, or, which is relevant here, what print(team) or print(player) mean.

For this I would add two methods, first the __iter__ method, which allows you to iterate over your team and get each player, and the __str__ method, which defines how your class prints:

class Player:
    def __init__(self, name, age, skills, style=None):
        self.name = name
        self.age = age
        self.skills = skills
        self.style = style

    def __str__(self):
        return f"{self.name} {self.age} {self.skills} {self.style or ''}"

class Team:
    def __init__(self, name, players=None):
        self.name = name
        if players is not None:
            self._players = list(players)
        else:
            self._players = []

    def add_player(self, obj):
        if isinstance(obj, Player):
            self._players.append(obj)
        else:
            print("Please provide player object")

    def __iter__(self):
        return iter(self._players)

    def __str__(self):
        out = [f"Team name: {self.name}", "Players:"]
        out.extend(str(player) for player in self)
        return "\n".join(out)

if __name__ == "__main__":

    players = [Player("Mahendra", 46, "Wicket Kipper", "Right-Hand Batsman"),
               Player("Sachin", 35, "Batsman", "Right-Hand Batsman"),
               Player("Saurabh", 44, "Batsman", "Left-Hand Batsman"),
               Player("Zahir", 38, "Bauwller", "Medium Pace Bauwller"),
               Player("Yuvraj", 43, "All rounder")]

    india = Team("India", players)
    print(india)

    # equivalent:
    print("Team name:", india.name)
    print("Players:")
    for player in india:
        print(player)

I also added an optional keyword argument to the Team constructor to allow passing in a list of players right away.

I also removed the explicit inheritance from object, which is not needed anymore in Python 3 (only for backwards compatibility with Python 2), as all classes are new-style classes.


It's not surprising that this is too slow:
you're reading data byte-by-byte.
For faster performance you would need to read larger buffers at a time.

If you want to compare files by content, use the filecmp package.

There are also some glaring problems with this code.
For example, instead of opening a file, doing something in a try block and closing the file handle manually, you should use the recommended with-resources technique:

    with open(filename1, "rb") as f:
        b = f.read(1)
        # ...

Finally, the function name and all variable names are very poor,
and don't help the readers understand their purpose and what you're trying to do.


Determining if two Strings have common subtrings of a given length in Java

Don't add unnecessary pre-checks
Your method getSubstringsSet starts with two early returns:
if(aString.length() < lengthOfSubstring){
    return setOfSubstrings;
}

if(aString.length() == lengthOfSubstring){
    setOfSubstrings.add(aString);
    return setOfSubstrings;
}

You actually don't need them. The rest of the code handles both cases just fine and it doesn't add to clarity or improve performance. Early-returns should be used when the rest of the code can then assume a condition that was checked, making its code simpler; but it is not the case here.
Use built-in methods
To add the substrings, you are currently doing:
StringBuilder sb = new StringBuilder();

//add each substring of length (lengthOfSubstring) to the setOfSubstrings.
for(int j = 0; j < lengthOfSubstring; j++){
    sb.append(charArray[i + j]);
}

setOfSubstrings.add(sb.toString());

So you're creating a new StringBuilder and then appending each character. This is a complicated way of retrieving the substring between two indices. It also allocates a new StringBuilder each time which isn't really needed.
You can just have
setOfSubstrings.add(aString.substring(i, i + lengthOfSubstring));

In the same way, stringIntersect is a lot more complicated than it should be.
First of all, you are using a label outerForLoop and then using it to break out of the inner loop with break outerForLoop;. This is generally not a good practice. What this shows is a missing method: what you really want is to make a method isIntersection(set1, set2) that would determine if the two sets have elements in common.
However, you don't even need to write one, since it is already built-in: Collections#disjoint. This method returns true if the two given collections are disjoint, i.e. have no elements in common. Therefore, you can remove your double for loop and just have:
boolean sameSubstringInBothStrings = !Collections.disjoint(setOne, setTwo);


OK, here goes:

No. You're using using which means that the object will be disposed of in the end of the block. As part of the Dispose() method, the connection will be closed and its resources released.
Not manually, you should open another using block to cause the object to Dispose() in the end.
Thanks to the using block, when an exception occurs, the object will be disposed because you're thrown out of the block.
"Enhance" is vague...


Most efficient solution for USACO: Cow Gymnastics - Python

Suggestions:

Use the variable names from the problem specification instead of inventing your own (just make them lower-case since that's preferred in Python code). Makes it easier to see the connections. Unless yours are much better.
I guess nums is plural so num is a single number, but you can iterate it? Bad name. And wth does asdf mean?
Python prefers snake_case for function names.
To be honest, the lack of any explanation of your method, the name asdf and the highly convoluted code made me give up reading it. But here's my solution, simply counting occurring pairs and then the result is the number of pairs that appeared K times:

from itertools import combinations
from collections import Counter

ctr = Counter()
with open('gymnastics.in') as f:
    k, _ = map(int, next(f).split())
    for session in f:
        cows = session.split()
        ctr.update(combinations(cows, 2))

with open('gymnastics.out', 'w') as f:
    print(list(ctr.values()).count(k), file=f)


Updating the total when any of a set of spinners changes its value

You could use a jQuery object to query all four of the spinners.

function sum(values) {
    return values.reduce(function (prev, next) { return prev + next; }, 0);
}

function inputToInt(input) {
    return parseInt($(input).val());
}

$('.spinner-input, #flight-class').change(function() {
    var passengerCounts = $('.passenger-list .spinner-input');
    var totalCount = sum(passengerCounts.toArray().map(inputToInt));

    var fc = $('#flight-class option:selected').text();

    $('#kisi-sayisi').val(totalCount + ' - ' + fc);
});


Python function to find the next smaller number with same set of digits

The solution to a good algorithm is a clear logic. Your code uses the "hammers" that are present, spring to mind, and do a tiny bit more than needed. So start to find a logic first.

To get the next smaller number the most strict algorithm would be:

Example: 1253479

Start from the last digit to the first as long as the digits are decreasing or equal. 12[5]+increasing 3479, 5 > 3.
From the increasing tail pick the element just smaller (4), and reverse the tail. 12(4)+decreasing 97[5]3.

Result: 1249753

The math is relatively simple, and the algorithm linear to the length.

  As you see the code can do with the "hammers", functions, you use.

Explanation (on request)

Say you have a number 1253479 = prefix 12, digit 5, and increasing suffix 3479. (5 > 3 hence a smaller permutation on digit+suffix is possible)

An increasing (non-decreasing) suffix 3479 is the first minimum permutation; other permutations like 4379 are greater.

A decreasing (non-increasing) suffix 9753 is the last maximum permutation; other permutations like 9735 are smaller.

Hence a permution++ resp. permutation-- works like:

1 2 5 3 4 7 9
     \ / / /
= =
     / \ \ \
1 2 4 9 7 5 3

Roughly reminiscent of increasing/decreasing an integer on paper with a suffix 00...0.

A proof would be more for a math forum.

As this answer has its probably deserved downvotes (it insists on a redesign), I leave it at that.


Implementing redirect in Redux middleware

Instead of creating your custom promiseMiddleware you could use the redux-thunk middleware which accepts a function as an action. And the function will be called with dispatch and getStore as parameters.

Imagine you would like to fetch some data.. and you want to do it as an action. like dispatch(getPost(id))

normally your actionCreator getPost would return the action object,

const getPost = (id) => {
  return {
    type: "FETCH_POST",
    id
  }
}

But when you use redux-thunk you can return a function:

const getPost = (postId) => {
  return dispatch => {
      // Now you can use dispatch inside this block, even for async calls..
      // Start fetching..
      dispatch({type: "START_LOADING_POST" }) // imagine this could change your state to {isLoading: true}

      http
       .get("from.somewhere.net/post/" + postId)
       .then((data) => dispatch({type: "POST_LOADED_SUCCESS", postId, data }))
       .catch((error) => dispatch(loadingPostFailed({postId, error})))
  }
}

I think you know how to apply the middleware to the store, so I skip it. Hope it makes it clear how you can extend your actionCreators with redux-thunk to functions and use them specially for async tasks, like promises or even with callback-based libraries.

Redux thunk was part of redux, but its now an own package, but also maintained by Dan Abramov, check out the repo: https://github.com/gaearon/redux-thunk

If you would like to save some time by writing every actionCreator by hand you could create an creator for the actionCreator :D sounds funny, but take a look at this:

const promiseActionCreator = type => {
   const
      start    = type + "_START",
      resolved = type + "_RESOLVED",
      failed   = type + "_FAILED";

   return (params) => (dispatch, getState) => {

      dispatch({type: start})

      http
          .get(params.url)
          .then(result => dispatch({type: resolved, result }))
          .catch(error => dispatch({type: failed, error }))
   }
}

// Now you can create/generate your special promise based actionCreator
const getPost = promiseActionCreator("POST_LOADER");


If the non-nil results of do-something are guaranteed to be logical true, you can easily use some:

  (some pred coll)

  Returns the first logical true value of (pred x) for any x in coll,
  else nil. One common idiom is to use a set as pred, for example
  this will return :fred if :fred is in the sequence, otherwise nil:
  (some #{:fred} coll)

(defn find-first-3
  [do-something range]
  (some do-something range)
)

If you expect do-something to return false as possible, non-nil value, you could use keep:

  (keep f coll)

  Returns a lazy sequence of the non-nil results of (f item). Note,
  this means false return values will be included. f must be free of
  side-effects.

(defn find-first-4
  [do-something range]
  (first (keep do-something range))
)

As for the chunk-issue: You should not bother if you're not hitting any performance issues or other problems. Otherwise, if you really want to get rid of it, the unchunk-trick you mentioned is totally fine IMHO, until Clojure will offer an official, built-in option (maybe it will someday).


Prepare once - execute multiple times

Prepared statements not only prevent SQL injection, but also enable you to only prepare a statement once, and then execute it multiple times with different values for increased performance:

$query_run = $db->prepare("SELECT `length_ft` FROM `runways` WHERE `airport_ident` = :ident");
$query_run->bindParam(":ident", $i);

foreach ($a as $z) {
    $i = $z['ident'];
    $query_run->execute();
    [...]
}

Naming

don't use short, non-expressive variable names. a, z, i (as non-loop variable), b, etc are not telling a reader much.
use either camelCase or snake_case, but don't mix them.
write out words. what's an org or a des? what is a destin? why is ident an originAirport?
What's a num? (ok, a number, but what kind of number? Seems to be a counter, so counter would be more fitting. But what does it count?
int is also not a very good name. It seems to be a random index? Then randomIndex would be better.

Misc

variables which are only used in one place, and whos name doesn't really add anything can be removed. Eg $count = count($b); is not needed, just use this directly: $int = rand(0, count($b));
if you split your code up into methods, it will be easier to read. You might have methods such as getOriginAirport, meassureDistancesFrom, getFlightId, getRunwayInfo, etc.


Get the best rational approximations for any real number in builtin Python

PEP-8 Guidelines

Follow the PEP-8 Style Guidelines, such as:

1 space around operators (1 / x instead of 1/x)
snake_case for identifiers & functions (cont_frac instead of contFrac)

Import As

The preferred method of creating an alias for an import is:

from decimal import Decimal as D

Since you are only using the floor function from math, you could also:

from math import floor

Docstrings

"""Docstrings""" exist to help a user with the usage of a function.  There are usually in triple quotes, because they should be multi-line strings, with enough information to be useful to the caller, without needing the caller to read the source code.

def continue_fraction(x, k):
    """
    Construct a continued fraction from a real value

    Parameters:
        x (float): Real value to determine continued fraction of
        k (int): A loop limit representing accuracy somehow

    Returns:
        List[Int]: List of continued fraction values
    """

A """docstring""" is the first statement of a module, class, function or method, if it is a string.  In particular,

    """Best Rational Approx Init"""

is not a """docstring""", because it is not the first statement.  It should be a comment.

    # Best Rational Approx Init

Comments are used to document the source code, for someone reading the source code.  In contrast, """Docstrings""" are used to provide help to the user of the item, so they do not have to read the source code.  It is displayed using the help() command:

>>> help(continue_fraction)

Don't use docstrings as comments, or vise-versa.

Superfluous Parenthesis

        ran = (hn0 + (i*hn1))
        rad = (kn0 + (i*kn1))

should be written as

        ran = hn0 + i * hn1
        rad = kn0 + i * kn1

Named Tuple

Consider using a named tuple, instead of using dictionaries for fixed content items.

from collections import namedtuple

fraction = namedtuple("fraction", "ratio, denom")

...

        ...
        ralist.append(fraction(f'{ran}/{rad}', rad))
        ...

    for x in sorted(conlist + ralist, key=lambda i: i.denom):
        finallist.append(x.ratio)

Collection

Why are you maintaining ralist separate from conlist, when you later add the two lists together and sort them??  Why not just maintain a single list?

List Comprehension

List appending is inefficient:

    finallist = []
    for x in sorted(conlist + ralist, key=lambda i: i.denom):
        finallist.append(x.ratio)

due to repeated reallocations of the list as the list size grows.  It is better to construct and initialize the list in one operation:

    finallist = [ x.ration for x in sorted(conlist + ralist, key=lambda i: i.denom) ]

Useless

This operation:

return list(dict.fromkeys(finallist))

takes a list, turns it into a dictionary with each list item as a key (all the dictionary values are None), and then constructs a list from just the dictionary's keys.  Uhm.   As long as the dictionary is kept in insertion order, which it is because you are using f'' strings so must be using Python 3.6 or later, this is indistinguishable from:

return finallist

Apparently the goal here was to remove duplicates.  A comment would have helped; it is not obvious.

Meaningful Function and Variable Names

What is contFrac and bestra?  It would be way clearer to use continued_fraction and best_rational_approximation, especially if you are writing this for "anyone exploring the logic of infinite continued fractions".

conlist, ralist, clist, app, ran and rad are equally obscure.


As evidenced by the bug in Rev 1, the inconsistent naming between getRoot()/setRoot() and self.key is a trap that you've created for yourself.

Getters and setters would be better done using the @property decorator.  Follow the convention in the documentation:

class BinaryTree(object):
    def __init__(self, obj):
        self.obj = obj
        self.left_child = self.right_child = None

    @property
    def obj(self):
        """The datum stored in the node."""
        return self._obj

    @obj.setter
    def obj(self, value):
        self._obj = value

    def __str__(self):
        return str(self.obj)    # <-- Simpler than %s interpolation

    …

Your traversal algorithms should not have a print statement, as they would be useless for anything other than printing to sys.stdout.  Instead, they should yield each result.  The caller can then choose to print them or do whatever it pleases.

for obj in pre_order(root):
    print obj

A nice way to write simple unit tests and provide documentation at the same time is to use the doctest module.


Division without multiplication, addition or division

If you run

Random rand = new Random();
for (int i = 0; i < 100; i++) {
    int a = rand.nextInt();
    int b = rand.nextInt();
    System.out.println(a + " / " + b + " == " + division(a, b) + " == " + a / b);
}

You'll see very clearly that the code is buggy. Investigate this yourself, and then come back to this post.

if (a == 1) { return  b; }

Is simply wrong.

if (a == 0 || b== 0) { return  0; }

should throw a java.lang.ArithmeticException: / by zero in the latter case. It should do so before checking a.

if (b > a)  { return 0; }

Covers the case of a == 0, as long as you ignore negatives - so remove the a == 0 check.

You don't even need these checks, though, so remove them.

You don't use

int size = size(a) - 1;

and it's also really bad style to have both an integer and a function of the same name anyway.

a = a - (b << i);
result = result + (1 << i);

should use -= and +=.

a - (b << i) >= 0

should be

a >= b << i

One then has

public static int division(int a, int b) {
    if (b == 0) {
        throw new java.lang.ArithmeticException("/ by zero");
    }

    int result = 0;
    for (int i = size(a) - size(b); i >= 0; i--) {
        if (a >= b << i) {
            a -= b << i;
            result += 1 << i;
        }
    }

    return result;
}

One should deal with negative numbers. This looks as simple as

boolean negate = false;
if (a < 0) {
    a = -a;
    negate ^= true;
}
if (b < 0) {
    b = -b;
    negate ^= true;
}

...

if (negate) {
    return -result;
} else {
    return result;
}

However, this fails for INT_MIN since -INT_MIN == INT_MIN!

What to do? It seems like one could flip into the negatives instead, and flip all of the comparisons. I don't think this would work, though, since

a = INT_MIN
b = INT_MIN + 1

would result in i = 1, resulting in running b << 1, which overflows. This doesn't just happen with INT_MIN either.

The simplest thing, then, might be to flip to positive after casting to long. One can also simplify things by removing size, then, in favour of some fiddling with b like:

int i = 1;
while (b < a) {
    b <<= 1;
    i <<= 1;
}

long result = 0;
for (; i > 0; i >>= 1, b >>= 1) {
    if (a >= b) {
        a -= b;
        result += i;
    }
}

All in all, one gets the unfortunately long

public static int division(int left, int right) {
    // Prevent overflow on negation
    long a = left;
    long b = right;

    if (b == 0) {
        throw new java.lang.ArithmeticException("/ by zero");
    }

    // Normalize to positive longs.
    boolean negate = false;
    if (a < 0) {
        a = -a;
        negate ^= true;
    }
    if (b < 0) {
        b = -b;
        negate ^= true;
    }

    int i = 1;
    while (b < a) {
        b <<= 1;
        i <<= 1;
    }

    long result = 0;
    for (; i > 0; i >>= 1, b >>= 1) {
        if (a >= b) {
            a -= b;
            result += i;
        }
    }

    if (negate) {
        // Should not overflow
        return (int)-result;
    } else {
        // Truncation might overflow if
        // result is -(long)Integer.MIN_VALUE,
        // but this is correct
        return (int)result;
    }
}


The use-case you came up with looks like a very clear candidate to be a GenServer.

A GenServer implementation will eliminate your need to manage the serving process, and using its client-side API conventions will also simplify the client usage.

Here is a sample implementation of a fizzbuzz:

defmodule FizzBuzz do
    use GenServer

    @fizz_buzz 15
    @fizz 3
    @buzz 5

    def start_link(default) do
      GenServer.start_link(__MODULE__, default, name: __MODULE__)
    end

    # Client API

    def getFB(n) do
        GenServer.call(__MODULE__, {:fb, n})
    end

    # Server API

    def handle_call({:fb, n}, _from, state) when rem(n, @fizz_buzz) == 0 do
        {:reply, "FizzBuzz", state}
    end

    def handle_call({:fb, n}, _from, state) when rem(n, @fizz) == 0 do
        {:reply, "Fizz", state}
    end

    def handle_call({:fb, n}, _from, state) when rem(n, @buzz) == 0 do
        {:reply, "Buzz", state}
    end

    def handle_call({:fb, n}, _from, state) do
        {:reply, "#{n}", state}
    end

end

Its usage would be:

FizzBuzz.start_link([])

IO.puts FizzBuzz.getFB(15)
# FizzBuzz


Get a stock quote from a web page using F#

I have been doing my own research and here is my answer to point 3.

  An alternative way to download the price that doesn't use a web browser control

namespace ExcelVIGSCA

module getPrice =

    open ExcelDna.Integration
    open FSharp.Data

    let saveVIGSCAjson () =
        // Get a copy of the data shape, and save it in a file so that the compiler can type check it.
        // I used http://www.telerik.com/fiddler to find the correct data.
        let url = @"https://www.vanguard.co.uk/uk/portal/GetMFJsonForPortId.js?portId=9158"
        let response = Http.RequestString(url)
        let json = (response.Split('=')).[1]
        System.IO.File.WriteAllText(__SOURCE_DIRECTORY__ + "\VIGSCA.json",json) |> ignore

    // Clearly, VIGSCA.json has to exist at compile time, so saveVIGSCAjson() will have to be have been run during development.
    // This makes the program very fagile.
    type VIGSCAData = JsonProvider<"VIGSCA.json">

    // information about attributes & data types: http://exceldna.codeplex.com/wikipage?title=Reference&referringTitle=Documentation
    [<ExcelFunction(Description = "Price for VIGSCA")>]
    // Excel-DNA needs concrete types for input and output to work: it can't be generic.
    let VIGSCAprice () =
        saveVIGSCAjson() // save the current data.
        let VIGSCA = VIGSCAData.GetSample()
        // The compiler will use the file it has at **compile time** to build up the type data.  This WILL lead to a runtime
        // exception if the type has changed.
        VIGSCA.FundData.Fund.[0].NavPrice.Price.[0].Price

After some research, including this illuminating article, I realised just how complicated web scraping is.  Extracting some data from a static HTML page would have been easy.  But we are dealing with a dynamic web page built on ssl/https connection.

I know that this code is incredibly brittle.  I certainly wouldn't want to give it to anyone else to use.  Consider it a learning exercise, or a hint at what can be done.  To get the web page at all, you have to have previously been to Vanguard's web site and selected the "Individual Investor" option, which presumably saves a cookie to that effect.

My research suggests that there are 2 broad categories of getting data from a dynamic web page.

Use a web browser programmatically (as in the question) and then make sure that the whole page, or at least the bit you are interested in, has downloaded before you extract the data.  The use of a regular expressions seems OK for this.  This is "simple" in the sense that you know what the final page looks like so you know what data to extract.
Use a protocol analyser (like fiddler) and inspect the web page source to work out exactly what request has the data you want.  Then use a tool, like the wonderful FSharp.Data to extract it.  This is definitely more work but you have a better understanding of how the web site is structured so that, hopefully, it is easier to maintain.  It is definitely more focused.

Whatever approach is chosen, knowledge of how these dynamic pages are built (including some familiarity with javascript) is necessary.  Thank goodness for sites like w3schools