IQueryable left outer join linq extension

Actually, it is way more complex than that, since Funcs<> cant't be translated to the database, so you'll have to "call" the expression. But since you can't call a expression, you'll have to change the expression into another that means what you need it to means.

Check out this question on StackOverflow. It has an good explanation on Linq inner workings and the accepted answer has a method that do the outer join. Be sure to read the second answer too, since it shows some issues that arise on more complex queries. And just as a warning, the method you are trying to write will easily gets 150 lines long (that's why I didn't copied it here)...


"Stack Exchange page visits" alike implementation

My 2 cents:

I would not use an array of objects to represent the pages, I would use an object where each $scope.ad.id is a property and where the value is the last time visited. This would take out your loop and dupe management
Any enterprising individual is able to artificially inflate the counter, either by clearing the localStorage or by calling FData.incrementVisitsForID(id); in a loop from the console.
Are you sure that 10 minutes = 3600 * 10, it seems wrong to me

I would counter propose something like this:

//Is data storage available?
if(typeof(Storage)!=="undefined")
{
  var tenMinutes =  1000 * 60 * 10; //10 minutes
  var now = (new Date()).getTime();
  //Get visits array from local storage or if that fails, an empty object
  var visits = JSON.parse(localStorage.getItem('visits')) || {};
  //Get time of last visit, or 0
  var lastVisit = visits[ $scope.ad.id ] || 0;
  //Does it count?
  if( now - lastVisit > tenMinutes)
  {
    FData.incrementVisitsForID( $scope.ad.id );
  }
  //Update visits for the next time
  visits[ $scope.ad.id ] = now;
  //Save visits array in local storage
  localStorage.setItem('visits', JSON.stringify(visits));
}


Best Approach for Assignment Code in Node.js (ES6 style)

For flat objects (i.e. whose values are only primitive types), there's Object.assign(), which shallow-copies all enumerable keys and values from one object to the other:

Object.assign(data, body);

However, in your case, shallow-copying means the dateObj member of the body would get copied by reference, instead of creating a new object and recursively copying its keys and values.

You can also try using the spread operator ..., which was introduced recently:

let data = new Data();

Object.assign(data, {
    // Shallow-copy all keys and values from body:
    ...body,

    // Overwrite certain keys:
    date: new Date(body.date),
    dateObj: { ...body.dateObj },
});

Whether or not this code is readable or intuitive is up to you to decide.

Also, as a minor note, Object.assign returns the first object you pass to it, so instead of this:

let data = new Data();
Object.assign(data, { /* ...properties */ });

You can write this:

let data = Object.assign(new Data(), { /* ...properties */ });


Write directory new entries to file periodically, keeping the ones that existed in the past

Use sort's -u and -o switches:

find … | sort -u - $file -o $file


Main script

Consider using the commander module. One benefit you get is that it parses arguments for you. Another is that the API that declares the arguments and options  autogenerates --help text for you. This way, you avoid having to write all the argument parsing yourself and you get a self-documenting CLI.

Lookup module

Move that require call outside the function. You only need to import aes once, not on every call to the lookup function.
When inside an async function, you can use await to write async operations in a synchronous-looking fashion. When you use await, you can assign the resolved value of an async operation to a variable in the same way you do it with synchronous operation.
The code inside the for-of is essentially a filter operation. Consider using array.filter() instead, assuming data is just an array.
I also recommend breaking out that nested ternary into nested if statements for readability. You could arrange the conditions so that it's cascading rather than nested.
I recommend returning an empty array instead of false when no matches are found. This way, the consuming code won't have to deal with type checking.

Decrypt module

The decryptAll function does not appear to rely on any variables in the scope of the exported function. You can move decryptAll out of that function.
That for-of is essentially a mapping function (transforming one array's values into another array of values). Use array.map() instead.
Since decryptAll is just mapping select properties into a new object, you can use a combination of destructuring and shorthand properties to simplify it.

Bottom line, your code could look like this:

Lookup

const aes = require('../../Code/MiddleWare/Security/index').encryption.AES

module.exports = async function(type, string, users, exact,  encrypted = true) {
  return await users.query('Users').filter(i => {

    // Technically, the encrypted block is a nested ternary in the
    // false portion of the first ternary. But written this way,
    // it looks like a flat list.
    return !encrypted ? i[type] === string
      : exact ? aes.decrypt(i[type]) === string
      : aes.decrypt(i[type]).match(string)
  })
}

Decrypt

const decrypt = require('../../Code/MiddleWare/Security/encryption').AES.decrypt

// Destructure arguments, then return an object with shorthand properties.
// Eliminates obj.
const decryptAll = ({ ID, Username, Email, Data, Password }) => {
  return { ID, Username, Email, Data, Password }
}

module.exports = function(array) {
  // We're expecting an array so the check is no longer needed.

  const retval = array.map(i => {
    const item = decryptAll(i)
    const itemWithDecryptedData = { ...item, Data: JSON.parse(item.Data) }
    return itemWithDecryptedData
  })

  return retval
}


Simple customer SQL query using a class and function

One thing you are doing well:

Dependency injection - I like how you pass the PDO object to the method that needs to use it. Since that is not an abstract function however, I wonder if you should be passing the PDO object to the class upon instantiation in the constructor (that is of course if the class needs a valid PDO object for other methods as well).

Some things I would suggest

TheGetCustomerName() method only considers the happy path with regards to the query.  What happens if prepare() fails?  What happens if execute() fails?  What happens if query operates correctly but no query match is found (i.e. id doesn't exist in table)? You should be handling these edge cases and either logging errors and/or handling exceptions if using PDO in exception mode (which it looks like you are).  You might consider throwing or rethrowing an Exception from this method itself if something fails.  You should consider returning null or false from this method if something fails and/or the SQL lookup is not successful.
You should consider enforcing types in you method signature.

Perhaps something like:

function GetCustomerName(PDO $pdo, $customer_id) {

or in PHP7 (which supports type hinting for scalars) and assuming $customer_id need to be an integer value:

function GetCustomerName(PDO $pdo, int $customer_id) {

This will allow you to enforce that a valid PDO instance is passed to the method, otherwise an InvalidArgumentException will be thrown.  This prevents you from having to do something like if ($pdo instanceof PDO) in your method.

Related to the above item. Right now your method assumes all passed parameters are valid.  You should always assume you are getting passed bad data and make sure you have appropriate parameters passed to the method before doing any other work in the method.  I would enforce PDO in signature as noted above, and if not using PHP 7 at least add a line like the following.

Example:

if (empty($customer_id) || !is_int($customer_id) || $customer_id < 1) {
    throw new InvalidArgumentException(
        'Send me a valid positive integer for $customer_id' .
        ' Value sent: ' . var_export($customer_id, true)
    );
}

You do not need an include for PDO code in your customer class.  You are taking on the PDO object as a dependency (which is a good example of dependency injection).  The customer class code therefore doesn't need to reference the code where the PDO object is created. It just needs to know it has a valid PDO object passed to it, not reference the code where such objects are created.  You should reference your include_once('pdo.inc.php'); line in test.php where the dependent PDO object is actually instantiated.
You should consider following typical PHP syntax schemes.  Typically in PHP you would NEVER see a function or method name that starts with a capital letter. This syntax is typically reserved for classes and interfaces.  I would consider renaming to getCustomerName().
I would consider separating your configuration from the place where you instantiate the PDO objects.  If you ever have the need to instantiate multiple database connections, you would want to separate these.  Oftentimes it is best to use constants to define these sorts of configuration values such that you don't tend to overwrite them and can see directly in code that these should be constant values.
You should consider changing the class name to Customer instead of Customers if a single class instance is expected to only deal with a single customer vs. a collection of customers. This may seem nitpicky, but it is typically best practice for developers to use meaningful names for items in code.  If Customer more correctly describes what the object represents than Customers, the singular version should be used.

You also ask about try-catch usage.  Generally you should use a try-catch block around any lines of code that you think might throw an exception and you want to be able to handle that exception in the code such that code execution will not terminate due to the uncaught exception.  For example in you method.  You should, at a minimum, have a try-catch block around the prepare(), bindParam()and execute() calls if you are using PDO in exception mode (which I would recommend). You could have one block around all this or multiple blocks depending on how granularity you want to handle the failure.

In test.php for example you would want to place a try-catch around the call to $a->GetCustomerName($pdo, 1); As this call could throw an exception (particularly if you added some of the parameter handling logic I mentioned earlier).

So for me, a rewrite of your code might look like:

pdoConfig.inc.php

<?php
define('DB_CONFIG_HOST', 'localhost');
define('DB_CONFIG_DB', 'dev');
define('DB_CONFIG_USER', 'dev');
define('DB_CONFIG_PW', 'dev');
$dsn = 'mysql:host=' . DB_CONFIG_HOST . ';dbname=' . DB_CONFIG_DB . ';';
define('DB_CONFIG_DSN', $dsn);l
?>

customer.class.php

<?php
class Customer
{
    function getCustomerName(PDO $pdo, $customer_id)
    {
        // validate parameters
        // in PHP 7 you would just add int type hinting in method signature
        // and could change the conditional below to only look
        // positive integer values assuming the id is > 0
        if (empty($customer_id) || !is_int($customer_id) || $customer_id < 1) {
            throw new InvalidArgumentException(
                'Send me a valid positive integer for $customer_id' .
                ' Value sent: ' . var_export($customer_id, true)
            );
        }

        // query DB for customer name
        $query = "SELECT first_name
                  FROM Customers
                  WHERE customer_id = :customer_id
                  LIMIT 1";
        try {
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':customer_id', $customer_id);
            $stmt->execute();
            if($stmt->rowCount === 0) {
                // no match found
                return false;
            } else {
                return $stmt->fetchColumn();
            }
        } catch (PDOException $e) {
            error_log(
                'Something went wrong with query. Message: ' .
                $e->getMessage();
            );
            // you could also rethrow exception here instead of returning null
            // if you want to abort method completion and have caller handle exception.
            // or of course not use try-catch block here at all
            // if you don't want any extra exception handling in this method.
            return null;
        }
    }
}

?>

test.php

<?php

include_once('pdoConfig.inc.php');
include_once('customers.class.php');

// instantiate PDO object
try
{
    $pdo = new PDO(DB_CONFIG_DSN, DB_CONFIG_USER, DB_CONFIG_PW);
} catch (PDOException $e) {
    error_log('Connection failed with: ' . $e->getMessage());
    die();
}

// instantiate customer object
// you might want to include in try-catch if instantiation is expected
// to potentially throw exceptions
$a = new Customer();

try {
    echo $a->getCustomerName($pdo, 1);
} catch (Exception $e) {
    error_log('Customer name lookup failed with: ' . $e->getMessage());
}
?>


Project Euler #12 - first triangle number with more than 500 divisors

Nitpicks

using namespace std;

This can be a bad habit to start.  See Why is using namespace std bad practice?

unsigned int sqrt_ = sqrt(number);

I don't like the name sqrt_.  Something like sqrt_number would be better in my opinion.

unsigned int number = 0;
for (unsigned int i = 1; ; i++)
{
    number+=i;
    if(getDivisorCount(number)>500)
        break;
}

That's an odd way to write a loop.  You are iterating i but never checking it.  I would prefer something like

for ( unsigned int number = 1, i = 2; getDivisorCount(number) <= 500; number += i, i++ ) ;

That's rather dense -- it might be easier in a while loop.  But at least this has a variable declaration, a loop check, and an increment.  Also, it avoids having to break to exit the loop.

unsigned int number = 1;
unsigned int i = 2;
while ( getDivisorCount(number) <= 500 ) {
    number += i;
    i++;
}

Analysis

You refer to your original code as quadratic, but quadratic in what?  The outer loop in main runs i times.  The inner loop runs number times.  What's number in terms of i?  The answer is that number is quadratic in i.  I.e. \$O(i^2)\$.  So we actually run the inner loop in getDivisorCount \$O(i^3)\$ times.

The optimized loop only runs the square root of number times.  But we know that the square root of number is about i.  So overall, it runs \$O(i^2)\$ times.

So the difference between the two is about i in magnitude.  What's i in this case?  Well, without giving the exact answer, I'll tell you that it's over 10,000.  You can get the exact answer by replacing

cout << number;

with

std::cout << i;

Note that you may have to move the declaration of i outside the loop.

Anyway, that's why your revised code is more than 10,000 times faster than your original code.  That's how big i was.

More generally, when going from \$O(n^2)\$ to \$O(n)\$ in an otherwise similar algorithm, you don't take the square root of the time.  You divide by n.  In this case, i or number is n.  This is why \$O(n)\$ is so much better than \$O(n^2)\$.


How to refactoring function when I've to do many things in one function

A low-hanging fruit will be defining some interfaces of datastores such as MyDB so that some details can be hidden from the controller code. For instance:

 const storeData = new MyDB();
 storeData.employee_id = empId;
 storeData.work_id = workId;
 storeData.value = value;
 storeData.date_start = date_start;
 storeData.date_end = date_end;
 storeData.status = 3;
 storeData.group_name = groupName;
 await storeData.save();

can be refactored to something like:

 MyDBBuilder
     .with(getData)
     .withStatus(3)
     .withGroupName(groupName)
     .save();

The complexity comes from the fact that it takes 4 steps to complete this business transaction. Unless there is a way to redefine data schema, all we can do here is to encapsulate the complexity and not expose it in the controller code.
In some cases, it might be appropriate to have all the db operations in some stored procedure, if you are not concerned with portability.


Spreadsheet function that gives the number of Google indexed pages

Comments

Never place them between the closing parenthesis and the opening bracket of the statement.
Comments are meant to be read, and not set aside. Here are suggestions for cleaner comments:

//Before the lines concerned, like this one
someObject.someFunction();

//Inside blocks of statements
if(foo){
  //If foo, then call foo
  foo();
} else if(bar){
  //If bar, then call bar
  bar();
}

Prettify Code

To make your code a bit readable, but save yourself the hassle of formatting it manually, use a prettifier. An example is jsbeautifier.

Code

function indexedpages(myUrl) {

  // JavaScript doesn't have block scope like C. Variables declared in blocks
  // other than functions are pulled up and declared in the nearest scope.
  var i;
  var codeBefore;
  var codeAfter;
  var result;

  // So I assume your code was about looking for numbers between a certain set
  // of strings. It's a repetetive task, we'll use an array to store these set
  // of strings and a loop that accesses them using an index.
  var wrappers = [
    ['
About ', ' results<'],
    ['
', ' result<'],
    ['
', ' results<']
    //add more wrappers if you want
  ];

  var wrappersLength = wrappers.length;

  // Make the request
  var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl);
  var sourceCode = UrlFetchApp.fetch(request).getContentText();

  Utilities.sleep(1000);

  // Then loop through each of the wrappers and testing them
  for (i = 0; i < wrappersLength; ++i) {

    // Get the codeBefore and codeAfter from an entry in the array
    codeBefore = wrappers[i][0];
    codeAfter = wrappers[i][1];

    // Parse
    result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(",", "");

    // Then check if the number is not NaN and if so, return which effectively
    // make the code break out of the loop and of the function as well.
    if (!isNaN(result)) return result;
    else return "0";
  }
}

When free of comments, it's just this short:

function indexedpages(myUrl) {
  var i;
  var codeBefore;
  var codeAfter;
  var result;
  var wrappers = [
    ['
About ', ' results<'],
    ['
', ' result<'],
    ['
', ' results<']
  ];
  var wrappersLength = wrappers.length;
  var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl);
  var sourceCode = UrlFetchApp.fetch(request).getContentText();
  Utilities.sleep(1000);
  for (i = 0; i < wrappersLength; ++i) {
    codeBefore = wrappers[i][0];
    codeAfter = wrappers[i][1];
    result = sourceCode.substring(sourceCode.indexOf(codeBefore) + codeBefore.length, sourceCode.indexOf(codeAfter)).replace(",", "");
    if (!isNaN(result)) return result;
    else return "0"
  }
}


Some quick comments. Since your request is about readability, you can do three things at least:

get rid of unused variables eg: start = datetime.now()
improve the naming conventions for your variables: variables like cont or conti are quite similar (risk of typos/confusion) but the names are not intuitive and do not accurately describe the data you are manipulating. count is also too generic to be meaningful. Note that game_date looks confusingly similar to game_data and you even have a line: game_data.date.append(game_date). I think the risk of typo bugs is not negligible here.
add some line spacing here and there, plus a few comments. You can afford it as the code is less than 100 lines of code, so the implementation is reasonable and not bloated.

I don't think the class GameData is really useful the way it is implemented. To get the final printable result you could stick with a dataframe, you already have one, so see if it can be transformed further or transposed to another.
You have time.sleep after pd.read_html, but it does not guarantee that the page will be fully loaded. There are several functions in Selenium that you can use to wait for the presence of a given element. But probably you could use the requests module instead. On sites that use JS/Ajax, you may have no other choice but to use Selenium, but it takes more effort to do it right.
It would be good to add some validation to make sure that the result of your scraping is not void. Otherwise the processing will be wrong and return garbage. The BS find function will return None if the element is not found. So all you have to do is something like:
if None in (cont, conti, content, main):

or you can use the any function for this purpose.
However, findAll has a different behavior and will return an empty list if there is no matching element found.


You have a function called input_guess().  That function inputs the guess, compares the guess, and plays the entire game.  It should only input the guess.  I would create a function to run the program, one to input the number, and one to do the comparison and output prompts about being too large or small.  This way, only the function that plays the game needs to know the number of moves left.  Once the number is correctly guessed, that function just returns to its caller, who can call it again if the user wants to play again.  Also, try not to write functions this long.

As for your range100() and range1000() functions, I would combine those into one function like this:

def get_num(min, max):
    print "New game. Range is from " + min + " to " + max
    num = random.randrange(min, max + 1)
    return num

You can tell the user how many guesses they have left in the function that controls the game.

Finally, you should have the part of the program that always runs in an if __name__ == "__main__": block.  This is for re-usability of your program, and you can read more about it here: What does if __name__ == “__main__”: do?.


Personally I like the style (especially the nice clear function and variable names). As its quicksort most of the code is straightforward enough that comments would probably only add meaning when it comes to the swapping. You should probably try and use four spaces, rather than tabs, for indenting the code (it's just common practice). The only minor stylistic change I would personally make is to uncapitalise PIVOT_INDEX. I know technically it is constant (in that it doesn't change value after it's assigned), but I just prefer to have one clear assignment for any constant values. However, I'm sure other people would disagree.

As for efficiency, you're always going to be bounded by the algorithm itsef, but there are a couple changes you could make. You calculate len(lst) multiple times in partition. Rather than doing that, you could just assign it like list_length = len(lst) once at the start of the partition function. Not a big deal I know. The only other meaningful change I can think of is in your get_median function. As you know that it's always called with three values you could change it to:

def get_median(nums):
    values = sorted(nums)
    return values[1]

If you really want to be fancy you can replace the get_median and the whole if-then-else construct that determines the PIVOT_INDEX with something like:

PIVOT_INDEX = sorted(zip([lst[0], lst[middle], lst[list_length - 1]], [0, middle, list_length]))[1][1]

which will give you the index (0, middle or list_length) of the median value in the same way.


Use an enum instead of #define. So instead of:

#define option_1 1
#define option_2 2
#define option_3 3
#define option_4 4

You can use enum:

enum {F_to_C, C_to_F, Off} option_type; // I am leaving off the fourth option!

You will also have to modify other portions of your code to use enums.

Stop using so many if statements. Use switch-case statements instead. There are a few places that you do this in your code but for example:

if (option == option_1)
    printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));

else if (option == option_2)
    printf("Celsius to Farenheight of %.1f F is: %.1f F\n", input_temp, C_to_F(input_temp));

else if (option == option_3)
    printf("Calculator OFF\n");

else if (option == option_4)
    printf("Invalid option choice, please try again...\nOption: ");

Instead:

switch(option) {
    case F_to_C:
        printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));
        break;
     ...
     default:
         printf("Invalid option choice, please try again...\nOption: ");
         break;

Notice that we have a default. You can give garbage as option_4, more than just the value 4. You should try handling this best you can.

Don't use _Bool! Just use bool and use true and false instead of 1 and 0. So this:

_Bool calc_off = 0;

Should be:

bool calc_off = false;

But actually I don't really believe you need calc_off because you use pointers unnecessarily.

This:

int option = 0;
float input_temp = 0.0f;
_Bool calc_off = 0;

while (!calc_off)

{
    get_input(&calc_off, &option, &input_temp);

    if (option == option_1) /*F to C*/ // Rewrite this to use switch case!
    {
        display_result(option_1, input_temp);
    }
    else if (option == option_2) /*C to F*/
    {
        display_result(option_2, input_temp);
    }
}

get_input in particular is troublesome.

Why not let get_input return an option? then:

while((option = get_input(...)) != Off) {


Parse a string as a list of words and parse characters

The documentation for re.split says:

  If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

For example:

>>> import re
>>> re.split('( )', 'hello world')
['hello', ' ', 'world']

If the string starts or ends with a separator, you get an empty string:

>>> re.split('( )', ' a b c ')
['', ' ', 'a', ' ', 'b', ' ', 'c', ' ', '']

You probably don't want these empty strings, so you should filter them out:

>>> [w for w in re.split('( )', ' a b c ') if w]
[' ', 'a', ' ', 'b', ' ', 'c', ' ']

So your parse_chars function would become:

[w for w in re.split('([^0-9A-Za-z])', string) if w]

For example:

>>> [w for w in re.split('([^0-9A-Za-z])', '10 green bottles!') if w]
['10', ' ', 'green', ' ', 'bottles', '!']


Converting from Roman numerals to Arabic numbers

Impressions

That's a very long solution.  The comments were generally helpful, but the code itself could have been easier to understand if it were shorter and more expressive.

The variable names were generally not helpful: l, i, t, c, li were all cryptic.

get_arabic_numbers(t) is not really named appropriately:

"get" implies retrieving something that already exists.  This is more of a calculation.
Why is "numbers" plural?
Why is the parameter named t — what does it stand for?
Strictly speaking, the result is an int.  It's not Arabic, nor is it even in base ten.  It's just an abstract integer, which is conventionally rendered for you as base-ten Arabic digits when str() is called on it (whether explicitly or implicitly).  (And by "Arabic", we mean 0123456789, not ٠١٢٣٤٥٦٧٨٩.)

Based on these concerns, I'd call it decode_roman_numeral(roman).  It happens to be what you wrote as the comment!  Similarly, I'd call the inverse function encode_roman_numeral(num).

Arabic → Roman

# The format
format = 0

That's not what I would call a "format" — I would call it a "result".

# Hold the numbers in the list
l = list()
…

# Convert from roman numeral to arabic number
for i in range(0, len(t)):
    if t[i] == 'I':
        l.append(int(1))
    elif t[i] == 'V':
        l.append(int(5))
    elif t[i] == 'X':
        l.append(int(10))
    elif t[i] == 'L':
        l.append(int(50))
    elif t[i] == 'C':
        l.append(int(100))
    elif t[i] == 'D':
        l.append(int(500))
    elif t[i] == 'M':
        l.append(int(1000))

As I mentioned before, l is a cryptic name.  There is no need to convert 1 to int(1).  Lookups are typically done in Python using a dictionary.  Also, whenever you populate a list by creating an empty list and appending to it repeatedly, that is a good candidate for a list comprehension:

trans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
values = [trans[r] for r in roman]

# Calculate the format as follows:
i = 0
while i < len(l) - 1:
    # If the next numeral is greater than the current one, add the next one minus the current one = format = format + next_numeral - current_numeral
    if l[i] < l[i+1]:
        format = format + l[i+1] - l[i];
        i = i + 2
    # Else add it normally
    else:
        format = format + l[i]
        i = i + 1

Do you really need a case that advances i by two?  How about this instead:

result = 0
for i in range(0, len(l) - 1):
    if l[i] < l[i+1]:
        result -= l[i]
    else:
        result += l[i]

As I mentioned before, the code could be more expressive.  This loop is summing values in a list, so we should use the sum() built-in function to say what we mean.

result = sum(
    val if val >= next_val else -val
    for val, next_val in zip(values[:-1], values[1:])
)

All together, then, I'd condense your function down to this:

def decode_roman_numeral(roman):
    """Calculate the numeric value of a Roman numeral (in capital letters)"""
    trans = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    values = [trans[r] for r in roman]
    return sum(
        val if val >= next_val else -val
        for val, next_val in zip(values[:-1], values[1:])
    ) + values[-1]

Arabic → Roman

The encode() function encodes a single Arabic digit, so encode_digit() would be a better name.  There is no point in passing l and c separately, since you only ever care about l[c].  Instead of looping to append characters to format, use the * operator to construct a repeated string.

I would write this helper function using a single expression with four cases:

def encode_digit(digit, one, five, nine):
    return (
        nine                     if digit == 9 else
        five + one * (digit - 5) if digit >= 5 else
        one + five               if digit == 4 else
        one * digit
    )

The get_roman_numerals() function is rather convoluted.  I had a hard time following the code, so I went by your comments instead.  In the end, I figured out that it was essentially doing this:

def encode_roman_numeral(num):
    num = int(num)
    return (
        'M' * (num // 1000) +
        encode_digit((num // 100) % 10, 'C', 'D', 'CM') +
        encode_digit((num //  10) % 10, 'X', 'L', 'XC') +
        encode_digit( num         % 10, 'I', 'V', 'IX')
    )


The UpdateNames event should be TeamChanged or something, so that it tells the presenter what happened on the view, as opposed to what the presenter should be doing; "update names" sounds more like a method name than an event, too.

The presenter shouldn't know about any form controls: the view knows about the model - there's no need to round-trip to the presenter to update the list of names, IMO that's pure presentation logic that should remain encapsulated in the view.

The IsValid logic could be used to keep the OK button disabled until the model is in a valid state; that way you wouldn't need that MsgBox, as the user wouldn't even be able to attempt to submit incomplete/invalid data.


Making the objectContext.CommandTimeout configurable?

I do not like the name myDAL as a class name.  It is very cryptic and does not follow C# naming conventions.  I would prefer DataAccessLayer or <entity>DataAccessLayer where <entity> is the name of the class the DAL is for.

That being said, why don't you inject the timeout value into your DAL class.  The constructor could be something like

public void myDAL(int timeout)
{
    if (timeout > 0)
    {
         ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = timeout;
    }

    // other constructor commands
}


Just a few things to point out.

There is a prelude function print that is defined print = putStrLn . show.

Additionally, using "do-notation" in this case is unnecessary as you aren't sequencing multiple IO actions.

main can be rewritten in a more point-free style using the function composition operator:

main = print . sum . filter odd . takeWhile (< 4000000) $ fibonacci

I might rewrite fibonacci like this (removes nested where clauses):

fibonacci :: [Int]
fibonacci = next 1 1
  where next x y = x : next y (x + y)

And here are a bunch of other ways to define fibonacci. One interesting way that is possible because of Haskell's laziness:

fibonacci = 1 : 1 : zipWith (+) fibonacci (tail fibonacci)


Splitting a text file into paragraphs and words

So there's a lot going on here -  a lot more than there needs to be. You're working way too hard for what is actually very simple.

A few notes: I can't review code that hasn't been written. You're saying you want the "article number", but I don't see code for anything like that, so I'll ignore that bit for now. Similarly, you talk about "a number of files" but all your current code has hard-coded file names (that are different from code block to code block), so I'll leave that alone too. That leaves finding paragraphs and the words in those paragraphs.

First, though, here are some of the things I noticed in your code:

Your code keeps doing the same things over and over. You open, read, and split the target file into paragraphs again and again. And in different ways.
A lot of code is never used for anything, or made entirely redundant by later code. E.g. you read all the lines in the file... and then don't use that for anything before joining all the lines into a single string again. And then you split it again, only differently. And then you read everything again a moment later...
You open the "output.txt" file for writing, but you never use it for anything. Nor do you close it again. I'd suggest just printing to stdout (i.e. puts) and then you can use I/O redirection in the shell to dump that into a file.

In all, there are problems, a lot of which, quite frankly, seem to suggest you don't understand your current code.

Here's a detailed look at your last code block

# Why use readlines when you don't need the actual lines?
lines = File.readlines("test.txt")

# Never used for anything
line_count = lines.size

# File.readlines + join is the same as just using File.read
text = lines.join

# Now you're re-splitting the text you just joined
paragraph_count = text.split("\.\r").length

# ... just so you can print this, which the next bit
# of code can do too, since it also splits the text
# into paragraphs
puts "#{paragraph_count} paragraphs."

# So all of the code above can safely be replaced with:
# Nothing (just delete it)

# When you use Array.new with a length and an object,
# that object is *repeated* - not cloned - across the
# array. So each index in the array points to the
# exact same object.
# This would likely lead to a bug (except that your
# next bit of code makes all of this redundant)
# Also, Ruby convention is to use underscores, so
# "test_array", not "testArray". Of course, that name
# is bad to begin with because it doesn't give you any
# hints about what it contains.
testArray = Array.new(paragraph_count.to_i, Hash.new)

# You never need to use a basic for loop in Ruby, ever.
# Want you want is Enumerable#map, or - better yet -
# use a block initializer in the first place to populate
# the array
for i in 0...paragraph_count.to_i do
    # So here, you overwrite each index, making the
    # the above array initialization pointless
    testArray[i] = Hash.new
end

# Elsewhere in your post, you just used `[]` to create
# a new, empty array. Why not do that here? It's the
# most common way of doing it.
words_in_each_paragraph = Array.new

# And now you open the file yet again, and split it
# into paragraphs. Didn't we just do all this?
File.foreach("test.txt", "\.\r") do |paragraph|

    # So you make a hash, and make each word a key in
    # that hash. Presumably because you only want unique
    # words. But that's what Array#uniq is for
    word_hash = {}
    paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
        h[w] = []
    }

    # Why do this? You can transform the structure for
    # testArray into words_in_each_paragraph, and back
    # again, as needed, rather than build two pretty
    # similar arrays.
    words_in_each_paragraph << word_hash
    testArray[i][:value] = word_hash
end

So yeah, there are issues.

Here's my take on practically all of your code: How to get an array, where each item is itself an array of unique words in the paragraph

# read file, split into paragraphs, and map each paragraph
# into its unique, constituent words
paragraphs = File.read("test.txt").split(/\s*?\r\s*/).map do |paragraph|
  paragraph.scan(/[[:alnum:]]+/).uniq
end

Done. That's all of it in 3 lines.

And it's more careful with its regexp patterns: It doesn't split at anything plus \r, and it'll include non-"word" characters in words, so it won't split non-English names for instance.


Removing all stopwords from a list of words

If stop is a list containing \$s\$ stopwords, and words is a list containing \$w\$ words, then the loop in the list comprehension will be \$O(w s)\$, since it basically has to iterate over both lists in a nested loop.

However, if you make the stopwords into a set…

stop = set(stopwords.words('english'))

… then each lookup can be done in \$O(1)\$ time.  You would get \$O(w)\$ running time just by changing the data structure like that.

Another minor issue is that by convention, Document should be lowercase, because it is a variable rather than a class.


I'm unclear how you are using dump = false and whether the method returns anything more than nil when params[:dump] is unassigned. If it doesn't, I would recommend the use of a guard clause:

def report
  return unless params[:dump]
  data = {}
  render :json => p(data)
end


Just a note about your comments, you don't need so many of them. Sometimes the name of functions are clear enough that anyone with a passing knowledge of the language/tools can follow it.

//tell the console what's happening
console.log("object sent to acc_datum is:");

//do the put request
return $http.put(putURL, obj).then(

Those are pretty self explanatory and taking up space, you could remove them.

Also it's better not to split a comment about 2 possiblities like this:

//on success do nothing
function(response){},
//on failure, get the data again
function(response){

They're part of one thought, combine them:

//on success do nothing, on failure get the data again
function(response){},
function(response){

This keeps your comments and code separated more cleanly.


HackerEarth: Find array index with cumulative sum till there matching a given target

With Java performance it is important to create methods other than the main method. Java compilation is method-based, and it often relates to how often the method is called. Since the main method is only called once, it is seldom optimized very well.

In addition to that, Java println is also slow, as it requires access to the console, and it is synchronizes, and flushes it. As a result, many println calls are also slower than fewer larger printlns. So, batch up your output as much as you can.

All in all, create methods, batch the output, and .... use a binary search. Then, use some useful Java native methods. Split is a good one, and also try-with-resources for the input streams. With the format of your input, a Scanner may be simpler too....

private static int[] readInts(Scanner scanner) {
    int size = scanner.nextInt();
    int[] values = new int[size];
    for (int i = 0; i < size; i++) {
        values[i] = scanner.nextInt();
    }
    return values;
}

private static void accumulateValues(int[] values) {
    for (int i = 1; i < values.length; i++) {
        values[i] += values[i - 1];
    }
}

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        int[] values = readInts(scanner);
        accumulateValues(values);
        int[] searches = readInts(scanner);
        int[] results = new int[searches.length];
        for (int i = 0; i < searches.length; i++) {
            results[i] = Arrays.binarySearch(values, searches[i]);
            if (results[i] < 0) {
                results[i] = -results[i] - 1;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int r : results) {
            sb.append(r).append("\n");
        }
        System.out.println(sb.toString());
    }
}


Process N lists simultaneously by doing permutations

Not sure why you're making it so hard on yourself. Why not just go through each of the 3 queues individually?

For the first queue, just go through it and make a new Node for each element. Add it to your result list.

For the other 2 queues, check if the index is already in the result list. If it is, add it to that node, otherwise create a new node.

EDIT it seems my point wasn't clear, so let me show you the difference:

public Map<String, List<Tuple3<Node, Node, Node>>> transform2() {
    Map<String, List<Tuple3<Node, Node, Node>>> result = new LinkedHashMap<>(estimateSize() / 3);

    for (Node node : xpn) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        result.get(node.getUniqueKey()).add(new Tuple3<Node, Node, Node>(node, null, null));
    }

    for (Node node : tu) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        List<Tuple3<Node, Node, Node>> tuples = result.get(node.getUniqueKey());
        boolean needNew = true;
        for (Tuple3<Node, Node, Node> tuple : tuples) {
            if (tuple._2() == null) {
                tuple.update2(node);
                needNew = false;
                break;
            }
        }
        if (needNew) {
            tuples.add(new Tuple3<>(null, node, null));
        }
    }

    for (Node node : efx) {
        if (!result.containsKey(node.getUniqueKey())) {
            result.put(node.getUniqueKey(), new LinkedList<>());
        }
        List<Tuple3<Node, Node, Node>> tuples = result.get(node.getUniqueKey());
        boolean needNew = true;
        for (Tuple3<Node, Node, Node> tuple : tuples) {
            if (tuple._3() == null) {
                tuple.update3(node);
                needNew = false;
                break;
            }
        }
        if (needNew) {
            tuples.add(new Tuple3<>(null, null, node));
        }
    }
    return result;
}

I personally find this a lot easier to understand than all your indirections and switches.

If you really don't want to have one big method you can also split it up like this:

public Map<String, List<Tuple3<Node, Node, Node>>> transform() {
    Map<String, List<Tuple3<Node, Node, Node>>> result = new LinkedHashMap<>(estimateSize() / 3);

    for (Node node : xpn) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._1()));
        tuple.update1(node);
    }

    for (Node node : tu) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._2()));
        tuple.update2(node);
    }

    for (Node node : efx) {
        Tuple3<Node, Node, Node> tuple = getTupleToModify(result, node.getUniqueKey(), (n -> null == n._3()));
        tuple.update3(node);
    }
    return result;
}

private Tuple3<Node, Node, Node> getTupleToModify(
        Map<String, List<Tuple3<Node, Node, Node>>> currentTuples,
        String key, Function<Tuple3<Node, Node, Node>,
        Boolean> filter) {

    if (!currentTuples.containsKey(key)) {
        currentTuples.put(key, new LinkedList<>());
    }

    List<Tuple3<Node, Node, Node>> list = currentTuples.get(key);
    for (Tuple3<Node, Node, Node> tuple : list) {
        if (filter.apply(tuple)) {
            return tuple;
        }
    }
    Tuple3<Node, Node, Node> result = new Tuple3<>(null, null, null);
    list.add(result);
    return result;
}


Well, you kind of have to have two arrays. You need your counts array and you need your output array. If you want to sort the input array in place, you can do that, that's just a completely different semantic for your algorithm. So you'll just need to figure that out up front: do you want to sort the input list (a la list.sort()) or do you want to return a new list that is sorted (a la sorted()).

That said, here's some comments on your initial solution. To start with:

counter, retVal = [0] * (Max + 1), []

There is no reason to do such a thing. That is unnecessary terse and you're just making it hard to see what's going on. Furthermore, you don't even need retVal for now. So let's just start with the counter by itself:

counter = [0] * (Max + 1)
for _ in Arr:
    counter[_] += 1

Next, we have this loop:

for i in xrange( Max + 1 ):
    retVal += [i] * counter[i]

You can actually do a little better in terms of code appearance. We have our counter array, which has all of those indices... what we want to do is iterate over the counter array while also having access to the indices. That's what enumerate() is for:

retVal = []
for i, count in enumerate(counter):
    retVal += [i] * count
return retVal

Lastly, if you want to follow PEP-8, your function name should really be counting_sort(). And _ should probably be replaced with some single-letter name (x, a, elem, what have you).


Find the longest sub string of a word after concatenation of given words array

Think of encapsulation and responsibilities

The main method parses the input and uses this piece of code to compute and print the answer:

findCombi(arr, N, "", new HashMap<Integer, Boolean>());

System.out.println(max);

This is ugly in many ways:

Where does the value of max come from? It's a global variable, its value gets set as a side effect of the call to findCombi. Try to organize code in a way to avoid side effects.
What are all those parameters passed to findCombi? They are low-level implementation details of findCombi. They should not be exposed outside that function. The main method shouldn't have to know how the solution is computed. It has the inputs (the array of words), it should pass just that to a function, and get an int back as the answer.
The parameter N is redundant, thanks to the .length field of arrays in Java.

This is what the snippet should have looked like:

int solution = findLongestSubstringCombination(arr);

There are no unnecessary parameters, and no side effects needed.


Simulation of Multiple Producer Consumer

The buffer is the resource. So it should take care about the access to itself by itself or another monitor. This monitor should not be the consumer nor the producer. So synchronization should NOT be located in the consumer or the producer.

If you want to omit effort (that will be technical debts) the first approach is to make the resource (in this case the Buffer) a monitor by introducing synchronized as the keyword in the method signatures of add() and remove(). size() and isEmpty() should not be available for clients, make them private. Now the buffer will be thread-safe.

To make use of wait and notify, you have to exactly know what is happening. wait() will suspend the current thread WITHIN a monitor.

A consumer-thread therefore may be suspended with wait() in the method remove() if nothing is in the buffer. A producer may be suspended in the method add() with wait() if he want wants to produce something but the cap is reached.

Both the consumer and the producer should notify all other suspended threads with notifyAll() after they changed the state of the resource. A simple notify() is not applicable here because in your current construct you do not distinguish between locks for consumers and locks for producers. After notifying the "notifiers" must leave the monitor by waiting or exiting the synchronized method (this will be maybe your solution).

A notified thread should first check, what has happend during its absence. So a consumer should check if something is in the buffer. If not then again wait(), consume() otherwise. A producer should check if the cap is reached. If not then produce(), wait() otherwise.

I see two further improvements:

First separate the locking responsibility from the resource. Introduce a "BufferMonitor" class for example delegating add() and remove() to the encapsulated real buffer and make its methods synchronized.

Second introduce additional locks for consumers and producers to be able to distinguish when to wake up one consumer or one producer. notifyAll() on the BufferMonitor will then become a notify() on the specific lock. Because I haven't implemented this scenario yet I do not know how much effort it is. After all it should be possible. But recognize: The BufferMonitor will not be obselete.

One sentence to the remove()-method. I suggest to somehow avoid returning -1 even it SEEMS to be impossible. A solution that does not need to return -1 is the most elegant one and I admit the most difficult. You may need something like a consumption announcement mechanism before calling "remove()". Maybe you take the challenge. But be careful: this is often called "developing gold taps". ;-)

Finally you should think about proper shutdown mechanisms of your threads. So waiting threads should be notified on shutdown and evaluate this shutdown request on their own.


A quick review, as the illustrious user34330 is no longer with us.

This:

if (val.type !== 'checkbox') {
    this.form[val.name] = val.value;
} else if (val.type === 'checkbox') {
    this.form[val.name] = val.checked;
}

should be

if (val.type !== 'checkbox') {
    this.form[val.name] = val.value;
} else
    this.form[val.name] = val.checked;
}

because if it is not not a checkbox, then... you know it is checkbox, you could also consider a ternary here:

this.form[val.name] = (val.type === 'checkbox') ? val.checked : val.value;

getObj should be getForm, since it returns the form
checkFullAM the name does not tell me what this does, due to a lack of comments I am mystified at what this function should do. <- That's bad
I would have expected to be able to pass a prefix to addURLPrefix, so that I could set https if I wanted to
setDomain seems to have no possible use, there are no comments to enlighten the reader why/how this could be useful


Mapping multiple values to an array object

What you have is fine. If you wanted to use a functional approach and avoid making coord be mutable you could use flatMap and map:

let indexes = 0...20
let coord = indexes.flatMap { (xVal:Int) -> [Coord] in
    indexes.map { (yVal:Int) -> Coord in
        Coord(x: xVal, y: yVal)
    }
}

If you are familiar with lambda expressions then you may know that this can be simplified to this:

let indexes = 0...20
let coord = indexes.flatMap { x in indexes.map { Coord(x: x, y: $0) } }

If all you are doing with Coord is storing coordinates, you may consider just using Tuples:

let coord = indexes.flatMap { xVal in indexes.map { yVal in (xVal, yVal) }}


Network MAC address conversion to IPv6 link-local address

Note that the purpose of the hex() function is to produce a hexadecimal integer literal (a string that can be used in Python source code), which is why it returns a hex value with the 0x prefix. Use the format() function instead, as it gives you much more control over the output.

For example, format(value, '012x') formats the integer value to a 12-digit hexadecimal (using lowercase digits), padding out the result to the minimum width with leading zeros as needed:

>>> mac_value = 0x237702d2ff9b
>>> format(mac_value, '012x')
'237702d2ff9b'
>>> format(42, '012x')
'00000000002a'

In this case, I'd actually split out the various bytes of the MAC address binary value that make up the IPv6 parts, and use str.format() to interpolate those into the IPv6 string.

def mac_to_ipv6_linklocal(mac):
    # Remove the most common delimiters; dots, dashes, etc.
    mac_value = int(mac.translate(None, ' .:-'), 16)

    # Split out the bytes that slot into the IPv6 address
    # XOR the most significant byte with 0x02, inverting the
    # Universal / Local bit
    high2 = mac_value >> 32 & 0xffff ^ 0x0200
    high1 = mac_value >> 24 & 0xff
    low1 = mac_value >> 16 & 0xff
    low2 = mac_value & 0xffff

    return 'fe80::{:04x}:{:02x}ff:fe{:02x}:{:04x}'.format(
        high2, high1, low1, low2)

I followed the PEP 8 whitespace recommendations to format the code here; whitespace around operators and after commas, for example.

In Python, we usually don't strive for shorter code; we aim for readable code. Sometimes you can express an algorithm in a very concise and readable way, but avoid code-golfing for the sake of compactness.

Python 3.3 added a ipaddress module; this module does not however include a utility to generate an IPv6 address from a given MAC address.


OBBs intersection improvement for AABBs-OBBs

Broad Phase collision detection

It looks like you are using this for what is called broad phase collision detection. This is the step in collision detection that is used to determine candidate pairs for the narrow phase that does the actual collision detection (Quick Summary)

As this is a bounding box text (especially if you are involving AABB) it looks like you're just trying to see whether to go through the actual intersection routing of the two shapes or not. If you can just stick with AABB in general, the math gets a lot easier and therefore faster. Also moving forward you can employ AABB-trees (they are space partinioning trees) to find all intersection candidates for one object with a tree query rather than a pairwise check.


I have to admit I didn't fully understood the algorithm. Anyway it seems suboptimal, due to use of heaviweight containers and a nested loops, and is really hard to follow.

I would rather start with an observation that replacing the array with its partial sums reduces the problem to finding two equal elements as distant as possible (two partial sums being equal means the sum in between is 0). This is pretty trivial:

Calculate partial sums (\$O(n)\$)
Stable sort (sum(i),i) tuples (\$O(n\log^2n\$))
Scan for largest equal range (\$O(n)\$)


A low hanging fruit first. You don't need to work through the entire powerset. Given that \$i_0 < i_1 < ... < i_k\$, and \$N = F_{i_0} + F_{i_1} + ... + F_{i_k}\$, how small \$F_{i_k}\$ could be?
Recall that \$F_0 + F_1 + ... + F_n = F_{n+2} - 2\$. As long as \$F_{n+2} - 2 < N\$, a representation is impossible, so the term \$F_n\$ cannot be the largest. Therefore, the largest term in the representation must satisfy both \$F_n \le N\$ and \$F_{n+2} - 2 \ge N\$. Since the Fibonacci numbers grow exponentially, this observation drastically reduces the choice of the largest term (one or two possibilities, depending on how \$N\$ compares to \$F_{n+1}\$).
That alone shall give you a boost.

Yet it is still bruteforcing. As you correctly say, there must be an underlying math.
I played with your program, printing the total number of representations for numbers between \$F_n\$ and \$F_{n+1}\$. The results are surprising:
Range     Total
3..4      3
5..7      5
8..12     11
13..20    21
21..33    43
34..54    85

Hmm... \$T_{n+1} = 2T_n - 1\$. Something to prove about, isn't it? Try. I don't want to spoil the fun.

For a proper review:

I don't see the reason for sumOfList, fibList, repWay, and rangerepWays being generators. yield only make sense if it breaks the natural control flow, while preserving some execution context. Those above have no context to preserve; they can safely return. Making them generators only adds overhead.
powerset is a different story. It yields in the midst of a (nested) loop.

Naming deserves some attention. It took me a while to understand what, say, repWays is supposed to accomplish. Along the same line, mostList is a list of the Fibonacci numbers, isn't it? - so name it accordingly.


Clarification on "if" statement - Digital Clock Tutorial C#

Welcome to Codereview. As I can see you are having troubles understanding the line that adds a "0" in front of hh. Let's say hh is 9. Then, as 9 is smaller than 10, time will be "09", if hh is "10", or greater, it won't add that "0" at the beginning. After that (time += ":"), the program will add a ":" which would represent the hours in the clock and a ":" character afterwards, like "10:" or "09:". So, When it adds the minutes, the algorithm will use a similar if statement, like this:

if (hh < 10) {
    time += "0" + hh;
}
else {
    time += hh;
}
time += ":";
if (mm < 10) {
    time += "0" + mm;
}
else {
    time += mm;
}

at the end the time that will be shown, will look something like "09:09", and such.


Clean way to remove an identical nested object in javascript

I think it can be simplified or solved differently.

That's good intuition. That's called a code smell. Something "smells" funny, off, or wrong but not sure what it is. Pay attention to that feeling!!

Unfortunately I can't get any further

This is an even stronger code smell.

do you have any ideas?

Re-examine the date object design.

date and IDs should be in one object
Put the date objects into an array. Array is designed for easy handling of multiple objects.
Using Array's provided methods should eliminate external variables and functions.

This code demonstrates overall structural changes after fixing the objects. Algorithm details not shown.
const dates = [
  { date : 'Sun Mar 07 2021',
     IDs : [ 1, 2 ]
  },
  { date : 'Sat Mar 06 2021',
     IDs : [ 1 ]
  }
]

const dupeDate = { date : 'Sun Mar 07 2021', IDs : [ 1 ] }

dates.forEach( date => {

  if( date.date === dupeDate.date ) return;

  if( date.IDs.includes( dupeDate.IDs[0] )) {
    // algorithm details here. Should be function calls as much as possible,
    // not dozens of lines of nested, nested code.
  }
});


Your current solution is actually pretty good, conceptually. There's nothing wrong with the start variable. I am not sure why you want to remove it. The loop is logically a good solution, but there's a better way than that, though (better because you can make the system do it for you....).

public int[] shiftLeft(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return nums;
    }
    int start = nums[0];
    System.arraycopy(nums, 1, nums, 0, nums.length - 1);
    nums[nums.length - 1] = start;
    return nums;
}

Note that, in addition to using System.arraycopy I also check to see that the input has valid values available....


I personally think that what you have done here by separating the layers is better than including this all in one layer....

You're following the Single Responsibility Principle - Business Logic and data retrieval results in two different reasons for change and therefore I believe separating them in different classes is following this principle
Your IUsersDAL can be stubbed in unit testing as this is injected into UsersProvider - you can separately test data access and business logic
Reusing GetUserByUserNamePassword in numerous other business provider's means you don't have to write the same query again therefore you're promoting code reuse.  Your UsersDAL is basically a repository pattern for the entity User as this will be used for storing the numerous LINQ queries associated with data retrieval for that entity.  Maybe think object having repositories for aggregate root objects only.
What if you changed your data retrieval for a User entity from a LINQ query to accessing them from a web service - you never know what might change in your application as it grows and you wouldn't want to be directly referencing web services in your business layer, accessing them through a Repository pattern would be a cleaner way of doing it.

I think developers sometimes doubt the extra layer due to the advantages of using an ORM and Linq as like you have done as you can create the data access retrieval within one query.

ORMs like Entity Framework are Unit Of Work and Repository patterns in themselves this is why having an extra layer to contain the query seems to be trivial, however I believe you're merely extending the repository as you're encapsulating data retrieval logic specific for an entity.


A comma.

$('table tr td:nth-child(' + rowNumber + '), table tr th:nth-child(' + rowNumber + ')').toggle();

jQuery's selectors are the same as CSS (with some stuff added here and there), so all the usual CSS selector rules apply:

$("div, h1")  // select div and h1 elements
$("div h1")   // select h1 elements that are nested somewhere within a div
$("div > h1") // select h1 elements that are direct descendants of a div

Etc.

By the way, rowNumber doesn't make sense; the code will select a given column, not a row.


Game of Life generation procession algorithm

Your algorithms looks correct, I could not find any obvious mistakes.

On the other hand, I have a suggestion towards the readability of your code:
Use more functions that tell the reader what you're doing right now. For example, instead of saying

if (grid[i][j] == 0) {
    if (neighbors == 3) {
        tempGrid[i][j] = 1;
    } else {
        tempGrid[i][j] = 0;
    }
}

you could write:

int cellIsDead(int x, int y) { return grid[i][j] == 0; }
int hasEnoughNeighboursToComeToLife(int x, int y) { return countNeighbors(x, y) == 3 }
void makeCellComeAlive(int x, int y) { tempGrid[i][j] = 1; }

if (cellisDead(i, j) && hasEnoughNeighboursToComeToLife(i, j)) {
    makeCellComeAlive(i, j);
}

Yes, this takes more time and also probably some global variables (although grid already looks global, so no issue), but it is a) easier to read (see how it almost reads like the rules of the game?) and b) easier to prove to be correct using unit tests. And any decent compiler will inline these function calls at compile time, so no runtime overhead.


Reach C++ policy-based common interface with different template parameters from one container

Few minor notes.

You have deliberately assigned -1 to represent undef, correct? The question whether you'll ever need to store -1 aside, you should probably define a named constant to get rid of magic number (it also helps when you decide to accept -1s). BTW, the minimal int (-2³¹ or so) is maybe a better alternative.
Every constructor and factory function accepts arguments by const ref. While acceptable for shared_ptr args, it makes sense to accept others (such as closures) by value and then move them inside the object's members.
const_cast is a threat to PolicyInterface's public push and pop methods.
VectorPolicy pushes elements to its right end but pops them on the left. If it should work as a LILO queue, std::deque is a better alternative to std::vector. Otherwise, VectorPolicy should follow stack (LIFO) idiom, and elements popped at the end.


Parse a file containing key-value pairs followed by coordinates of nodes in a graph

One problem we all know regarding speed is caching. A std::vector<T> has a nice property, namely that &vec[i] + 1 == &vec[i+1], e.g. the memory is continuous. So whenever you have a loop like

for(size_t i = 0; i < values.size(); ++i) {
    values[i] += 2;
}

the values values[i+1], values[i+2] … will already reside in your cache, and you don't have to access your main memory for those. However if you store only pointers in your vector<T>, ie.

std::vector <std::unique_ptr<Node>> nodes;

you lose that nice property, since we know have to access *vec[i], and &(*vec[i]) != &(*vec[i+1]). The above code becomes

for(size_t i = 0; i < values.size(); ++i) {
    *(values[i]) += 2;
}

and we really want to keep the number of * low. Luckily, unless you want to allow nodes[i] == nullptr for some i, there is no need to use a layer of indirection. Just use

std::vector <Node> nodes;

and create the Node at the end of your vector with std::vector<T>::emplace_back:

        while (file >> index >> x >> y) {
            nodes.emplace_back(index, x, y);
        }

Next, you usually don't want to use the whole namespace std. It's considered bad practice. And last but not least, you want to use variables as local as possible, to get rid of errors that are hard to debug (e.g. found_at should be declared/initialized in your if).

If we follow all of these points, we end up with

int dimension  = -1;
int best_known = -1;
std::vector <Node> nodes;

void read_file(const char *file_name) {

    std::ifstream file(file_name);

    if (file.fail()) {
        throw std::runtime_error("file failed to open");
    }

    std::string line;

    while (std::getline(file, line)) {

        if (line.find("BEST_KNOWN") != std::string::npos) {
            const auto found_at = line.find(':');

            if (found_at == std::string::npos) {
                throw std::runtime_error("line containing 'BEST_KNOWN' formatted not as expected");
            }

            best_known = std::stoi(line.substr(found_at + 1));

        } else if (line.find("DIMENSION") != std::string::npos) {
            const auto found_at = line.find(':');

            if (found_at == std::string::npos) {
                throw std::runtime_error("line containing 'DIMENSION' formatted not as expected");
            }

            dimension = std::stoi(line.substr(found_at + 1));

        } else if (line.find("NODE_COORD_SECTION") != std::string::npos) {
            break;
        }
    }

    if (dimension == -1 || best_known == -1) {
        throw std::runtime_error("dimension and best known result should have already been read");
    }

    unsigned index;
    double x, y;

    while (file >> index >> x >> y) {
        nodes.emplace_back(index, x, y);
    }

    file.close();
}

Note that I've moved the parse of the single node coordinates after the initial getline approach.

Concerning your additional questions: yes, exceptions provide a way to control your flow, but so would error return codes, e.g.

enum READ_ERROR { BEST_KNOWN_FORMAT, DIMENSION_FORMAT, BEST_DIM_NOT_READ, READ_OK };

....

    if (dimension == -1 || best_known == -1) {
        return BEST_DIM_NOT_READ;
    }

The choice is yours, but exception handling and stack unwinding is often a hassle. The compiler can use some optimizations if it knows that a certain part of your code will never throw. However, since we're using nodes.emplace_back, we're already using at least one function that can possibly throw.

Also note that you slightly violate the DRY principle in your line.find("DIMENSION") and line.find("BEST_KNOWN") lines, but another layer of indirection would make things slightly more confusing (for the reader).

Other than that, well done. Your code doesn't fall into other pitfalls that usually happen, e.g.

while(file >> index >> x >> y)

is exactly how you should handle formatted extraction with iostream.


It looks alright to me, although it seems odd having a young man of age 20 to equal an "elderly" man of age 30 :-).

I have 3 minor things:

1) One MemoryStream can be used to serialize all expressions:

  public Func<T, byte[]> Build(Func<byte[], byte[]> computeHash)
  {
    return obj =>
    {
      var binaryFormatter = new BinaryFormatter();
      using (var memory = new MemoryStream())
      {
        foreach (var t in _fingerprints.OrderBy(e => e.MemberName, StringComparer.OrdinalIgnoreCase))
        {
          var fingerprint = t.Fingerprint(obj);
          {
            binaryFormatter.Serialize(memory, fingerprint);
          }
        }

        return computeHash(memory.ToArray());
      }
    };
  }

2) The ToHexString() can be simplified like this:

  public static string ToHexString(this byte[] source)
  {
    if (source == null) throw new ArgumentNullException(nameof(source));

    return string.Join("", source.Select(ch => ch.ToString("X2")));
  }

3) FingerprintBuilder.Empty is an strange name. I would call it Builder or avoid the static instantiater.


Moving circles along a ray to eliminate location check

I had two thoughts. One was ... You really only need an angle and a distance. The distance is the amount you expand and the angle can be derived from the x/y coordinates.

http://jsfiddle.net/uLu7v/38/

first you calculate the angle:

var angle = Math.atan2(hoveredY - circleY, hoveredX - circleX);

Then you calculate the distance they move:

var topMove = ((expand /2 ) * Math.sin(angle)); // sin for Y
var leftMove = ((expand /2 ) * Math.cos(angle)); // cos for X

then use jQuery's built in animate +=:

$this.animate( {
    "left": "-=" + leftMove + "px",
    "top":  "-=" + topMove + "px"
}, 75 );

Tada!

Edit:- A couple of improvements in the code not supplied in the question:

In function inCircle() change the return statement to return (mouseDistance <= radius); Using the ternary operator to return a boolean? ... I'm sure it used to return some other values right?

In $( ".circle" ).click( :

if(!$( this ).data( "clicked" ) && inCircle( $( this ), event.pageX, event.pageY ) ) {

    $( this ).data( "clicked", true );
    setLocations( this, 200, event );

} else {

    resetLocations();
    $( this ).data( "clicked", false );

};

Makes it cleaner but not a real improvement otherwise, more of a preference.

In function setLocations() your circle parameter conflicts with the local circle variable. I would change the parameter to circleElement.


I'd imagine a $stmt->fetchAll() would be more performant than the while-loop and $stmt->fetch(). Rather than paging over an entire set of records one at a time, try returning the results from the database in-bulk. Your code is making a trip to the database with each iteration of your while loop. Your code will still look virtually identical:

$i = 0;
$r = $stmt->fetchAll();
foreach ($r as $data) {
    $array[$i] = array();
    foreach ($data as $k => $v) {
        $array[$i][$k] = $v;
    }
    $i++;
}

If you're using mysqli (native driver only), and not PDO's MySQL, you could do this:

$i = 0;
$r = $stmt->get_result();
$r = $r->fetchAll();
foreach ($r as $data) {
    $array[$i] = array();
    foreach ($data as $k => $v) {
        $array[$i][$k] = $v;
    }
    $i++;
}

You shouldn't worry about loops per se, but performance hits that you see, whether they come from loops or not. This is only possible if you're profiling your code.


Median-of-medians/quickselect filter in C

Major stuff

Consider const

Design: kth_largest() has a side effect of re-arranging array. this is surprising and not part of "Finds the kth largest element of an array in O(n) time."  I'd expect code to do the job without the side effect

// long kth_largest(size_t k, long *array, size_t n_elts) {
long kth_largest(size_t k, const long *array, size_t n_elts) {

Small size error

Code may call err(1, NULL); when n_elts < 5 as malloc(0) can return NULL.  I'd expect code to work for sizes 1 to 4 also.

Doubtful O() claim

"Finds the kth largest element of an array in O(n) time."    Perhaps when n >>> k, but not in general.  I'd expect O(n*k).  So perhaps

Finds the kth largest element of an array in O(n) time when k <<< n
otherwise O(n*k)

No error check

Do not trust user input follows the rules nor allocations always succeed.

long *array = malloc(n_elts * sizeof(long));
if (array == NULL) {
  Handle_Error();
}

for (size_t i = 0; i < n_elts; ++i) {
  // scanf("%ld", &array[i]);
  if (scanf("%ld", &array[i]) != 1) {
    Handle_Error();
  }
}

Minor stuff

object vs type

Rather than size to the type, size ot the object.  Easier to code right, review and maintain.

// qsort(a, n, sizeof(long), compare_longs);
qsort(a, n, sizeof *a, compare_longs);

// long *medians = malloc(n_sublists * sizeof(long));
long *medians = malloc(sizeof *medians * n_sublists);

No need for floating point math

i/2 will already have "floor" the quotient before the floor().  Absolutely no need for floor() and with its potential loss if precision for large i.

// return (size_t)(floor(i/2));
return i/2;

size_t is an unsigned type
Enable all warnings

pos >= 0 is always true below.  A well enabled compilers would have warned.

size_t pos = -1;
...
assert(pos >= 0);

Match specifier and type

"%zd" does not match a size_t.  "%zu" does.  Also implies useful warnings were not enabled.  Save time - enable warnings.  See also How to use “zd” specifier with printf()?/

// scanf("%zd", &k);
// scanf("%zd", &n_elts);
scanf("%zu", &k);
scanf("%zu", &n_elts);

Read until EOF

"I would read until EOF, but then I would have to deal with a growing array, I think." --> Yes, good idea.  Confident this is up to D. Ben Knoble abilities, so will not post code.

Design idea: pass the k as an argv[] and the array via stdin.


A more efficient way of extracting a name from a string?

Here's a simple Regex to pull out the CN value:

CN=([^,]*),

You can use this C# code to get the value:

string CN = Regex.Replace(input, @"CN=([^,]*),", "$1");

Here are the important points:

I'm assuming you want everything between the "CN=" and the next comma.
The Regex replace allows a special string in the last parameter.  The "$1" will be replaced with all of the characters in between the parentheses.
You can test out the Regex here https://regex101.com/r/dT8lP8/1

In terms of computational efficiency, your solution is most likely more efficient than this Regex solution.  You might see an improvement if you replace the second through fifth lines of your solution with this:

var StartIndex = Manager.IndexOf("=") + 1;
var EndIndex = Manager.IndexOf(",", StartIndex) - 1;

I'm using this overload of the IndexOf method that tells the code at what index to start looking for the comma.  This starts the search at index 3 ("J") instead of index 0 ("C").  Again, this might run a little faster, but probably not measurably so.


What would Bob do?

You've written an interactive program, but the user does not know what your program does. Therefore, Bob—the generic user—might accidentally write "test" instead of a number, and suddenly your program runs wild.

A first step in the right direction would be to tell the user what your program will do—as long as its interactive. Note that this is not C++ specific.

We can do so by starting with:

cout << "This program converts a binary number to a decimal one\n"
        "Please state the length of your number: ";

But that's error prone. First of all, Bob might not know how long the binary number is. Try to check whether 1101011010101101 is 14 or 15 characters long. That's a trick question, those are 16 characters.

So instead, just let Bob write anything and then check how long it is and whether it was really a binary number.

Prefer std::string to char[N]

Instead of char binary[i], we will use a std::string binary. This makes the input a lot easier. However, to handle the input easier, let's write a function. Actually, let's write two:

bool is_binary_number(const std::string& binary){
    return std::all_of(binary.begin(), binary.end(), [](char c){
        return c == '0' || c == '1';
    });
}

That's using C++11's all_of in combination with a lambda. In case you don't know that yet, here's the same variant written in a range-based for loop:

bool is_binary_number(const std::string& binary){
    for(char c : binary) {
        if(c != '0' && c != '1') {
            return false;
        }
    }
    return true;
}

But this is C++11 syntax. In case you're not familar with C++11 at all, it's almost the same as

bool is_binary_number(const std::string& binary){
    for(size_t i = 0; i < binary.size(); ++i) {
        if(binary[i] != '0' && binary[i] != '1') {
            return false;
        }
    }
    return true;
}

In case you don't know std::string & yet, that's a reference. A reference is an alias to an already existing object. A const reference is an alias where we cannot change the value:

int        value = 15;
int&       ref   = value;
const int& cref  = value;

ref = 12;

std::cout << value << std::endl; // prints 12, since we changed it via ref
std::cout << cref  << std::endl; // prints 12, since we changed it via ref

// does not compile:
cref = 7;           // error; this reference is read only!

The details are a little bit more complicated, but in the end, when we call is_binary_number(on_a_string), we won't make a copy of on_a_string.

Either way, now that we have a function to check whether a string is a binary number, we can write our function to ask Bob for input:

std::string ask_binary_number() {
    std::cout << "Please enter a binary number: ";

    while(true) {
        std::string input;
        std::cin >> input;

        if(is_binary_number(input)) {
            return input;
        } else {
            std::cout << "That wasn't a binary number, try again: ";
        }
    }
}

We can now use this in main:

#include <iostream>
#include <string>        // necessary for std::string

int main () {
    std::string binary = ask_binary_number();

    ...
}

Note that we don't need to touch main at all if we want to change the input method later on. We only need to change ask_binary_number. This makes it easy to ask the user for another number, or re-use ask_binary_number in another project.

Exercise: Usually, you don't want leading zeroes in binary numbers. Which function do you have to change to not allow leading zeroes in the result of ask_binary_number? What changes are necessary?

Keep it simple and stupid

In your for loop, you do two things at once: you print the binary number and convert the number to a decimal. Unless you know that this is a bottleneck in your program and you need cache locality or something similar to keep your code fast, do one thing and one thing only. This makes it a lot easier to change the code later without breaking something else.

We can split this functionality again into two functions:

void print_binary_with_spaces(const std::string & binary, size_t digits = 4){
    // exercise; almost solved by your own code
}

unsigned long binary_to_decimal(const std::string & binary){
    // exercise; almost solved by your own code
}

If you implement all functions given above, you end up with the following main:

#include <iostream>
#include <string>

// functions here (either completely or only their declaration)

int main() {
    std::cout << "This program converts a binary number to a decimal one." << std::endl;
    std::string binary = ask_binary_number();

    std::cout << "Your binary number ";

    print_binary_with_spaces(binary);

    std::cout << " is " << binary_to_decimal(binary) << "in decimal"
              << std::endl;
}

Note that all complex interactions are moved into functions. However, as you have seen in ask_binary_number and is_binary_number those functions aren't complex themselves either. Keeping things simple is a principle (KISS) that's often applied, as is splitting the functionality (separation of concerns).

A concrete example of overly complex code

Why am I pointing to simplicity? Because your while loop is overly complex:

i = i * 2;
j = 1;
while (i)
{
    if (i > j)
    {
       ...            // lets call this A
       ++j;
    }
    else
    {
        ...          // lets call this B
    }
    --i;
}

Essentially, you have the following loops:

for(j = 0; j < i; ++j)
{
    A; // see above
}

for(--i; i > 0; --i)
{
    B; // see above
}

If we used that in your program, it would look like this:

for(int j = 0; j < i; ++j){
    cin >> binary[j];
}

while(i-- > 0){
    cout << binary[i];
    if (i%4 == 1)
        cout << " ";
    if (binary[i] == '1')
        decimal += powerOfTwo;
    powerOfTwo *= 2;
}

This is not only easier to understand, it's even shorter. So try to keep your loops simple.


First, lets use inheritance. We will inherit the specific event types from the event interface.
interface Event {}

class EventType1 implements Event{}

class EventType2 implements Event{}

Secondly, lets define the type of functions that we will call in the handleEvent() method. In this case it is Consumer<Event>
Now our handleEvent() function will look like this
void handleEvent(Event event,
                 Consumer<Event> option1,
                 Consumer<Event> option2) {
   if (someCheck()) {
      option1.accept(event);
   } else {
       option2.accept(event);
   }
}

Now we can call this function and pass instance of event interface and two lambdas or method references
Handler.handleEvent(new EventType1(),
    event -> {
       //do something
    },
    event -> {
       //do something else;
    });
}


Best combination of a sum between two parameters in an array of objects

You're right that your solution wouldn't be the most accurate. If I'm understanding your question right, what you just described is the Multi-dimensional 0-1 knapsack problem (see the "Multi-dimensional knapsack problem" heading in this wikipedia page). Solving these kinds of problems is not easy for computers to do quickly, and the best algorithm to use can largely depend on the type of data you're expecting to receive.
Are there very, very few items you're ever going to work with? How important is speed? Can you get away with a simple brute-force method, and try every possibility?
How much does accuracy matter? Maybe the particular use case doesn't necessarily need the best answer, just a good enough answer. If so, the code you wrote would work just fine.
Otherwise, I would read up a bit on the knapsack problem, and try googling "Multi-dimensional 0-1 knapsack problem" (multidimensional because you are working with multiple limits, not just weight. 0-1 because you either use the item or you don't, you can't use 1/2 an item in a package). My quick searching showed that there's a number of technical articles out there that address this exact issue. Knowing the name of the algorithm you need should help with finding more resources on it :).


Bug

The only issue I see is that the data array is never expanded.

As a result any value of ptr that is not zero will cause undefined behavior. What you want to do is give a fixed but reasonable size for the data.

std::size_t const maxDataSize = 10000;

...

   std::vector<int> values;
   values.resize(maxDataSize);

Then make sure when you access the data you mod it to the correct range:

        case '>': ptr = (ptr + 1) % maxDataSize; break;
        case '<': ptr = (ptr - 1) % maxDataSize; break;

Comment

This is not a standard C++ header.

#include <bits/stdc++.h>

What you want is

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

Comment

The code is non modifiable so the the code parameter should be constant. I would also pass by const reference to prevent a copy or require a move operation to pass the code into the interpretor.

I can see how you would interpret the output as what is printed to the output stream by the interpreter as the result. But is not the whole of memory the actual output?

Two things I would do:

Make . output to the output stream (like , takes from the input stream.
I would give the bf_interpreter() two parameters. The code to execute and the data memory that can be used by the program. The data memory is passed by reference so that any changes can be inspected after the interpreter has finished.
Potentially I would even pass two streams (input/output) as parameters to bf_interpreter(). Though that is a bit more subjective.

Thus my function definition would be this:

 std::string bf_interpreter(std::string const& code,
                            std::vector<int>&  memory,
                            std::istream&      input = std::cin,
                            std::ostream&      output = std::cout
                           );

ReDesign

OK. So given there is a lot more state here than I really want to pass as a function. I would change this a bit and create a "Brain Fuck" class where all the important state is passed to the constructor then you can call interpret on the object.

class BF_Engine
{
         // Add Members here
         void nextStep() {
             // Add interpreter here
         }
    public:
         BF_Engine(std::string const& code,
                   std::vector<int>&  memory,
                   std::istream&      input = std::cin,
                   std::ostream&      output = std::cout
                  );

         void interpret(std::size_t steps = 1)
         {
             while (!finished && steps > 0) {
                 nextStep();
                 --steps;
             }
         }
         void interpretRun()
         {
             while (!finished) {
                 nextStep();
             }
         }
 };


The .NET framework will do this for you pretty cleanly with the right classes.

For example:

string url = "http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/";

DirectoryInfo di = new DirectoryInfo( new Uri(url).LocalPath );

The di.Name property contains "All Ends In Silence".


FileSystemWatcher with threaded FIFO processing

Files created in the folder seem to be cached FileSystemWatcher until the current file has finished processing.

Not really cached, FileSystemWatcher just raises its events one at a time. So, until your event handler returns, you won't get another notification. And since you execute all your code in that event handler, that can take a very long time.

The docs say this:

  To avoid missing events, follow these guidelines:

  […]
  Keep your event handling code as short as possible.

So you shouldn't do it this way.

  Do I need two threads?

If you want to make reasonably sure you won't miss anything, yes, you need (at least) two threads.

  Is ObservableCollection the best object to use to manage the list of files to process?

In the current state, ObservableCollection doesn't make much sense, because there is no list, you will only ever have one item in the collection.

If you switched to two (or more) threads, ObservableCollection is still not a great choice, since it's not thread-safe.

  Where do I put a second thread? I am guessing that I need a new thread each time a new file is added to the ObservableCollection but won't that trigger a thread for each file, then the log will be jumbled up with each file that is added to the collection?

If you wanted to process each file in parallel, you would need more threads. To keep the log clean (and to perform any other operations that are not thread-safe), you should use a lock.

In any case, you shouldn't directly use Threads. Instead, you should use Tasks, or some higher-level constructs (see below for more), since they are more efficient and easier to work with.

But if you don't need parallelism, a single processing thread (i.e. two threads in total) is enough and it also means you don't need any locks (assuming only this thread writes to the log).

Some specific options on how you could implement this:

Use ActionBlock from TPL Dataflow (requires .Net 4.5). This could be the simplest option, since it means you don't need to create any Threads or Tasks manually.

In the event handler, you would call Post(), and the work would be handled by the delegate that you passed to ActionBlock's constructor.

ActionBlock can also work in parallel, if you set its MaxDegreeOfParallelism.
Use BlockingCollection and a Task with a loop.

In the event handler, you would call Add(). You would then also create a Task (using Task.Run() or Task.Factory.StartNew()) with a foreach loop over GetConsumingEnumerable(), that process the files.

This will work best if there is only a single Task, which means it won't be parallel.
Create a separate Task for each file.

In the event handler, you would create a Task with a delegate that processes the file.

This way, files will be processed in parallel.


Eliminate duplication in similar fake data access classes

Why not use generics:

public class FakeDb<TList> : Dictionary<string, List<TList>>
{
    public const string Table1 = "Table1";

    public void AddToTable(string tableName, TList line)
    {
        if (!ContainsKey(tableName))
        {
            Add(tableName, new List<TList>());
        }

        List<TList> rows = GetTableData(tableName);
        rows.Add(line);
    }

    private List<TList> GetTableData(string tableName)
    {
        return this[tableName];
    }
}

Then to use:

var simpleDB = new FakeDb<string>();
var complexDb = new FakeDb<Dictionary<string, List<string>>>();


At the risk of nitpicking there's quite a fiew small/micro-optimizations that could be done:

group multiple var declarations using commas

var containerTop = container.offset().top, headerOrigin = header.offset().top;
chain method calls to the same object

header.before(placeholder).css('...')
group multiple calls to css() passing an object as the parameter:

header.css({ position: 'fixed', width: originalWidth + 'px'});


You should not use "magic numbers". Define a constant representing the size of the grid:

var GRID_SIZE = 3;

Generally new Array() can be shorted to [] (an empty literal array). Also it's not really necessary to give a length when initializing arrays, because JavaScript has dynamic arrays. Thus

var grid=new Array(3);
grid[0]=new Array(3);
grid[1]=new Array(3);
grid[2]=new Array(3);

can be shorted to

var grid = [];
grid[0] = [];
grid[1] = [];
grid[2] = [];

or by using a literal array even to

var grid = [ [], [], [] ];

This however skips the use if the GRID_SIZE constant. So you could instead integrate this with the loops filling the grid:

var grid = [];
for (var i = 0; i < GRID_SIZE; i++) {
  grid[i] = [];
  for (var j = 0; j < GRID_SIZE; j++) {
    grid[i][j] = 0;
  }
}

Your HTML table is unnecessary complex.

You don't need to encode the coordinates of the cells in the ID. You can get the coordinates (or find a cell based on coordinates) using the DOM (more about that later).

You don't need to give every single the same class. Instead give the table a class or identifier (e.g. tic-tac-toe) and style the cells using a descendant selector:

.tic-tac-toe td {
   /* ... */
}

Event handlers shouldn't be assigned using HTML attributes. And if you do, then you don't need to use javascript: in them. javascript: is only used in attributes that normally don't contain JavaScript, such as href, however you shouldn't be using that either. Event handlers should only be assigned using addEventListener.

Finally the non-breaking spaces are also unnecessary. To make sure that the empty cells are displayed use the CSS empty-cells: show.

This leaves us with:

When assigning the event handler it is not not necessary to assign each cell it's own handler. Instead assign the handler to a common parent element - in this case the table. The event object will contain a reference to the actually clicked element:

var table = document.getElementById("tic-tac-toe-1");
table.addEventListener("click", tableClick);

function tableClick(event) {
    var element = event.target;
    if (element && element.tagName === "TD") {
       var y = element.cellIndex;
       var x = element.parent.rowIndex;

       clickCell(element, x, y);
    }
}

Since you already have a reference to the clicked cell, you don't need to look for it in clickCell.

function clickCell(cell, x, y) {
  if (grid[x][y] > 0) {
    alert("Dont Try To Cheat Bud!!!!!");
  } else {
    if (currentPlayer == 1) {
      cell.className = "x";
      cell.innerHTML = "X";
      grid[x][y]=1;
      currentPlayer=2;
    } else {
      cell.className = "o";
      cell.innerHTML = "O";
      grid[x][y]=2;
      currentPlayer=1;
    }
  }
}

Also you shouldn't assign the colors to the elements. Instead define the colors in the CSS with classes.

.x { color: #3F88C5; }
.o { color: #E2C290; }

If you ever need to get an element from the coordinates, then you can use the DOM properties rows and cells:

var cell = table.rows[y].cells[x];

Some quick last things:

Identifying the current player using the numbers 1 and 2 is not good (magic numbers again). Find an alternative. Also: What happens, if the user doesn't enter 1 or 2 at the beginning?
The reset function basically has the same loop as the initialization. You should re-write both so that you can re-use the loop instead of having it twice in your code.
The grid variable isn't necessary. All information in it can be get directly from the HTML table.


Fine-grained synchronization to serve a file

Java's low level thread synchronization mechanism (synchronized blocks, volatile variables, wait(), notify(), etc) were proven to be tricky for the human single threaded mindset. Threading hazards like deadlock, thread starvation, and race conditions, which result from incorrect use of low level thread synchronization, are also hard to detect and debug.

To that end, Java 7 introduced several new features/classes in the java.util.concurrency package that allow developers to approach the thread synchronization domain from a high(er) level.  java.util.concurrent.locks.ReentrantLock is more flexible and gives more fine grain control over the scope of locking.  it also performs better.  The advice that I see around the web (including on Stack Overflow) is that ReentrantLock should replace synchronized block in all new code.