How and where to define a partial helper module

Your current solution is fine, in my opinion. The underscore naming-convention used on view-partials doesn't apply for modules, that's why you got the uninitialized constant-error. If you name it ApplicationHelper::ApplicationContainer it has to be in a file named application_container.rb

What you have in your code now is a module you can include in other Helper-modules– just as you would a partial in your views.


File.open('data.txt', 'r') do |f| ... end

Good job. This is indeed the preferred way to read a file in Ruby. You get to read the file as a stream, and the file gets closed automatically. One thing to note is that the r flag is the default and can be left out. It is fine to leave it there for clarity, however.

Don't forget to set the correct encoding. If the real encoding is compatible with low-ASCII, you can assume ASCII-8BIT but it will treat characters in multibyte encodings as multiple characters. See later, however. You can set a default one, or you can do it while opening the file with :external_encoding => ....

If you strive for simplicity rather than speed (or if the file is small enough to be read all at once), you can also load the file into memory at once, then iterate over it:

f = IO.read('data.txt')

line_number = 0
while line = f.gets
    line_number = line_number + 1
    ...
end

Apart from the fact that assignment within conditional is frowned upon in many languages because it can be confused with accidental assignment instead of comparison,

File inherits several iterators from IO (don't forget to check for inherited methods - from superclasses AND modules) when looking up documentation). One of them IO#each_line, formerly IO#lines. For the line number, you can use IO#lineno. You can also use f.each_line.with_index{|line, index|...}, but that is zero-based.

line.each_byte do |c|
    if c & 0xff80 != 0
        puts 'A non-ascii character is found at line ' + line_number.to_s
        break
    end
end

I think you're looking for String#each_codepoint instead of String#each_byte. A UTF-16 non-ASCII character could well be composed of two ASCII bytes. UTF-8 non-ASCII characters are readily composed of multiple bytes, so you'd be getting multiple reports per character. If you assume a single-byte encoding, both will do (and each_byte is more explicit), but ...

If your intention is to test single-byte encodings, then the mask 0x80 will suffice. If your intention is to support any encoding of the Unicode character set, then the mask 0xff80 will not suffice as Unicode code points are 20 bits long. Some rare characters actually lie in the U+10000 .. U+1007F region. Perhaps the surest test is to use > 0x7F

Better yet, realise you are working with strings, and use string methods to manipulate them.

Even if you use each_byte, you still have to specify the external encoding. If the external encoding is set to UTF-8 but the source file isn't, you'll get an exception. That being said, you could set a 7-bit encoding (US-ASCII) and rely on the exception being thrown, but that won't get you the line number the character occurs on.

While string concatenation is the way to go in languages that lack string interpolation, string interpolation is the preferred way in Ruby. The nice thing is that it performs automatic string conversion where concatenation requires you to convert manually. Just don't use huge blocks or nested interpolation inside unless you care for character count rather than readability. Compute the part first, then interpolate it in.

One last thing to note is that you are not very consistent in the use of one-letter / descriptive variable names. Descriptive names never hurt, and single-letter variables should only be used if their scope is small enough (or if the single letter is descriptive per se).

This is how I would modify your code:

File.open('data.txt') do |file|
    file.each_line.with_index do |line, index|
        if /[^\x00-\x7F]/ =~ line
            puts "A non-ascii character is found at line #{index + 1}"
            break
        end
    end
end

If you are not afraid of perlisms,

File.open('data.txt') do |f|
    while f.gets
        if /[^\x00-\x7F]/
            puts "A non-ascii character is found at line #{$.}"
            break
        end
    end
end


Initializing and printing an array using pointers and dynamic allocation in C

There are a number of things I would change here, so I'm going to go through the process incrementally, applying changes to the whole file in passes rather than in chunks. I think this should make it more clear why the changes are implemented.

C99 Note

You should have access to, at the very least, a C99 compiler. If that's not true, you can ignore this first point, but if it is, you should change your counter declarations to be inside the first for clause.

for (int i=0;i<n;i++)

Pointers

In initArr, you both return the int array and assign it to the provided out parameter, arr. Why? Out parameters make code confusing and hard to follow! They make sense if you're performing the array allocation somewhere else, but since you're performing the array allocation inside initArr, just drop the arr parameter and return the value.

As a side effect of this, since you no longer need a double pointer, you can replace your dereferences with simple array accesses.

int * initArr (int n)
{
    int * arr = (int *) malloc(sizeof(int*)*n);
    printf("size is %d\n", sizeof(arr));
    for (int i=0;i<n;i++)
    {
        arr[i]=i+10;
    }
    return arr;
}

Next, why are you passing a double pointer (int**) to printArr? More importantly, why does printArr have a return value if it's a purely side-effectful function? Change the parameter to int* and make the function return void.

void printArr (int * arr, int n)
{
    for (int i=0;i<n;i++)
    {
        printf("Arr element %d is %d\n", i, arr[i]);
    }
}

This also simplifies the main function.

int main(void) {
    int * arr2 = initArr(10);
    printArr(arr2,10);

    return 0;
}

Next, let's take a look at the allocation itself (the one in initArr). First of all, you cast to (int *) manually, which is unnecessary and downright discouraged in C. If you're using C++, it's necessary (though you shouldn't need malloc in C++, anyway), but with a C compiler, just drop it.

Second of all, you are not actually allocating the right data! You're allocating n slots for int* values—int pointers. You actually want int data. This might not matter depending on your architecture and compiler, but it's still poor code. Fortunately, you can actually fool-proof this—don't pass an explicit type of sizeof at all! Just deference arr itself, and the compiler will calculate that value's size.

Those changes simplify the allocation to this:

int * arr = malloc(sizeof(*arr)*n);

Finally, the line just after that—the printf line—is useless. It will always print the same value because it's checking the size of a pointer, which is always the same size regardless of type (though it can change on different architectures). That said, the line doesn't make any sense there. A function called initArr shouldn't have side effects, anyway. Just take it out.

Style and Warnings

I'm not sure if you just omitted it from your code, but your code depends on functions declared in external header files in the standard library. Include these at the top of your file.

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

Next, let's talk about code style. You are writing some very densely-packed expressions in some places. Some whitespace can make code much more readable! For example, change the for loops to this:

for (int i = 0; i < n; i++)

Similarly, change your allocation to this:

int * arr = malloc(sizeof(*arr) * n);

Proper spacing makes code more readable and therefore more maintainable!

Finally, let's talk about pointer declarations. You are declaring your pointers with the asterisks just sort of "floating". This is actually not a bad compromise. Some people prefer them to be grouped with the type (int* foo), others with the name (int *foo). I prefer the former style, so in my final copy of the code, I changed them accordingly, but this is often merely personal preference.

Result

Here is all the code as it stands with the above changes implemented! Not only is it more readable due to style, but it's easier to understand the control flow since it no longer unnecessarily indirects variables via reference.

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

int* initArr(int n)
{
    int* arr = malloc(sizeof(*arr) * n);
    for (int i = 0; i < n; i++) {
        arr[i] = i + 10;
    }
    return arr;
}

void printArr(int* arr, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("Arr element %d is %d\n", i, arr[i]);
    }
}

int main(void) {
    int* arr2 = initArr(10);
    printArr(arr2, 10);

    return 0;
}

Extra Notes

  Can I use arr[i] anywhere in the functions instead of **arr? (Gave error when I tried it)

You can! But * has lower precedence than array subscript ([]), so you'd need to use grouping operators

(*arr)[i]

This became unnecessary with the other changes, though.

  What is the most common way of dealing with arrays when writing professional code? Is my approach correct?

Depends on the situation. Honestly, the best away to handle arrays is to not use them—if you're using a language with any more power than C, you should have higher-level language constructs (std::vector, ArrayList, etc.). However, if you have to use C, abstracting them behind an API is a good start.

  One issue I'm encountering is having no way to tell printArr() what the size of the array is.

Yes, in C, arrays are just blocks of memory, so you can't get their length at runtime because it's not stored anywhere! If you wanted to do this, though, you could encapsulate your array in a struct.

typedef struct my_array {
    unsigned int length;
    int* data;
} my_array_t;

You could then return a my_array_t from initArr and pass a my_array_t to printArr, which could use arr.length to get the length.


How to verify if HTML table sort is stable or not?

From a once over;

The easiest way to be sure that you sort algorithm is stable, is to write you own sort algorithm.
The second easiest way to be sure is to pass in each array entry object it's position in the array ( you could set this after your arr[i][j] assignment ). If (a[c]==b[c]) then you would not return 0, but you would return -1 or +1 based on their original position in the array
You did not declare c and asc with var
var arr = []; is preferred to var arr = new Array();
One single comma separated var statement is preferred over many var statements
You declare var i twice, since var i declares i for the scope of the function, you do not need to declare it again.
Your indenting is off, you should look into that
Assigning a function to document.ready is old skool, you should look into using addEventListener or simple using $( handler );.
You should cache the value of a<$("tbody tr:eq(0) td").length

 for (var a = 0, count = $("tbody tr:eq(0) td").length; a < count ; a++)

On my second point, imagine you are sorting people by their age, in a stable manner:

Bob, 23 years
John, 12 years
Tricia, 23 years

becomes

Bob, 23 years
Tricia, 23 years
John, 12 years

it would be unstable if the order was

Tricia, 23 years
Bob, 23 years
John, 12 years

because Tricia was initially below Bob, she should stay below Bob.
You can accomplish this by comparing the original position of the 2 records and making sure that if the age is the same, you make sure the original order is respected.

I hope this example made it clearer.


This is a pretty good implementation of what you've set out to do. The naming of things is clear and the code is pretty well split up into methods.

Main Class

I'd maybe put a slightly clearer explanation of what the user is expected to do at the start, as well as your "enter an upper limit". This is usually an excuse to break out your finest ascii art.

Something else to consider is what if your user doesn't enter an integer? That will break your program, so putting in some error handling that asks your error-prone meatbag to try again and get it right this time, please. Your way of checking is to put the scan.nextInt() in a try/catch block and catch an InputMismatchException.

When you're asking the player if they want to play again, you set running to true, but there's no way for it not to be true, so that's unnecessary.

Game class

You're seeding rand every time you're calling generateRandomNumber(), which isn't really going to be an issue here, as you're not calling that method quickly/often, but you should really only seed a random number generator once in a program, otherwise you'll start having it return the same value over and over again, so maybe move your Random rand = new Random() to the constructor?

In guess(), I'd rearrange the first section to this:

 if (guess == randomNumber) {
        if (tries > 1) {
            System.out.println("You got the number in " + tries + " tries.");
        } else {
            System.out.println("You got the number in " + tries + " try.");
        }
        return true;
 }

You're repeating yourself less and the return value is the same regardless. The same goes for the next part, instead, I'd have:

 else if (guess > randomNumber) {
        System.out.println("Too high try again");
    } else if (guess < randomNumber) {
        System.out.println("Too low try again ");
    }
    return false;


I don't like either implementation, but since you asked, the first one is the least bad since it makes better use of case classes. And that brings me to my first point,

You need to make use of case classes (better)

And it all starts with the first thing you did in your code. Because you did this:

sealed trait Node {
   val label: Int
}

You just automatically eliminated the ability to create empty trees due to the fact that every tree now has to contain an item. This puts you in a bad position because as you have noticed, you now have no choice but to resort to Options. Don't get me wrong, Option monads are great but when used in such a manner it does them no justice.

Anyways, I suggest removing the val label: Int and just having an empty sealed trait.

sealed trait Node {}

Then you can also remove the override from your other classes:

case class LeafNode(label: Int) extends Node
case class BranchNode(label: Int, left: Option[Node], right: Option[Node]) extends Node

Still looks pretty bad, but we can fix that.

Case Objects are still a thing

From the above use of Option, it would seem that you are trying to say that a BranchNode can sometimes contain a node and other times, contain nothing. In that case, let's create a better representation of "Nothing" by making use of case objects:

case object EmptyNode extends Node

Aha! you say

Mhm I reply

Since we now have a case object to represent the Empty state of a tree, let's reconstruct our tree now

case object EmptyNode extends Node
case class LeafNode(label: Int) extends Node
case class BranchNode(label: Int, left: Node, right: Node) extends Node

And there you go, a perfect recipe for great pattern matching.

With this in order, we can now reconstruct the traversal method. Note you have two options with this, either create an implicit class which implements the traversal method and allows you to do tree.inorderTraversal or create a method which takes the tree as you have already done. For this demonstration, I will opt for the implicit class option:

implicit class InorderTraversable(val aTree: Node) extends AnyVal {
    def inorderTraversal: List[Int] = aTree match {
        case EmptyNode => List()
        case LeafNode(item) => List(item)
        case BranchNode(item, left, right) => (left.inorderTraversal :+ item) ++ right.inorderTraversal
    }
}

Other statements

Avoid nesting functions if you can
Try to throw less exceptions
Use pattern matching to your full advantage. Read more here

Putting it all together:

package com.codereview

sealed trait Node {}
case object EmptyNode extends Node
case class LeafNode(label: Int) extends Node
case class BranchNode(label: Int, left: Node, right: Node) extends Node

object Main extends App {
    implicit class InorderTraversable(val aTree: Node) extends AnyVal {
        def inorderTraversal: List[Int] = aTree match {
            case EmptyNode => List()
            case LeafNode(item) => List(item)
            case BranchNode(item, left, right) => (left.inorderTraversal :+ item) ++ right.inorderTraversal
        }
    }

    val tree =
    BranchNode(1,
        BranchNode(2,
            BranchNode(3,
                BranchNode(4, LeafNode(6), LeafNode(5)),
                BranchNode(7, LeafNode(8), EmptyNode)),LeafNode(9)), LeafNode(10))

    println(tree.inorderTraversal)
}


First of all, it's great that you use type signatures. However, your using snake_case, whereas Haskell usually uses camelCase for functions, e.g. no_shift should be called noShift.

Next, your shift functions for characters can be simplified by both pattern matching and succ and pred:

shiftForwards :: Char -> Char
shiftForwards 'z' = 'a'
shiftForwards c   = succ c

shiftBackwards :: Char -> Char
shiftBackwards 'a' = 'z'
shiftBackwards c   = pred c

Next, your "global" function gets easier if you use str as an argument and not in a lambda.

shiftStr :: Int -> [Char] -> [Char]
shiftStr num str
       | num > 0  = shiftStr (num - 1) (map shiftForwards str)
       | num < 0  = shiftStr (num + 1) (map shiftBackwards str)
       | num == 0 = str

The special cases for num == 1 and num == -1 aren't necessary, since shiftStr will return immediately if the subsequent call uses num = 0.


You're attempting to handle the data binding yourself by creating arrays to store objects based on the click event. Angular does the two way binding for you.

Basically, I assign a new property named "included" by assigning it as the model to the input checkbox. Then I use that property on the filter of the fruit array to display only the one's whose colour is selected.

            <input type='checkbox' ng-model='f.included'></input>{{f.colour}}

{{f.name}}

angular.module('fruit', []);

function FruitCtrl($scope) {
    $scope.fruit = [
        {'name': 'Apple', 'colour': 'Red'},
        {'name': 'Orange', 'colour': 'Orange'},
        {'name': 'Banana', 'colour': 'Yellow'}
    ];
}


JavaScript: Better way to sort an array by setting custom index

Updating my comments on current implementation, Thanks @Mast for pointing out.

You have used let for output, targetIndex and title. None of
them never updated. const is better suitable here.
Usage of value.title.indexOf('_') is repeated. you can use variable.
You can avoid substring usage because you are already did value.title.split('_') and you can use index 1 value from result
    array.

Apart from these minor points, code looks good to me.

As you asked, Here is alternative ES6 implementation.

Use arrow function
With reduce and using destructure in input function arguments and have the default value for title.
In reduce function use destucture to get the values from split result.

const data = [{"title": "100_baz"}, {"title": "01_foo"}, {"title": "05_bar"}];

const indexSort = data => data.reduce((acc, {title = ''}) => {
  const [num, value] = title.split('_');
  acc[Number(num)] = value;
  return acc;
}, []);

console.log(indexSort(data));


Open a text file and remove any blank lines

I see two good strategies to accomplish the task.

One solution is to read all of the text into a list, then rewind to the start of the file and write out the desired lines.

def remove_empty_lines(filename):
    """Overwrite the file, removing empty lines and lines that contain only whitespace."""
    with open(filename, 'r+') as f:
        lines = f.readlines()
        f.seek(0)
        f.writelines(line for line in lines if line.strip())
        f.truncate()

The disadvantage of that approach is that it scales poorly if the file is huge, because the entire contents have to be read into memory first.  The other approach would be to overwrite the file while reading from it.  This uses two file objects, each keeping track of its own position within the file.

def remove_empty_lines(filename):
    """Overwrite the file, removing empty lines and lines that contain only whitespace."""
    with open(filename) as in_file, open(filename, 'r+') as out_file:
        out_file.writelines(line for line in in_file if line.strip())
        out_file.truncate()

Note some other issues with your code.

First, PEP 8, the official Python style guide, recommends lower_case_with_underscore for function names, and two blank lines between functions.

The fileExists function does not just test for the existence of the file — it actually checks whether you can open it for reading, which is a more stringent condition, since it also involves file permissions.  But I don't see any reason to check specifically for file existence.  All kinds of I/O errors are possible, such as filesystem permission denial, read-only filesystem, disk quota, or hardware failure.  Furthermore, even if the file exists when you check, it could disappear during the split second between if not fileExists(…) and the real open(…) call.  On top of that, your rmoveEmptyLines function has no way of reporting failure to its caller.  (Printing an error message doesn't count!)  Therefore, the only reasonable approach is to Just Do It, and handle any exception that might occur.

Any open() call should be written using a with block, which will automatically close the file handle when exiting the block.


Toggling checkboxes based on certain conditions

I may have misunderstood something but if you just want to be able to detect case where the input string is none of expected, you may do something like that:

default:
  console.log("This operation '"+operation+"' is not supported, it will be ignored");

at the end of your switch\case construction


It's not bad, though there are some things I'd do different.

Firstly, I'd use a map of arrays for receivers. Doesn't have to be a Map instance, a simple object literal will do. For instance, subscribe would look like this:

var receivers = {};

var subscribe = (name, callback) => {
  if(typeof callback === 'function') {
    receivers[name] = (receivers[name] || []);
    receivers[name].push(callback);
  } else {
    throw new TypeError("callback must be a function");
  }
}

This makes it simple to dispatch events:

var dispatch = (name, data) => {
  receivers[name].forEach(receiver => receiver({name: name, data: data}));
}

Secondly, I wouldn't use rely on a gid value to track receivers; I'd use the receiver itself. It eliminates needing to track multiple IDs if one function is subscribing to multiple events, and it makes the sub/unsub functions "symmetrical": All you need is an event name and a function.

function someHandler() { ... }

eva.subscribe('someEvent', someHandler);
eva.unsubscribe('someEvent', someHandler);

To achieve this, unsubscribe could look like:

var unsubscribe = (name, callback) => {
  if(receivers[name]) {
    receivers[name] = receivers[name].filter((receiver) => receiver !== callback);
  }
}

Also, one important note: Your list function returns a reference to the receivers array. I don't know if this is intended, but it does mean, that you'd be modify the otherwise-"private" array. For instance, saying eva.list().push("foobar") will cause problems, because it sidesteps all you type-checking, and adds something to the array that your code isn't expecting.

Frankly, I don't know how useful the list function is to begin with, but in your current code, you could halfway fix the issue by simply calling slice() on the receivers array. That'll create a copy, and return that instead:

var list = () => receivers.slice();

However, the contents of the copied array will be references to the same objects that are in "private" receivers array, so you cause mischief:

eva.list()[0].action = "foobar"; // obviously not a proper callback

You could spend the time doing a deep clone of everything, but... eh.

Again, simpler to let the array only contain functions. Even if they're returned as references in a copied array, it's harder to accidentally break things.

If you use an object/map to hold the receivers as I suggest above, you do have to do some more complex cloning to return it safely (although the arrays it contains can be copied safely with slice). However, I'd just scope everything in the API to a name, including list and clear:

var list = (name) => receivers[name] ? receivers[name].slice() : [];

var clear = (name) => receivers[name] = [];

If you want to could add a method to return all registered event names by using Object.keys(receivers).

You'll note that I haven't bothered much with type-checking. Only when subscribing do I check that the callback is actually a function. But name arguments? Don't really care.

Type-checking isn't super necessary in JS. Often it really doesn't matter due to type coercion, or you explicitly cast/parse if you need to. Other times it's just simpler to say "garbage in, garbage out": If someone really wants to use a float as an event name, let them. And let them sort it out, if things don't work. This is what I usually lean toward. Since JS isn't strictly typed (and sometimes plain weird), the effort spent implementing your own type-checking could be spent better elsewhere.

All together, minus comments:

var eva = (() => {
  var receivers = {};

  var subscribe = (name, callback) => {
    if(typeof callback === 'function') {
      receivers[name] = (receivers[name] || []);
      receivers[name].push(callback);
    } else {
      throw new TypeError("callback must be a function");
    }
  }

  var unsubscribe = (name, callback) => {
    if(receivers[name]) {
      receivers[name] = receivers[name].filter((receiver) => receiver !== callback);
    }
  }

  var dispatch = (name, data) => {
    receivers[name].forEach(receiver => receiver({name: name, data: data}));
  }

  var list = (name) => receivers[name] ? receivers[name].slice() : [];

  var clear = (name) => receivers[name] = [];

  return {
    subscribe: subscribe,
    unsubscribe: unsubscribe,
    dispatch: dispatch,
    list: list,
    clear: clear
  };
}());


Note: I don't claim to be an expert in SOLID principles, I do understand abstraction a bit though.

Back to SOLID, CalculateArea violates the Open/Closed principle (The most frustrating concept to me). That is, when you add a shape  you have to go and modify the code by adding an if-statement, this can easily solved by using interfaces,

 interface IShape{
    double CalculateArea();
 }

 class Rectangle : IShape{
    double CalculateArea(){
       return Width * Height;
    }
 }

And so on for different shapes, so there is no need for if-statements. Btw: how come you representing a circle in a class called Box??

Single responsibility principle is being violated as well, where your class represents a Box Object and persists it to a database, these are two different responsibilities. You should rather have Data Access Layer to deal with a very HIGH dependency like a database.

In regards to SQL generation you can abstract those as well using interfaces, and that is, given a shape get its sql code.

  interface ISQLShapeTemplates{
      DbCommand InsertionCode(IShape shape);
      DbCommand SelectCommand(IShape shape);
  }

I used DbCommand and not SqlCommand because it's more abstract .


Simple concurrency implemented in Python

async def count_words_for_file(file):
    with open(file) as f:
        return sum(len(line.split()) for line in f)

Just making this function async won't bring you any benefit. asyncio can improve performance only if you're running multiple operations that can be parallelized. Usual case is when you're running multiple downloads: asyncio will do some job instead of idle waiting answer from network and through that bring you benefit.

In your case almost everything faces CPU (splitting lines) and disk I/O (reading files). For can be parallelized throught processes only (due to GIL), for second you can use threads (since GIL doesn't affect disk I/O). In both cases you can use asyncio to rule the process with run_in_executor.

Read this link for general explanation and few examples.


Collision Detection in a 2D shooter game

You are creating a new Player and Tile every time this code executes. That is likely your performance hit. Try moving the existing player rather than creating a new one in a new location.

Does performance slow down further the longer the game runs? This is because your objects are piling up.

For further reading I recommend looking at AABB Collision Detection and Quad Trees.


Yay exceptions!

Though it isn't reservered for execution-ending errors, I would avoid throwing an OutOfMemoryException, because usually it signals something very inconvient indeed. IndexOutOfRangeException also seems inappropriate: I would probably use InvalidOperationException in both Enqueue and Dequeue.

The constructor could do with a check to ensure maxSize is positive, so that it doesn't throw with a cryptic error.

Front and End don't throw on an empty buffer, and probably should.

API and Encapsulation

There is no reason this class couldn't be generic: I would make it so. Indeed, because it stores ints at the moment, it would not be clear to a consumer looking at the members that Front and Rear return elements rather than indexes.

I'd expect a Count => _size property, so that the Queue can be used for the sort of things Queues tend to be used (e.g. in your previous questions).

Do you have a particular use-case in mind for exposing _buffer? What good can come of this? There is no information made available as to the content of the buffer, so it can't be used for anything because nothing except the CyclicQueue knows how to use it. I would strongly suggest making this private (also, if it is public, it should ideally following the ProperCamelCase naming conventions like your other public members).

Since this is a non-resizing queue, the MaxSize probably ought to be public information. I'd also consider making it MaxSize => _buffer.Length to reduce redundancy. You could also make _buffer readonly to signal it's not meant to be changed to the maintainers.

Correctness

I'm not sure the _size > 0 check in Enqueue works. Consider a sequence of Enqueue, (Dequeue, Enqueue)*n on a newly created CyclicQueue: this will leave _end = 0 while _start is incremented. I think this can be resolved by setting _end = _maxSize - 1 in the constructor and removing the check.

Misc/Boring Stuff

You could do with a little more white-space between things... at the very least, be consistent with your between-member spacing.
You could do with tests which test the exceptions (i.e. checking it throws if you try to enqueue/dequeue too many things.
As always, inline-documentation would be appreciated. This should describe the non-resizing nature of the queue, when it throws exceptions, and resolve the confusion concerning whether Front is an index or element.


I think you need to ignore the contents of quoted values.

Add the flag:

    boolean inQuotes=false;

then, at the top of your if statement:

        if (c == '"') {
            inQuotes=!inQuotes;
        }
        if (!inQuotes) {
            if (c == '{') {
                sb.append(c);
                sb.append(System.lineSeparator());
                tabCount++;
                printTabs(sb, tabCount);
            } else if(c == '}') {
                ...  // Your code
        } else {
            sb.append(c);
        }


Change example.jpg to example-color.jpg on hover

On another approach, you could do spriting. One problem you'll encounter with that approach, where you change src is that the image will take some time to load before the hover image appears. That's annoying. With sprites, you have one image just positioned differently on a container. There's no loading that will happen on hover.

See this example. And the best part is... no JS!

HTML:

CSS:

/* Class for setting the image */
.image {
    background-image: url("http://www.alexmourer.com/wp-content/uploads/2013/09/css-sprite.png");
    display: block;
    width: 77px;
    height: 77px;
}

/* class for positioning to the right image (x and y) */
.image.twitter{
   background-position: 0 0;
}

.image.facebook{
   background-position: 308px 0;
}

/* class to offset the image on hover, in this case, up */
.image:hover{
    background-position-y: -154px;
}


Asynchronously fetching data from the database

Your async/await usage doesn't look fine because the chain it's incomplete. FindList should be async and named FindListAsync and it should await the result from QueryAsync.

There are also a few other things that botter me:

since BaseQueryDataStoreAsync is an abstract class then QueryAsync should probably be protected and not public - otherwise someone can use it for any query
the CategoryQueryService should be injected
the GetHandler doesn't look very useful
making the dbConnectionString a const is a terrible idea - you could/should use appSettings.json to store it and IConfiguration or IOptions to get it
setting QueryAsync's default parameters to null where they are null anyway (source) is pretty pointless - instead just use the overload with a single parameter.


Inserting new Node in a Binary Search Tree

A BST must not contain duplicate values.
Your implementation allows inserting a duplicate value as the right child.
It should be something like this:

if (newNode.getNodeData() < currentParent.getNodeData()) {
    if (currentParent.getLeftChild() == null) {
        currentParent.setLeftChild(newNode);
    } else {
        insertNode(currentParent.getLeftChild(), newNode);
    }
} else if (newNode.getNodeData() > currentParent.getNodeData()) {
    if (currentParent.getRightChild() == null) {
        currentParent.setRightChild(newNode);
    } else {
        insertNode(currentParent.getRightChild(), newNode);
    }
} else {
    // duplicate item
    // option 1: do nothing: ignore input, add nothing to the tree
    // option 2: throw new IllegalArgumentException("no no: dupe")
}

It's also recommended to use braces always,
so I modified the original code accordingly.


I think your script would benefit from some object oriented composition. Basically you have three different concerns.

Config
File backup (select from database and storage in CSV)
File upload

A few things could change now, for instance backup from a different source (different database, cloud etc), upload to a different remote service (e.g. dropbox). Additionally, having small composable objects would make it easier to test this.
Here are some examples how to compose your script more object oriented.
Config
We could use an OpenStruct to store our config data. This way we only need to write our environment variables once, if we want to change them later there is only one place to update them.
require 'ostruct'

config = OpenStruct.new(
  year: ARGV[0],
  month: ARGV[1],
  day: ARGV[2],
  box_user_id: ENV['BOX_USER_ID'],
  box_folder_id: ENV['BOX_FOLDER_ID']
)

FileBackup
We can extract a backup file which just excepts rows and writes them to a CSV file. The dependency injection makes it also easier to test this (e.g. inject the data to write and the test directory)
class BackupFile
  def initialize(rows:, date: DateTime.now.strftime("%m-%d-%Y").to_s, directory: "./tmp")
    @rows = rows
    @date = date
  end

  def save
    CSV.open(full_path, "wb") do |csv|
      rows.each do |entry|
        csv << [entry.values[0], entry.values[1]]
      end
    end
  end

  def full_path
    File.join(directory, filename)
  end

  def delete
    FileUtils.rm(full_path)
  end

  private

  attr_reader :rows, :date

  def file_name
    "access-emails-#{date}"
  end
end

db_client = MySQL.new(search_timestamp)
emails = db_client.get_emails_from_db
return 'No new emails found' if emails.entries.empty?

file = BackupFile.new(emails.entries)
file.save

Upload
The uploader accepts a client, path and remote folder. Also notice that we have an adapter around the BoxApi to implement a common interface upload. If we want to swap it out to upload to Dropbox, we only need to write a DropboxClient adapter which we can inject into the uploader. To test, we can write even a TestClient.
class Uploader
  def initialize(client:, path:, remote_folder:)
    @client = client
    @path = path
    @remote_folder = remote_folder
  end

  def upload
    client.upload(path, file_name, remote_folder)
  end

  private

  attr_reader :client, :path, :remote_folder

  def file_name
    File.basename(path)
  end
end

class BoxClient
  def initialize(client:, box_user_id:)
    @client = client.new(box_user_id)
  end

  def upload(path, file_name, remote_folder)
    client.upload_file_to_box(path, file_name, remote_folder)
  end

  private

  attr_reader :client
end

Error handling
I would move the error handling into the classes directly and also inject the logger. Something like this:
class BoxClient
  def initialize(client:, box_user_id:, logger: Logger.new)
    @client = client.new(box_user_id)
  end

  def upload(path, file_name, remote_folder)
    client.upload_file_to_box(path, file_name, remote_folder)
  rescue BoxError =>
    logger.error("Upload failed: #{e.message}")
  end

  private

  attr_reader :client
end


Counting the number of page turns to arrive at some specified page

Math.min(p / 2, n / 2 - p / 2)

Explanation:

If we go from start page \$1\$ takes \$0\$; page \$2,3\$ takes \$1\$; page \$4,5\$ takes \$2\$ and so on. So for \$2k,2k+1\$ we require \$k\$ turns. Hence \$p=2k,2k+1\implies \lfloor p/2\rfloor = k\$
If we go from the back  it depends on:

If \$n\$ is odd then \$n,n-1\$ take \$0\$; \$n-2,n-3\$ takes \$1\$ and so on. So \$n-2k,n-(2k+1)\$ takes \$k\$.

Let \$n=2q+1\$ then \$p=2q-2k+1,2q-2k\implies \lfloor p/2\rfloor = q-k\$

i.e. \$k=q-\lfloor p/2\rfloor=\lfloor n/2\rfloor -\lfloor p/2\rfloor \$
If \$n\$ is even then \$n\$ takes \$0\$; \$n-1,n-2\$ takes \$1\$ and so on. So \$n-(2k-1),n-2k\$ takes \$k\$.

Let \$n=2q\$ then \$p=2q-2k,2q-2k+1\implies \lfloor p/2\rfloor=q-k\$

i.e. \$k=q-\lfloor p/2\rfloor=\lfloor n/2\rfloor -\lfloor p/2\rfloor\$


My implementation of (open) Knight's Tour

final List<int[]> moves local to solve shadows private final int[][] moves member. While it may not affect the functionality, it surely makes code harder to understand.
I don't see how moves.isEmpty() could ever be satisfied.
Dealing with visited squares looks suspiciously redundant:

The all squares visited condition is directly derived from currentMove value: currentMove == total, so there is no need to scan the entire visited array.
Similarly, a square visited condition could be implicitly derived from the corresponding board[][] value. Initially, it is -1 for unvisited squares - and you may maintain this invariant by resetting the board[][] to -1 instead of setting visited[][] to false.

This means that you may eliminate visited[][] array.
An x > 0 condition in isLegitMove looks strange, as if the indexing starts with 1 (according to the rest of the program logics it starts with 0). I am not sure I understand why x == 0 makes the move illegitimate. Looks like a potential bug.


Don't Reinvent the Wheel

In your "STEP 1", you are manually setting each pixel of the background to black. This is expensive and unnecessary. You can simply draw a black rectangle the size of the canvas:

ctx.fillStyle = "rgb(0, 0, 0)";
ctx.fillRect(0, 0, Width, Height);

Next, in "STEP 2" why are you using your own line drawing routines? You could simply call the built-in routines, like:

ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();

And to draw circles, you can use the arc() method:

ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2.0 * Math.PI, false);
ctx.fillStyle = "rgb (1, 1, 1);"
ctx.fill();

This will likely be much faster than rolling your own.

Naming

I find your variable names hard to read and understand. Names like xCL, yCL and xMP, yMP are not very descriptive. Maybe centerX, centerY and midPointX and midPointY instead?

Also, iCL seems to be unused. It can be removed.

Abuse of Lambdas

Your entire drawing function (the main purpose of your program) is an anonymous function passed as an argument to another function. It's difficult to follow the flow of it all, and it's odd that the most important thing in your code is a single argument to a function that merely collects stats.

And then you mix in stats collection in the actual function that does the drawing. I'd separate it all out, like this:

function draw()
{
... all the drawing code...
}

function collectDrawStats()
{
    stats.begin();
    draw();
    stats.end();
}

setInterval(collectDrawStats(), 1000 / 60);

Avoid Magic Numbers

What is the 1000 / 60 in the call to setInterval()? Does that have something to do with the refresh rate being 60 fps? You should create a named constant that tells a reader what it means. Is it milliseconds per 60th of a second? If so, what's the significance of that?


I think the best way to refactor your problem is to use React programming pattern: a stateful, parent component passes down a prop to a stateless, child component. So, you don't ever need to declare mesas as a class, it is just a functional component because we dividing components into presentational components and container components.
But, I didn't get about the App's state, if you plan to use external storage fine, but if you need to manage the local state, just insert the mesas in your App under constructor. However, abstracting, based on your code, my  refactoring:
// App.js
import React from 'react';

const mesas = [{
      id: 1,
      valor: 500,
      produtos:['COCA COLA', 'FANTA']
    },{
      id: 2,
      valor: 100,
      produtos:['PRATO1', 'PRATO2']
    }]
const App = () => {
    return (<ListaMesas mesas = {mesas} />)
}

// Mesas.js
import React from 'react';

export const mesas = ({ mesas }) => {
    const mesasList = mesas.map((mesa) => {

            <text>{mesa.id}</text>

    })
    return (

            {mesasList}

    )
}


Efficient way to calculate the sum of all primes between a range

Nice implementation, it's already efficient but as noted in the comments can be improved. Few general suggestions:

Format the code: many IDE support auto formatting or you can use an online formatter.

Omitting brackets is not good practice: it's better to include the brackets to avoid confusion when reading or changing the code. See the difference from:
static boolean isPrime(int n){
      if(n==1)return false;
      for (int i=2; i*i<=n; i++)
          if (n%i==0) return false;
      return true;
}

To:
static boolean isPrime(int n) {
    if (n == 1) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Arrange the methods from general to specific, it's easier to follow. From:
static boolean isPrime(int n){
}

static int sum(int a, int b){
    //call isPrime
}

public static void main(String[] args)throws IOException{
    // call readint
    // call sum
}

static String next () throws IOException {
}

static int readInt () throws IOException {
    // call next
}

To:
public static void main(String[] args)throws IOException{
    // call readint
    // call sum
}

static int readInt () throws IOException {
    // call next
}

static String next () throws IOException {
}

static int sum(int a, int b){
    //call isPrime
}

static boolean isPrime(int n){
}

The methods readInt and next can be replaced with java.util.Scanner:
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();

Close the resources: br.close() (or scanner.close()) at the end of main or if exceptions occur.

PrintWriter pr is not used.

The method sum(int a, int b) does not sum two integers. A better name might be sumPrimesBetween

StringTokenizer is discouraged for new code, from the docs:

StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of String
or the java.util.regex package instead.

Performance
As mentioned in the comments, since you know the upper bound 10^5 you can precompute all the prime numbers in advance. The main logic can be:

Precompute all prime numbers until 10^5: you can use an array of boolean initialized to true and then set the corresponding index to false if not prime. For example:

static void computePrimesUntil(int n) {
    isPrime = new boolean[n+1];
    Arrays.fill(isPrime, true);
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i <= n; i++) {
        if (isPrime[i] && (long) i * i <= n) {
            for (int j = i * i; j <= n; j += i){
                isPrime[j] = false;
            }
        }
    }
}

Code inspired from here.

Parse all the questions from the user
Output the sum of primes for each question

Note: depending on how the total running time is calculated, you need to consider the time to parse the input and print the results. The total running time also depends on the machine where you run the program.


Is `if( hidden ) return;` an antipattern?

There's a semantic difference between the two of these. In the first, the draw method always draws the object whether the object is visible or not. I.e. it is the caller's responsibility to check the visibility of the object. In the second, the object checks it's own visibility and recognises that it does not need to do anything if the object is hidden.

The difference in the loop, then, is the difference between saying "Draw all of the non-hidden elements", and "Draw all of the elements, (where draw means draw the element if it is visible)"

One focuses on the fact that we're drawing visible elements, the other adds the concept of visbility to the method draw.

In my opinion, the second of these better fits the semantic of what draw is supposed to do, and for that reason it is clearly better to perform the visibility check inside draw rather than inside the loop.


Check if number is divisible by three and two

Instead of checking for division by 2 and 3 separately twice, you can make use of the fact that:
$$ 2 * 3 = 6$$
num = int(input("enter number"))
if num % 6 == 0:
    print("Divisible by 3 and 2")
elif num % 3 == 0:
    print("divisible by 3 not divisible by 2")
elif num % 2 == 0:
    print("divisible by 2 not divisible by 3")
else:
    print("not Divisible by 2 not divisible by 3")

python pep8 suggests to use 4-whitespace nesting as indentation levels.

Use 4 spaces per indentation level.

If you have more numbers to check divisibility against, keep a set of the numbers for which num % x == 0, and print the factors at the end.


Check if any of class properties is not null/empty/was assigned

Naming:

Don't use variable names such as t. They're not meaningful, not for you, not for others. In this case, use type.

Class names, public fields and method names use PascalCase and not camelCase. So, isEmpty will become IsEmpty. But then again, this is also not a meaningful name. Boolean methods or properties in C# will most likely start with Is or Has. An example for the name of your method would be HasAllEmptyProperties.

var keyword:

Use var to declare your variables instead of declaring them explicitly. The compiler will determine the type for you and your code looks cleaner.

The method:

Your code looks good. You could however make it cleaner by using LinQ. Loops won't be avoided but it looks cleaner. I'm not saying this is a perfect solution but here goes:

public bool HasAllEmptyProperties()
{
    var type = GetType();
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    var hasProperty = properties.Select(x => x.GetValue(this, null))
                                .Any(y => y != null && !String.IsNullOrWhiteSpace(y.ToString()));
    return !hasProperty;
}

I could also have used the All() method and positive comparison instead of Any(). But this is inefficient as all elements have to be checked against the condition whereas Any() will return as soon as an element satisfies the condition (like in your loop).

You can take the comparison code and throw it in an extension method for reusability. It also makes your method-code cleaner, for example:

public static class Extensions
{
    public static bool IsNullOrEmpty(this object obj)
    {
        return obj == null || String.IsNullOrWhiteSpace(obj.ToString());
    }
}

public bool HasAllEmptyProperties()
{
    var type = GetType();
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    var hasProperty = properties.Select(x => x.GetValue(this, null))
                                .Any(x => !x.IsNullOrEmpty());
    return !hasProperty;
}

Since you only have two properties, performace won't be a problem. Even if you were to add a couple more properties. Hope this helps!


Is this common way to build this class and method?

Hello and welcome to Code Review!

I'd like to first direct you to Microsoft's official naming
guidelines for C# development. Your code goes against a few of
those, and if that's your company's or team's guidelines, than great!
If you don't have an official style, start with the ones I linked to.
I'd definitely not call the convert method from the constructor.
This could throw exceptions that would prevent the object from being
created. Keep your processing methods separate and let the caller
call it. It IS public, after all!
your member variables seem a little too, well, global, in some cases.
Only _fileInfo and _newFileName are used in more than one method.
Keep the others local to their methods.

As part of this, note that _editpcap never gets assigned and is
always null. I don't think that's what you're intending.

the getNewFileName method looks very Java-like as Java didn't have
the concept of properties. This is a prime candidate for being made a
property.
the Process class is IDisposable, so wrapping it in a using
block is idiomatic.
now I'm just getting into minor nitpicking, the fields set in the
constructor are invariant after construction, so make the intent
known by using the readonly keyword. Also, you can employ modern C#
amenities as object initializers and the var keyword.

All this being said, here is my proposed refactor of the code:

public class Editcap
{
    #region members
    private readonly FileInfo fileInfo;
    private string newFileName = string.Empty;
    #endregion

    #region c'tor
    public Editcap(FileInfo fileinfo)
    {
        if (fileinfo == null)
        {
            throw new ArgumentNullException("fileInfo");
        }

        this.fileInfo = fileinfo;
    }
    #endregion

    public void ConvertFileToPcap()
    {
        this.newFileName = this.fileInfo.FullName.Replace(this.fileInfo.Extension, "_new") + ".pcap";

        string editpcap = null; // still not set, need to fix!
        var editpcapProcess = new ProcessStartInfo(string.Format("\"{0}\"", editpcap))
        {
            Arguments = string.Format("{2}{0}{2} -F libpcap {2}{1}{2}", this.fileInfo.FullName, this.newFileName, "\""),
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
            UseShellExecute = false,
            ErrorDialog = false
        };

        using (var capinfosProcess = Process.Start(editpcapProcess))
        {
            capinfosProcess.WaitForExit();
        }
    }

    public string NewFileName
    {
        get
        {
            return this.newFileName;
        }
    }
}


Releasing retained objects inside dealloc

- (void)dealloc{
    if(account_)

You don't need to do this. Objective-C ignores attempts to call methods on nil objects. So you call release and nothing will happen if its already nil

        [account_ release];
    account_ = nil;

Your object is being destroyed, there isn't a whole lot of point in setting values to nil

    [super dealloc];
}


Converting HashMap data to a Response object

The only thing you need is a saparate method doing the parsing.

This parse method can either be in a specific converter class that is used in a specific case when you're taking the strings and ammounts from a certain place.

public static FinalProduct parse(String key, Long quantity) {
    //transform into FinalProduct here
}

Or if you'll always start from those business specific Strings you could just provide a constructor for FinalProduct that takes those as input params:

public class FinalProduct{

    private String id;
    private String city;
    private Long code;
    private String client;
    private String type;
    private Long qty;

    public FinalProduct(String codedProduct, Long qty) {
        this.qty = qty;
        //parse coded input string here
    }

    // only getters here, no setters
}

Since the variables are probably not going to change after initializing the class you can make them final and not provide setters. Immutable objects are generaly easier to get right in a production code base (less edge cases when using multi threading for example).

Using streams isn't going to make much of a difference really. The parsing itself isn't going to change and the loop is already as simple as it's going to get. I personally prefer the loop version over the stream version when going through a map:

for loop:

List<FinalProduct> products = new ArrayList<>();
for (Map.Entry<String, Long> entry : map.entrySet()) {
    products.add(new FinalProduct(entry.getKey(), entry.getValue()));
}

stream:

map.entrySet().stream()
        .map(entry -> new FinalProduct(entry.getKey(), entry.getValue()))
        .collect(Collectors.toList());


1. Use parameter expansion for great effect
You can replace most of the case construct with a two ${name:#pattern} expansions. If pattern matches the value of name, the empty string is substituted, otherwise the value of name. If name is an array, matching elements will be removed from the array. So instead of this:
local before

before=1
# [...]
case $1 in
    after)
        # Append to PATH
        before=
        ;&
    before)
        shift
        ;;
esac
#[...]
if [[ -n $before ]]
then
#[...]
fi

it would look like this:
local before=${1:#after}
argv=(${argv:#[^/]*})
if [[ -n $before ]]
then
#[...]
fi

With before=${1:#after} before will be empty if the first parameter is "after", non-zero otherwise. argv=(${argv:#[^/]*}) will remove any element from argv that does not start with an /, including "before" and "after"
One difference would be, that before contains the value of the first parameter instead of 1 unless said parameter was "after". But this does not matter as long as you check only if before is non-zero.
The second difference would be, that in addition to removing "before" and "after" from argv, any relative paths (or anything that does not start with an /) will be removed, too.
2. Make use of path instead of PATH
There is no need to split PATH into an array on your own because zsh already makes the value of PATH available as an array with the array parameter path. Any change to PATH is automatically mirrored in path and vice versa. So you can manipulate path directly without the need for the local path_array parameter.
Instead of
path_array=(${(As.:.)PATH})
path_array=(${path_array:|argv})
if [[ -n $before ]]
then
    path_array=(${(Oa)argv} $path_array)
else
    path_array=($path_array $argv)
fi
PATH="${(j.:.)path_array}"

You need only
path=(${path:|argv})
if [[ -n $before ]]
then
    path=(${(Oa)argv} $path)
else
    path=($path $argv)
fi


You should code to make sure that user input doesn't break any assumptions you are making about the game. For example, I like the gimmick that the players can pick a symbol. However, you should make sure they pick a sensible one. What happens if they pick the same? What about if they pick space?

I would suggest that in the code you use fixed indicators, and replace them when you display them. If not, do some input validation to block weird choices.

As to your question about the draw detection, counting is standard. You could keep a variable to hold the count, and update it each time someone plays. That avoids most of the work recalculating each time.

Your technique for swapping between the two players works and is quite creative. However, I would strongly recommend that you have one outside loop to keep the game going and two distinct inner loops to get player input. This makes it clearer that the behaviour of the players is symmetrical.

Building on that symmetry, you could then have just one input loop and keep a variable recording whose turn it is.


Responses in comments starting with koj -.

#!/usr/bin/env python

"""
Safely copies .mpg files from one volume to another using
temporary filenames and hash verification
"""

import os
from datetime import datetime
from hashlib import sha256
from shutil import copy2

#ask user for origin (where to get files)
def choose_drive(drives, label):
    # koj - needs documentation
    while True:
        for d in drives: # koj - use for d, drive in enumerate(drives)
            print '%s - %s' % (drives.index(d)+1,d) # koj - print '%d - %s' % (d+1,drive)
        drive = raw_input('Select %s: ' % label)
        # koj - cast to int here inside a try/except. (except ValueError, continue).
        if not drive in str(range(0, len(drives)+1)): # koj - Then, no cast to string
            continue
        else:
            return os.path.join('/Volumes', drives[int(drive)-1]) # koj - no need to cast to int anymore

# safe copy
def safe_copy(src, dst):
    # koj - needs documentation
    dst_temp_name = dst+'_INCOMPLETE'
    try:
        copy2(src,dst_temp_name)
        if compare_hashes(src, dst_temp_name):
            try:
                os.rename(dst_temp_name, dst)
            except Exception as e:
                print 'Error trying to rename the file: ', e
        else:
            safe_copy(src, dst)
    except Exception as e:
        print 'Error trying to copy the file: ', e

# hash a file and return the hash string
def get_local_hash(filename, block_size=2**20):
    """
    Hashes a file using SHA1
    """
    # print 'Starting hash of %s at %s' % (filename, datetime.now().time())
    print 'Hashing', filename
    try: # koj - use a with statement to manage the file handle
        local_file = open(filename,'rb')
    except Exception as e:
        print 'Error while opening file for hashing: ', e
    hasher = sha256()
    while True:
        data = local_file.read(block_size)
        if not data:
            break
        hasher.update(data)
    # print 'Finished hash at %s' % datetime.now().time()
    result = hasher.hexdigest()
    local_file.close()
    return unicode(result)

def compare_hashes(file1, file2):
    # koj - needs documentation
    if get_local_hash(file1) == get_local_hash(file2):
        return True # koj - sure, but why not just return get_local_hash(file1) == get_local_hash(file2) ?

#main
# koj - did you really need that label?
def main():
    # get list of volumes
    drives = [d for d in os.listdir('/Volumes')]
    # ask user for origin drive
    origin = choose_drive(drives, 'Origin')
    origin_files = os.listdir(origin) # koj - filter here: (orig for orig in os.listdir(origin) if orig.endswith('.mpg'))
    # ask user for destination drive
    destination = choose_drive(drives, 'Destination')
    destination_files = os.listdir(destination)
    # for each file on origin, check if it exists on destination
    for of in origin_files:
        if of.endswith('.mpg'): # koj - see filter on line 76 above, don't need this.
            if of in destination_files:
                if compare_hashes(os.path.join(origin, of), os.path.join(destination, of)):
                    print 'already exists and is identical... skipping', of
                else:
                    print 'already exists but is different... copying', of
                    safe_copy(os.path.join(origin, of), os.path.join(destination, of))
            else:
                print 'does not exists... copying', of
                safe_copy(os.path.join(origin, of), os.path.join(destination, of))

if __name__ == "__main__":

    main()


The main change is separation of logic and User Interface. Firstly the calculation methods should ideally not reside in UI methods like event handlers.

Secondly the calculations should really be in it's own class, (but this application is just small enough that it is not ENTIRELY necessary).

in programming we hate Magic Numbers. If you can, move any numbers littered around your code and name them something useful.

so:

As 9/5 + 32 is equal to 1.8 (+32) and that number represents the scale difference, if we declare that at the top of our code like

double FAHRENEHEIT_SCALE_DIFFERENCE = 1.8;
double FREEZING_POINT_OF_WATER = 32;

Depending on how much you have covered thus far you should then move the actual conversion to it's own method.

(because if you come back to this code in 12-18months will you be able to remember what it does? What if it quadruples in size with more features?

So:

I would suggest something along the lines of

public double convertCelsiusToFahrenheit(double celsius)
{
  return celsius * FAHRENEHEIT_SCALE_DIFFERENCE + FREEZING_POINT_OF_WATER;
}

Next,
you can tidy the button click.

private void btnConvert_Click(object sender, EventArgs e)
{
    double celsius = double.Parse(txtCelsius.Text);
    lblFahrenheit.Text = convertCelsiusToFahrenheit(celsius);
}

Finally the golden change is the separation of the logic from the interface.

Now that you have a simple method that is separate from the actual screen; you could move it, and all similar methods into it's own TemperatureConverter class, or something similar.


What are best practices of creating database importer in Rails?

Some notes:

As usual, I'd recommend a more functional approach. It's not a theoretical issue, functional code is more concise, more clear. When I see @k = [] I get the shakes thinking that this variable can (and will) be modified just everywhere in the class (an instance variable is just a nasty global variable -for the scope a class, granted- with a pretty name).
Also related to FP, your code is hard to abstract because it's written with procedures instead of functions: they don't take values (as arguments) and return values, everything works by side-effects through instance variables. No referential transparency, no idempotence...
Don't create so many individual constants, group them in hashes.
File.open 'data/PAC_APO.GES', 'r'. Hardcoded files in classes? mmmm.
96 * 1000 + 760 + 9. Magic number, define it as a constant so it has a name.

Answering your particular question about how to avoid repeating code for those 3 methods: whatever is different put it as arguments. If some value depends on something the caller cannot know yet about (the code under when I, U, D), then use an argument block as callback. So it might be written:

def extract_to_database(collection)
  add       = true
  tmp       = []
  type      = K

  collection.each_with_index do |line, i|
    break if (i > 96 * 1000 + 760 + 9)

    _type    = line.strip
    _changed = TYPES.include? _type

    if _changed && i > 0
      case type
      when K then @k << tmp
      when F then @f << tmp
      when FB then @f << tmp
      when I, U, D
        yield(tmp)
      end

      tmp  = []
      type = _type
    end

    tmp << clean(line)
  end
end

Note that I kept your old imperative code (a functional approach would require rewriting the full class), but at least is now DRYed. I'd strongly encourage to try the functional paradigm, it's hard at first but it pays off on the long run. My article on this matter.


C++17 Recursive Fibonacci calculation with memoization

Compiler is g++ 4.2.

Yikes. That compiler is ancient. I’ve met competitive programmers younger than that compiler. If you’re planning to do any serious C++ programming, you really should look into upgrading your toolchain, if possible.
#define BIG unsigned long long int

This is absolutely the wrong way to create a new type.
First, there is a trend in C++ to avoid the preprocessor completely. So, no #defines, no #ifs, and so on. It is ALMOST completely unnecessary in the most recent version (C++20), but even in C++11 it is almost completely avoidable.
Rather than a #define, you should use a type alias:
using BIG = unsigned long long int;

But there’s one more problem. By convention, ALL_CAPS variable names are reserved for preprocessor macros… which basically means you should never use them. That means you should do:
using big = unsigned long long int;

Or, even better, choose a more descriptive name, like:
using big_uint = unsigned long long int;

But even better still would be to create your own namespace, and put everything—this type alias and all the Fibonacci functions—in there:
namespace your_ns {

using big_t = unsigned long long int;

int fib(int n) {
    // ... etc. ...

} // your_ns

Now I know your focus is on the memoized version of the Fibonacci algorithm, but the non-memoized one is really problematic:
int fib(int n) {
    if (n < 2) {
        return n;
    }
    return fib(n-1) + fib(n-2);
}

Imagine what happens if you call fib(5). Internally, that results in two calls to fib(4) and fib(3):
fib(5)
  ↓
fib(4) + fib(3)

Except… fib(4) also degrades to fib(3) and fib(2), while fib(3) degrades to fib(2) and fib(1):
fib(5)
  ↓
fib(4)           + fib(3)*
  ↓
fib(3)* + fib(2) + fib(2) + fib(1)

As you can see, fib(3) is called twice. And it gets even worse, because fib(3) degrades to fib(2) and fib(1):
fib(5)
  ↓
fib(4)                              + fib(3)
  ↓
fib(3)           + fib(2)*          + fib(2)*          + fib(1)
  ↓
fib(2)* + fib(1) + fib(1)  + fib(0) + fib(1)  + fib(0) + 1

Now you can see fib(2) is called three times. Each one of those times becomes fib(1) and fib(0).
fib(5)
  ↓
fib(4)                                     + fib(3)
  ↓
fib(3)                   + fib(2)          + fib(2)          + fib(1)
  ↓
fib(2)          + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + 1
  ↓
fib(1) + fib(0) + 1      + 1      + 1      + 1      + 1      + 1

So the net result of a single call to fib(5) is:

1 call to fib(4)
2 calls to fib(3)
3 calls to fib(2)
5 calls to fib(1)
3 calls to fib(0)

And that’s just fib(5). Imagine how many repeated calls you’ll get with fib(50).
(This is obviously not such a big problem with the memoized version… but it’s still a problem!)
What you really want to look into is the tail-recursive Fibonacci algorithm. I’m not going to work it out for you, but I’ll give you the interface:
auto fib_impl(int n, big_t a, big_t b)
{
    // ...
}

auto fib(int n)
{
    // are you sure you don't want to check for negative numbers?
    if (n < 2)
        return big_t(n); // note: this line won't compile if you used BIG; this is why the preprocessor sucks

    return fib_impl(n, 0, 1);
}

Now you don’t say what version of C++ you’re working with, but if it’s one of the more recent versions, then you can make all of this constexpr. That means that, when possible, the function may be computed at compile time, meaning it will have (effectively) zero run-time cost.
BIG fib_with_memo(int n) {
    if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it
        BIG val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap[n] = val;
        return val;
    }
    return umap[n]; // otherwise return the cached value
}

Now, since umap has no purpose outside of this function, it makes more sense to hide it within the function as a static variable. If you don’t know what function static variables are, they’re basically global variables, but only visible within the function.
While you’re at it, you might as well replace:
umap[0] = 0;
umap[1] = 1;

with:
umap = std::unordered_map<int, big_t>{{0, 0}, {1, 1}};

Why? Because this will be MUCH more efficient. The first way means that each line first searches the map for the key, then creates the new pair. The second way doesn’t bother with the search, but rather just creates the two pairs directly.
So now your fib_with_memo() could look like this:
auto fib_with_memo(int n) {
    // umap is constructed only once, the first time the function is called,
    // and initialized with {0, 0} and {1, 1}.
    static auto umap = std::unordered_map<int, big_t>{{0, 0}, {1, 1}};

    // note everything else is exactly the same (except I replaced the BIG
    // with auto)

    if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it
        auto val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap[n] = val;
        return val;
    }
    return umap[n]; // otherwise return the cached value
}

Another small fix is that once you’re in that if block, you know for a fact that n isn’t in the map. So rather than doing umap[n], you can emplace the new pair directly:
    if (umap.find(n) == umap.end()) {
        auto val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap.emplace(n, val);
        return val;
    }

Depending on your implementation, that might be more efficient.
Another possibly major optimization comes from the fact that you use find()… and then just discard the result. Why not use it?
    if (auto p = umap.find(n); p == umap.end())
    {
        // we didn't find n
        auto val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap.emplace(n, val);
        return val;
    }
    else
    {
        // we found n
        return p->second;
    }

So this is about where we’re at right now:
auto fib_with_memo(int n) {
    static auto umap = std::unordered_map<int, big_t>{{0, 0}, {1, 1}};

    if (auto p = umap.find(n); p == umap.end())
        auto val = fib_with_memo(n-1) + fib_with_memo(n-2);
        umap.emplace(n, val);
        return val;
    }
    else
    {
        // we found n
        return p->second;
    }
}

Now we get to the real problem: the same issue as with the non-memoized version, where you’re calling the same function over and over and over. The fix is the same as with the non-memoized version: refactor:
auto fib_with_memo_impl(int n, big_t a, big_t b) {
    static auto umap = std::unordered_map<int, big_t>{{0, 0}, {1, 1}};

    if (auto p = umap.find(n); p == umap.end())
        auto val = // actual algorithm to calculate fib here
        umap.emplace(n, val);
        return val;
    }
    else
    {
        // we found n
        return p->second;
    }
}

auto fib_with_memo(int n) {
    // are you sure you don't want to check for n < 0?

    // trivial solutions, don't even bother diving into the calculation
    if (n < 2)
        return big_t(n);

    return fib_with_memo_impl(n, 0, 1);
}

It’s up to you to implement the actual Fibonacci calculation there (you have a and b to work with). But otherwise, that should be a drop-in replacement for your current design, except orders of magnitude faster.
An alternative design
As you said:

I used a std::unordered_map (hash table) because its lookup/insertion times are \$O(1)\$ (compared to the std::map, which has \$O(log(n))\$ for both.)

Unfortunately, this thinking is misguided.
It turns out that due to the way modern processors work—particularly with caching—that big-O notation can be WILDLY misleading. I recall that the inventor of C++ himself was floored when someone showed him that a std::list, which has \$O(1)\$ insertion in the middle, is slower than a std::vector, which has \$O(n)\$ insertion in the middle, even for huge numbers of elements.
Forget all that theory crap, and instead take a step back and consider your actual problem. Imagine that you’ve called fib_with_memo(10). Okay, now what would you expect to see in the memo-map?
It would be this, right?:
0  → 0
1  → 1
2  → 1
3  → 2
4  → 3
5  → 5
6  → 8
7  → 13
8  → 21
9  → 34
10 → 55

Now look at the keys. It’s just 0 to 10, right? In order, with no holes. Just like an index.
So… why do you need a map? You’re just “mapping” an index to a value. That’s just what a basic array, or a vector, does.
Let’s imagine that we’re using a vector for the memoizing, with the “key” just being the index. That means after memoizing fib_with_memo(10), the vector would contain:
[index 0 ] → 0
[index 1 ] → 1
[index 2 ] → 1
[index 3 ] → 2
[index 4 ] → 3
[index 5 ] → 5
[index 6 ] → 8
[index 7 ] → 13
[index 8 ] → 21
[index 9 ] → 34
[index 10] → 55

So, after fib_with_memo(10), the vector contains 11 elements, and the element at index n—or, vec[n]—is the nth Fibonacci number.
Simple, right?
So how do you tell whether a number is already memoized? Again, simple, just check the vector’s size. If we call fib_with_memo(13), the vector must have at least 14 elements in it for vec[13] to be valid. So:
if (vec.size() > n)
    return vec[n];
else
    // calculate the nth fibonacci number

In fact, the implementation becomes trivial, too. That’s because if the function is called with an unmemoized n, all you need to do is resize the vector to n + 1, and fill in all the numbers between the old size and the new size. Something like:
auto fib_with_memo(int n) {
    // are you sure you don't want to check for n < 0?

    // trivial solutions, don't even bother diving into the calculation
    if (n < 2)
        return big_t(n);

    static auto vec = std::vector<big_t>{0, 1}; // start with fib(0) and fib(1)

    // note that if you really want, you could start with more than just
    // 0 and 1 - after testing your real-world use case, you could determine
    // that you will need, say, up to fib(8), so you could precompute that
    // much and put it in the vector initializer list above
    //
    // if you make the non-memoized fib function constexpr, then you could
    // even be *really* clever, and do something like:
    //      static auto vec = std::vector{fib(0), fib(1), fib(2), fib(3), ...
    // for as many precomputed values as you like.
    //
    // and then you could be *REALLY* clever (if you’re using a more modern
    // version of c++), and do something like:
    //      static auto vec = [](auto initial_size) {
    //          auto v = std::vector<big_t>(std::min(2, initial_size + 1));
    //          v[0] = 0;
    //          v[1] = 1;
    //
    //          for (auto p = std::next(v.begin(), 2); p != v.end(); ++p)
    //              *p = *(p - 1) + *(p - 2);
    //
    //          return v;
    //      }(4); // 4 to calculate fib(0) though fib(4), but you can use any number
    // but that's getting *really* fancy.

    // memoized, so use cached value
    if (vec.size() > n)
        return vec[n];

    // not memoized, so calculate all the values between what's been cached,
    // and what's desired

    auto old_size = vec.size();
    vec.resize(n + 1);

    // now fill in everything from vec[old_size] to vec[n] inclusive,
    // where vec[i] = vec[i - 1] + vec[i - 2]

    return vec[n];
}

Obviously I haven’t profiled this design, but I’d bet it is hundreds, if not thousands of times faster than a similar design using a hash map.
Questions
Difference between a macro and a type alias
When you do:
#define type long double

you’re talking to the preprocessor here… not the compiler.
The preprocessor is stupid (as in, unintelligent), it doesn’t understand C++ (often the same preprocessor is used for C, C++, and sometimes even other languages, like Objective-C, and sometimes Fortran, etc.). It just deals with meaningless tokens. In this case, it just does a blind textual substitution. Everywhere type appears in the code, it just gets literally replaced with long double—literally as if you manually did copy-paste—with no regard as to whether that makes sense.
To see where that causes problems, consider the following code:
struct thing
{
    std::string name;
    std::string type;
};

type value =
    type(0);

Everywhere type appears gets replaced with long double, so…:
struct thing
{
    std::string name;
    std::string long double; // compile error
};

long double value =
    long double(0); // compile error

Note that it didn’t just replace type when it is actually naming a type—which can still cause syntax errors, as it does for the second error above—it also replaced type when it was the name of a variable in the class. That’s why the preprocessor is so dangerous. It’s dumb. It’s indiscriminate. It blindly replaces everything, even when it makes no sense.
Now, when you do:
using type = long double;

you’re talking to the compiler here, not the preprocessor, and that makes all the difference.
This creates a type alias that the compiler understands. The compiler understands C++. The compiler doesn’t just blindly replace text, it knows when type is actually naming a type (and it’s not a variable name, for example), and even knows which type it’s naming (because namespace_1::type may not be the same as namesapce_2::type), and it does the replacement intelligently.
So when the compiler sees the original code:
struct thing
{
    std::string name;
    std::string type;
};

type value =
    type(0);

it will not replace the type in class thing, because that’s not a type, it’s a variable name. And it will replace the type in the last two lines… but not simply by literally replacing the text (which would break the cast on the last line). Instead, it will do the replacement intelligently. value will be a long double, and the last line is casting a 0 (an int) to a long double… everything just works.
In summary, the preprocessor is dumb. It just does blind text replacement, with no regard for what that text actually means… which often results in breaking code. By contrast, the compiler actually understands C++, so it knows when something is actually a type and when it’s not—and even which type it is—so it can do type substitutions intelligently, and not break code.
Refactored code
The standard on CodeReview is not to re-review code in the same question, but rather to post a new review request with the new code. So I can’t re-review your refactored code here. BUT! What I can do is give you suggestions to help you in your refactoring, and in general.
The number one most important thing you can do when coding, not just in this case, but always, is WRITE TESTS. This is the absolute most important skill as a programmer you could ever develop. If I were hiring, and I had two candidates, and one wrote tests and the other didn’t… I wouldn’t even look at the second, I wouldn’t even give them a shot, regardless of how “good” a coder they might be. A coder that doesn’t write tests would be worse than useless to me… yes worse than useless, because they’d actually be a net maintenance burden. I’d literally rather hire nobody than hire someone who doesn’t write tests.
Even if you’re just doing hobby programming, you should get in the habit of writing tests. I swear it will change your life. It makes everything so much easier. And you no longer have to wonder “does my code work?” You’ll just know. And if someone points out a bug you missed… no problem, just add a new test case that catches the bug, then fix it, and now you’re even more sure your code works.
Testing is so important, that I even recommend writing the tests before you write the first line of “real” code.
The first thing you should do is look into a proper testing system. I use Boost.Test but… it’s extremely heavyweight. (I mean, it’s awesome—by far the most powerful testing system—but, yeah, it’s not trivial to set up.) You might like Catch2. GoogleTest is another option but… meh.
The easiest way to set up Catch2 (other than using your system package manager, if you’re on Linux) is to download the two files mentioned at the start of the tutorial—catch_amalgamated.hpp and catch_amalgamated.cpp—and just put them in the same directory as your project. In that directory you should have (at least) fibonacci.hpp, fibonacci.cpp, fibonacci.test.cpp, catch_amalgamated.hpp, and catch_amalgamated.cpp:

fibonacci.hpp: your header
fibonacci.cpp: your implementation
fibonacci.test.cpp: your tests
catch_amalgamated.hpp: the Catch2 header
catch_amalgamated.cpp: the Catch2 code

and when you compile, you need to make sure to also compile the Catch2 code:
# only need to do this one time, which is good, because it will be slow
$ g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp

# should do these every time
$ g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp
$ g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp
$ g++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o
$ ./fibonacci.test

Or, better yet, put all those commands in a shell script or makefile. Also, you could use --std=c++11 or --std=c++14 or even --std=c++20, depending on what version of C++ you want to use.
Here’s a simple build script you could use:
#!/bin/sh

# Stop immediately if something fails.
set -e

# Only recompile Catch2 if we have to.
if [ ! -f catch_amalgamated.o ]
then
    printf '%s\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp'
    g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp
fi

# Compile everything else.
printf '%s\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp'
g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp

printf '%s\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp'
g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp

# Link.
printf '%s\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o'
g++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o

Put that in build.sh, make it executable, and you can just do:
$ ./build.sh
$ ./fibonacci.test

That will speed up your workflow, and anything that speeds up your workflow is a good thing. (Even better than a build script would be a proper makefile, but that’s too complicated for here.)
The test file doesn’t need to be complex:
// fibonacci.test.cpp

#define CATCH_CONFIG_MAIN
#include "catch_amalgamated.hpp"

#include <random>

#include "fibonacci.hpp"

// You should always test important edge cases:

TEST_CASE("Fibonacci(0) memoized is 0")
{
    CHECK(your_ns::fib_with_memo(0) == 0);
}

TEST_CASE("Fibonacci(1) memoized is 1")
{
    CHECK(your_ns::fib_with_memo(1) == 1);
}

// Doesn't hurt to test a few random cases:

TEST_CASE("Fibonacci(10) memoized is 55")
{
    CHECK(your_ns::fib_with_memo(10) == 55);
}

TEST_CASE("Fibonacci(20) memoized is 6765")
{
    CHECK(your_ns::fib_with_memo(20) == 6765);
}

// Test the *property* of Fibonacci numbers:

TEST_CASE("Fibonacci(n) memoized is Fibonacci(n - 1) + Fibonacci(n - 2)")
{
    constexpr auto lower_limit = 5;
    constexpr auto upper_limit = 50; // or maybe as high as 90-ish, if you like

    constexpr auto number_of_trials = 3;

    auto rng = std::mt19937{std::random_device{}()};
    auto dist = std::uniform_int_distribution<int>{lower_limit, upper_limit};

    for (auto trial = 1; trial <= number_of_trials; ++trial)
    {
        // random number between lower and upper limit, inclusive
        auto const n = dist(rng);

        DYNAMIC_SECTION("n = " << n)
        {
            auto const fib_n = your_ns::fib_with_memo(n);
            auto const fib_n_minus_1 = your_ns::fib_with_memo(n - 1);
            auto const fib_n_minus_2 = your_ns::fib_with_memo(n - 2);

            INFO("fib(n) = " << fib_n);
            INFO("fib(n - 1) = " << fib_n_minus_1);
            INFO("fib(n - 2) = " << fib_n_minus_2);

            CHECK(fib_n == (fib_n_minus_1 + fib_n_minus_2));
        }
    }
}

Test cases should be as simple as possible. Indeed, the last case is pretty complex for a test case in my opinion, but most of it is just generating random values for n and recording the intermediate results so you can see exactly where things went wrong.
At first this shouldn’t compile, because fib_with_memo() shouldn’t exist yet (assuming you’re writing the tests first, which you normally should). So you just write some placeholders:
// fibonacci.hpp

#ifndef INCLUDE_GUARD_fibonacci
#define INCLUDE_GUARD_fibonacci

namespace your_ns {

using big_t = unsigned long long int;

big_t fib_with_memo(int);

} // namespace your_ns

#endif // include guard

// fibonacci.cpp

#include "fibonacci.hpp"

namespace your_ns {

big_t fib_with_memo(int)
{
    return {};
}

} // namespace your_ns

Now it should compile and run… and generate a bunch of test case failures. But that’s good! A failing test case means that at least something is being checked, and it probably means that a bug was found.
I got 2 cases passed, and 3 failures. The 2 passes are because fib_with_memo(0) returns 0… which by fluke happens to be correct, and because since fib_with_memo(anything) returns 0, that means fib_with_memo(anything) == fib_with_memo(anything - 1) + fib_with_memo(anything - 2) is always true. This happens sometimes as you’re developing; broken code happens to return the “right” answer… or at least an answer that “works”. Other tests should catch that problem, though.
So now you start to develop your Fibonacci algorithm. Let’s say as a first step, you do:
big_t fib_with_memo(int n)
{
    if (n < 2)
        return n;

    return {};
}

Compile and run… now 3 tests pass, and 2 fail. Progress!
This is how you do it. Take tiny steps, and check as you go. It may sound tedious, but once you get in the habit, it becomes automatic.
So the next thing I’ve done is just copy-pasted your refactored code into fib_with_memo() (I also needed to #include <vector>, and I needed to rename big to big_t because I didn’t notice I’d got the name wrong), and…
ALL TESTS PASSED!
Congratulations!  Check it in!
So your refactored code works… but… can it be improved? Well, that’s a question for another code review. Catch2 also supports benchmarking, so you can even do performance checks in your testing code, and as you make changes, you can see if things speed up or not.
But the point is, if you adopt this style of development—testing, testing, testing, testing—you will write better code, quicker, and when it comes time to refactor, you can do so with confidence because if you “break” anything, the tests will catch it immediately. It’s such a nice way of coding that once you get in the habit, you can’t quit; you feel naked and unsteady when you’re trying to code without tests.
Some other tips:

I suggested putting the memo map (or vector) in the function as a static variable, and that’s definitely what you should do for the final code. However, while developing, you could pull it out and make it a global, so you can inspect what’s in the map/vector directly, and make sure that it’s working properly. It’s okay to break stuff while you’re working on it, once you remember to put things back in order when developing/testing is done.

If you do pull the memo map/vector out and make it a global (for development only), then you can observe its capacity to make sure it’s not wasting space. You can also use a tracing allocator to track allocations, and see if you’re losing efficiency there.
A simple tracing allocator is:

template <typename T>
class tracing_allocator
{
public:
    using value_type = T;

    // not needed in C++17
    using propagate_on_container_move_assignment = std::true_type;

    auto allocate(std::size_t n)
    {
        std::cout << "allocating " << n << " bytes\n";
        return std::allocator<T>{}.allocate(n);
    }

    auto deallocate(T* p, std::size_t n)
    {
        std::cout << "deallocating address " << static_cast<void*>(p) << ", which is " << n << " bytes\n";
        return std::allocator<T>{}.deallocate(p, n);
    }
};

template <typename T1, typename T2>
constexpr auto operator==(tracing_allocator<T1> const&, tracing_allocator<T2> const&) noexcept
{
    return true;
}

// not needed in C++20
template <typename T1, typename T2>
constexpr auto operator!=(tracing_allocator<T1> const&, tracing_allocator<T2> const&) noexcept
{
    return false;
}

And you’d use it by declaring your vector as:
static std::vector<big, tracing_allocator<big>> mem = {0, 1};

And now you will get trace statements printed to standard output, for every allocation (and deallocation). This will help you observe how your memo map/vector is growing, and whether there are unnecessary/overlarge allocations happening.


Activity Selection to maximize the number of activity executions

Note: your code doesn't currently compile for at least two reasons: you are not telling the compiler cout and endl live in the std namespace, and you can't declare your arrays start and end because n is not known at compile-time (instead, you'd have to use dynamic memory allocations).

In any case, your code smells like your background might be in C (but then you'd probably also know about dynamic memory... well, anyway). Indeed, with C++, you typically define variables as close to their site of usage. Moreover, you could take advantage of the algorithms and data structures provided by the language.

  Is there a better approach than sorting arrays and comparing?

Essentially no: you must sort the arrays (with no additional knowledge, you can't beat the log-linear bound). This dominates your runtime, but it is scalable and practical enough that you don't have to worry about it.

  What is a better way to sort the two arrays on the basis of the second array?

Because start and end times are logically and tightly coupled (i.e., something is wrong if we suddenly lose the correspondence), it's a good idea to tie them together. For that reason, we can use std::pair. To store such objects, we can use a dynamic array, i.e., std::vector. For sorting that according to the second element, we can use std::sort.

To summarize, we could proceed along the following lines (I'm taking the liberty to omit reading input to avoid clutter):

#include <iostream>
#include <algorithm>
#include <vector>

typedef std::vector<std::pair<int, int> > PairList;

int activitySelection(const PairList& p)
{
    PairList s(p);
    std::sort(s.begin(), s.end(), [](const auto& x, const auto& y) {
        return x.second < y.second;
    });

    int end = s[0].second;
    int count = 1;

    for (int i = 1; i < s.size(); ++i)
    {
        if (s[i].first >= end)
        {
            ++count;
            end = s[i].second;
        }
    }

    return count;
}

int main()
{
    PairList v{ {1,2},{3,4},{2,6},{5,7},{8,9},{5,9} };
    std::cout << activitySelection(v) << "\n";
}


Python get UTC offset for when only naive date time objects are available

Take advantage of Python operator overloading

is_behind_utc = time_now < time_utc

If the current time is less the the UTC time then we are behind UTC time.

There is no need to use logic concerning seconds.

Longer names > comments

# Flag variable to hold if the current time is behind UTC.
is_behind_utc = False

Let's analyze the comment:

Flag variable : this can easily be deduced as it is a boolean
to hold if : each variable holds something
the current time : valuable information
is behind UTC : already present in the variable name

So I could write:

current_time_is_behind_utc = time_now < time_utc

The name incorporates the valuable information in the comment, avoids the unnecessary and the repetition of the same concept.

Use ternary when sensible

if is_behind_utc:
    pos_neg_prefix = "-"
else:
    pos_neg_prefix = "+"

I cringe because such verbosity obscures what is simple:

pos_neg_prefix = '-' if current_time_is_behind_utc else '+'

Simplify avoiding too many variables

utc_offset_fmt = time.strftime("%H:%M", utc_offset)
utc_offset_str = pos_neg_prefix + utc_offset_fmt

return utc_offset_str

Can simply be:

return pos_neg_prefix + time.strftime("%H:%M", utc_offset)

I think that each additional variable is an addition burden and point of failure in the code being another layer of indirection, and tend to avoid too many variables when sensible.


You can use the amazing parse_str() function. It does everything you need. But you are using different delimiters for key => value pairs. If you change those to & and =, you can do like this:

$filtersStr = 'id=1&name=alex';

parse_str($filtersStr, $filters);

And $filters will have what you want. But that's not the case, so, one could do this:

parse_str(
    str_replace(
        array('%', '=', '&', '||', ':'),
        array('%26', '%3D', '%26', '&', '='),
        $filtersStr
    ),
    $filters
);

The characters %, = and & will have a special meaning. They have to be replaced with their URL-codes. parse_str() works on URL-encoded strings and leaving those characters unchanged would cause all sorts of bugs. The order of the elements in the array is VERY important.

Here's how it works:

Replace % by %26
It must be the first of you will be replacing % everywhere and break it
Replace = by %3D
This guarantees that no meaningful = will be replaced
Replace & by %26
Replace || by &
Replace : by =
At this point, your 'id:1||name:alex' will be 'id=1&name=alex'
Hand it over to parse_str()

And done! I prefer the first method instead of this kludge. Use this second one with extreme care!

In a comment, it was explained that it's usage was like this:

/arena?filter=id:1||content_name:alex&anotherParam=smth

If you can change the URL, throw this whole code away and do like this:

/arena?filter[id]=1&filter[content_name]=alex&anotherParam=smth

This will have the exact structure you wish. Simply use $_GET['filter'] to access all values. And done! An alternative with 0 lines of code!


Your function name is strange. You wanted to get a sequence of random numbers and operations whose result is an even number. But you named your function genOddSeq. Also, avoid abbreviations. Write code for the human, not the machine.

Instead of using an empty array and a loop to fill that array, consider using Array(), Array.fill() and array.map(). For example, creating an array of 10 random values from 0 to 1 would look like:

const tenRandomDecimals = Array(10).fill().map(Math.random)

You can do the same for the operations.

Now instead of hard-coding the logic of the operation selection inside a ternary, consider using a key-value pair where the key is + and * and the values are functions that accept two numbers which do the actual operation. When you generate an array of random + and *, just use them to get the actual function in the key-value pair.

if (numbersComp % 2 != 0) {
  result[getRandomInt(0, count)] += 1
}

This bit of logic is strange. Do you really need to get a random value? Or can you just use one from a known location, like the first number?

Last but not least, tests. It's always good practice to start with tests. Even other code review posts include a minimal form of test to verify the code is working.

Anyways, here's how I'd implement it. A bit longer, but there's no surprises. There's no state held, no variables to keep track of. Also using const both as a signal and a guarantee that the value will not change during runtime.

const operationFunctions = {
  '+': (a, b) => a + b,
  '*': (a, b) => a * b,
}
const operationKeys = Object.keys(operationFunctions)
const getRandomInteger = (min, max) => Math.floor(Math.random() * (Math.ceil(max) - Math.ceil(min))) + Math.ceil(min)
const getRandomOperationKey = () => operationKeys[Math.floor(Math.random() * operationKeys.length)]
const range = size => Array(size).fill().map((v, i) => i)

const getEvenResultSequence = count => {
  const firstNumber = getRandomInteger(1, 10)
  const numbers = range(count - 1).map(() => getRandomInteger(1, 10))
  const operations = range(count - 1).map(getRandomOperationKey)
  const result = operations.reduce((c, v, i) => operationFunctions[v](c, numbers[i]), firstNumber)
  const adjustedFirstNumber = result % 2 ? firstNumber + 1 : firstNumber

  return [[adjustedFirstNumber, ...numbers], operations]
}

console.log(getEvenResultSequence(4))
console.log(getEvenResultSequence(4))
console.log(getEvenResultSequence(4))
console.log(getEvenResultSequence(4))
console.log(getEvenResultSequence(4))


to use a constructor or not use a constructor

I think a class provides benefits when you need two things:

Persistent data associated with an instance, and
Methods that do something with the data

If you only need to consolidate data in a single data structure, an object or array is simpler and more suitable.

If you only need to perform an operation on data and produce a result, and then have other not-very-related code work with the result, a plain function is simpler and more suitable.

Your situation looks to fall into the second category. You have data that you want to validate, but all you want to do is validate, and the possible class wouldn't be doing anything else. If all you're doing with a class to set a property, then retrieve that property in a method to process data, and then you never use the instance again, there's not much point to having the class at all - it's just noise. I'd use a standalone function instead.

export const validate = (data) => {
  const results = {};

  const validateInputDataForMissingKeys = checkInputDataForMissingKeys(data);
  if (validateInputDataForMissingKeys) Object.assign(results, validateInputDataForMissingKeys);

  const validateInputDataForMissingValues = checkInputDataForMissingValues(data);
  if (validateInputDataForMissingValues) Object.assign(results, { validateInputDataForMissingValues });

  const validateInputDataMaximums = checkInputDataMaximums(data);
  if (validateInputDataMaximums) Object.assign(results, { validateInputDataMaximums });

  return results;
};

Then call it like:

const validationForInputsResult = validate(inputData);

Also note that you should strongly prefer using const instead of let. let is a warning to other readers of your code (possibly including yourself, in the future) that you may be reassigning the variable in the future. If you're not going to reassign, better to use const, since it requires less cognitive overhead.

The checkInput functions and validateInput variables look a bit repetitive. If possible, it would be nice to change things so that they return an empty object instead of a falsey value, and have checkInputDataForMissingValues and checkInputDataMaximums return objects with validateInputDataForMissingValues and validateInputDataMaximums properties. That way, you can spread them directly into the results object:

const validate = data => ({
  ...checkInputDataForMissingKeys(data),
  ...checkInputDataForMissingValues(data),
  ...checkInputDataMaximums(data),
});

Having 3 separate checkInputData functions plus validate feels a tiny bit off to me. Organization-wise, you could consider putting them all into an object, together with validate if they're not used anywhere else, that way all the related functionality is in a single data structure:

export const validator = {
  checkInputDataForMissingKeys(data) {
    // ...
  },
  checkInputDataForMissingValues(data) {
    // ...
  },
  checkInputDataMaximums(data) {
    // ...
  },
  validate(data) {
    return {
      ...this.checkInputDataForMissingKeys(data),
      ...this.checkInputDataForMissingValues(data),
      ...this.checkInputDataMaximums(data),
    };
  }
};

and

const validationForInputsResult = validator.validate(inputData);