Initializing and populating a Python dictionary, key -> List

line.strip() does not modify the variable, it returns a modified string. But you can chain it together with the split. I would also jchoose a better variable name than rec. As J.F.Sebastian suggested in the comments, you could go with items:

for line in f:
    items = line.strip().split('\t')

Your code is the perfect place for a collections.defaultdict. You can give it a type which it will use when the key is not defined. It makes implementing a counter a lot easier (just pass it int, whose default constructor returns an int with value 0) or, give it list and it will give you an empty list:

from collections import defaultdict

value_dict = defaultdict(list)

with open("file.txt") as f:
    for line in f:
        items = line.strip().split('\t')
        key, value = items[0], items[5]
        value_dict[key].append(value)

I also added the with..as construct in there, in case you are not yet using it.

In python 3.x I would use the extended iterable unpacking:

key, *other_vals, value = line.strip().split('\t')


Does the code comply with the Java coding conventions?

I think it does comply quite well. A tiny thing is that it would be better to put a space between ){, for example in if (list.isEmpty()){. More importantly, it can be simplified.

There is no need for the inner list variable pointing to this.
The inner (non-static) class has direct access to the containing class' fields and methods: it can access firstNode directly from the containing list. So in this code:

final MyLinkedList<T> list = this;
return new Iterator<T>() {
    final Node<T> firstNode = list.firstNode;

You can drop both the list variable and the firstNode variable.

It's a minor thing, but currentNode can be private.

The hasNext method can be simplified by a lot:

@Override
public boolean hasNext() {
    if (list.isEmpty()) {
        return false;
    } else if (currentNode == null){
        return true;
    } else if (currentNode == list.lastNode){
        return false;
    }
    return true;
}

This is equivalent:

@Override
public boolean hasNext() {
    return !isEmpty() && currentNode != lastNode;
}

  Could this be made significantly faster?

Slightly. Notice that the isEmpty() check is pointless to perform for every iteration of a non-empty list. So as a minor optimization,
you could check for emptiness once, in the beginning,
and then omit all the isEmpty() checks from the rest of the code.

Suggested implementation

Putting it all together:

public Iterator<T> iterator() {
    if (isEmpty()) {
        return Collections.<T>emptyList().iterator();
    }
    return new Iterator<T>() {
        private Node<T> currentNode = null;

        @Override
        public boolean hasNext() {
            return currentNode != lastNode;
        }

        @Override
        public T next() {
            if (currentNode == null) {
                currentNode = firstNode;
                return currentNode.data;
            }
            if (currentNode.nextNode == null) {
                throw new NoSuchElementException();
            }
            currentNode = currentNode.nextNode;
            return currentNode.data;
        }
    };
}

Unit testing

I didn't just refactor aggressively. I wrote unit tests first to know that I'm not breaking anything. After that I could go ahead and refactor aggressively:

@Test
public void testEmpty() {
    MyLinkedList<Integer> list = new MyLinkedList<>();
    assertFalse(list.iterator().hasNext());
}

@Test(expected = NoSuchElementException.class)
public void throwIfNextOnEmpty() {
    MyLinkedList<Integer> list = new MyLinkedList<>();
    list.iterator().next();
}

@Test(expected = NoSuchElementException.class)
public void throwIfIterateBeyond() {
    MyLinkedList<Integer> list = new MyLinkedList<>();
    list.add(1);
    list.add(2);
    Iterator<Integer> iter = list.iterator();
    iter.next();
    iter.next();
    iter.next();
}

@Test
public void testStandardIteration() {
    MyLinkedList<Integer> list = new MyLinkedList<>();
    Integer[] items = { 12, 3, 4 };
    for (int i : items) {
        list.add(i);
    }
    Iterator<Integer> iter = list.iterator();
    for (Integer item : items) {
        assertTrue(iter.hasNext());
        assertEquals(item, iter.next());
    }
    assertFalse(iter.hasNext());
}

These may not be perfect, and might not cover all corner cases, but I hope they are enough to get you started.


Unit testing isn't something I do a whole lot of.  So as for a general review of what you've written, I can't attest much to that.

But as to the idea of creating a class category just to sorta-kinda exposed "private" methods for the sake of testing and testing only?  Well... let's talk about Objective-C, shall we?

Despite the way we talk about "methods", Objective-C doesn't really do... methods...  they're all messages which invoke underlying C functions.

In other languages, if you try to call a non-existent method, your code won't compile.  In Objective-C, you'll merely get a warning if the file you're in can't see the method you're trying to call, and if it really doesn't exist, you'll get a runtime crash.

But the fact remains that you can still compile the code and you can still pass the message to the object.  And if the object implements the method that matches the message, it will execute the code.

So even without the class category, we could still call the methods on the object--we'd just have a bunch of warnings.

And there's ways around the warnings as well.  This blog discusses this in more detail, but here's an example of doing this with one of your methods:

Given the method:

- (void)setMoodForTesting:(int)moodAmount;

We could invoke this method as such:

SEL mftSelector = NSSelectorForString(@"setMoodForTesting:");

((void (*) (id, SEL, float))objc_msgSend)(dwarf, mftSelector,1000);

It may also be worth looking into this blog entry for some information on cleaning this up and making it more reasonable to use.

In the end, this allows you to still test private details of the class, but these details aren't exposed anywhere to anyone.  If somehow you were to accidentally import this .m directly, you would then expose these private details and could accidentally use them somewhere.


Edge cases for simulated malloc function

Not sure if it's just a result from copy-and-pasting the code here but the code formatting needs improvement.

Inconsistent indentation
Inconsistent use of spaces
Random empty lines

Clearly formatted code is a lot easier to read, maintain and is less prone to contain bugs.
Naming is inconsistent as well, e.g. allocated_list vs freelist vs tempBlock.
There is no need to place braces around the return value like this: return(0);. It should simply be return 0;. return is not a function call.
In order to append blocks to the end of each of the lists you currently iterate to find the end. It would pay off to keep a tail pointer pointing to the last element of each of the lists which avoids that.
I think there is a bug when calling sfree on the last block allocated. Example:

First call to smalloc allocates a new struct block and assigns it to allocated_list

This means allocated_list->next == NULL.

Call to sfree

cur points to allocated_list
cur != NULL
But cur->next->addr is invalid because cur->next == NULL

I think the cleaning up is technically broken. When initializing the structure you perform a single call to mmap to obtain a set of mapped memory pages. However on clean up you munmap every single block allocated by the user of smalloc. As per munmap man page:

  The implementation  will require that addr be a multiple of the page size {PAGESIZE}.

This can't be guaranteed because the passed in addr is not aligned at all as it is purely dependent on what was allocated by the user.

However I suspect it "simply works" because the first call to munmap unmaps the entire space mapped in originally with mmap because that's what the first addr of freelist is. Nevertheless the implementation is incorrect and works by pure coincidence.
You should check the return values of malloc and munmap as well.
Multiple calls to mem_init will leak memory. While it would certainly count as user error detecting this and notifying the user is good defensive programming.


Count occurrences of an element in a list

Since your type a is required to be an Ord you can access Eq functions. This makes counting occurrences a bit simpler, because you can just filter and count the matching elements:

numTimesFound :: Ord a => a -> [a] -> Integer
numTimesFound _ [] = 0
numTimesFound x list = sum $ map (\a -> 1) $ filter (== x) list

Of course we don't need to stop there. We can use function composition and length to  write the last line as:

numTimesFound x xs = (length . filter (== x)) xs

In addition to that 200_success raises an interesting point in the comments:

  Actually, there is no reason to require Ord a, when Eq a will do


The indentation is inconsistent: the test class has its {} indented the same as the class declaration, but the main class has them indented one level more.

It's good that you've included a unit test, but it's only testing half of the functionality. What about the getter?

put and get as method names don't follow C# conventions, which would be Put and Get -- although it would be even more idiomatic here to make them an indexer. The original task is phrased in terms which are as language-agnostic as possible, but in an interview you should aim to show language knowledge where you have it as well as general knowledge and skill.

Is there any reason for hard-coding int as the type of the key and value rather than making them generic?

private List<KeyValuePair<int, int>> _orderList;

Two questions: firstly, why KeyValuePair<int, int>? I don't see anything which uses the value. Secondly, why include List in the name? The type says that already.

                _orderList.Remove(toRemove);

            var tempCacheCell = _orderList.FirstOrDefault(x=>x.Key == key);
            _orderList.Remove(tempCacheCell);
            _orderList.Add(tempCacheCell);

What's the asymptotic complexity of adding or fetching an element? It can certainly be improved. Hint: one approach would be to manually implement a different type of list. Alternative hint: there's some quite powerful collections in .Net Framework (I haven't checked which of them made it into .Net Standard).


Removing elements on a List while iterating through it

There are several ways to do this. Let's look at the alternatives:

Iterating over a copy, removing from original

This is a simple solution for the underlying problem of your first code: A ConcurrentModificationException is thrown because you iterate through the list and removing from it at the same time.

Easy solution is to create a copy of the list and iterate through that.

for (Integer integer : new ArrayList<>(nums)) {
    if (integer < 3) {
        nums.remove(integer);
    }
}

Down-sides of this approach:

Creates a copy of the original list, which requires memory and an operation which performance depends on the type of the list (ArrayList, LinkedList, etc.)
Additionally, nums.remove(value) is a \$O(n)\$ operation. Making this loop overall \$O(n^2)\$

Java 8 Streams

List<Integer> filteredList = nums.stream().filter(i -> i >= 3).collect(Collectors.toList());

Down-sides:

Does not actually modify the existing list, so if references to the list are spread around various variables, you still have some old elements that just shouldn't be in that list.
Creates various stream-related objects which might not be the most effective option.

On the up-side, this is among the fastest for bigger lists.

If you're not using Java 8:

List<Object> originalList;
List<Object> newList = new YourFavoriteListType<>();
for (Object obj : originalList) {
    if (shouldKeep(obj)) {
        newList.add(obj);
    }
}

Java 8 method

nums.removeIf(i -> i < 3);

Java 8 introduced the default method removeIf on the Collection interface. This allows different implementations to have implementation-specific performance-optimized implementations of this method.

Iterator.remove()

Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
    Integer integer = it.next();
    if (integer < 3) {
        it.remove();
    }
}

The only down-side of this approach is that you need to switch your for-each to a while. However, this approach is the most efficient one, especially for LinkedList where it is \$O(n)\$ (it's \$O(n^2)\$ for ArrayList because it has to copy array data on each remove(index) call). This is the approach I would recommend in most cases.

Note: Instead of using a while-loop it can also be written as:

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
    Integer integer = it.next();
    ...

Conclusion

If you want to mutate the existing list, removeIf is the solution I would go with. If you like functional programming and prefer a new list instead of mutating the existing one, then go with the list.stream().filter(...).collect(Collectors.toList()) approach.

See also

"When to use LinkedList over ArrayList?" on Stack Overflow


Is there anyway to use less if statements in my function?

You can use the ternary operation to reduce the vertical space, i.e. x = a if condition else b. This sets x to a if condition is true and to b otherwise.
You can also use a dictionary to map a string to some object, like
the_map = {'a': 4, 'b': 7, 'c': 43}`
x = the_map['c']

This will set x to 43.
Then you can evaluate everything in the initializer instead. So it's not less if checks per se, but it's a bit cleaner, and you can call generate multiple times without needing to do the checks.
import random
import string

class Password:
    def __init__(self, length, string_method, numbers=True, special_chars=False):
        self.length = length
        self.string_method = {
            'upper': string.ascii_uppercase,
            'lower': string.ascii_lowercase,
            'both':  string.ascii_letters
        }[string_method]
        self.numbers = string.digits if numbers else ''
        self.special_chars = string.punctuation if special_chars else ''

    def generate(self, iterations):
        characters = self.string_method + self.numbers + self.special_chars

        # Generating the password
        for p in range(iterations):
            output_password = ''
            for c in range(self.length):
                output_password += random.choice(characters)
            print(output_password)

# Test

password = Password(20, 'lower', True, False)
password.generate(3) # generate the random password 3 times

If you actually want less checks, then just pass in the characters directly. Passing in the length and which characters you want to use into password generator seems perfectly legitimate and straight-forward. This also allows you to do more complex things like generating a password with just vowels, without even numbers, or maybe if you want to exclude certain punctuation.
import random
import string

class Password:
    def __init__(self, length, characters):
        self.length = length
        self.characters = characters

    def generate(self, iterations):
        # Generating the password
        for p in range(iterations):
            output_password = ''
            for c in range(self.length):
                output_password += random.choice(self.characters)
            print(output_password)

# Test

password = Password(20, string.ascii_lowercase + string.digits)
password.generate(3) # generate the random password 3 times


Using Timer with Backgroundworker to ensure the doWork method is called

I needed something similar, in that I had code that was going to periodically check the database for new records and notify the user with baloon tips.  Checking the database every n-secs caused a pause in the UI that I didn't want the user to experience so I moved the procedure to a thread.

I had a System.Windows.Forms.Timer tick event, where the Thread was created something like (leaving out all the exception handling etc):

TIMER_TICK(object sender, EventArgs){
    Thread checkNow=new Thread(ProcessAutoCheck)
    checkNow.IsBackground=true;
    checkNow.Start();
    checkNow.Join(500);
}

Then in the ProcessAutoCheck method, I used the lock approach to prevent thread contention:

**lock**(lockObject){
{
....

The program worked as designed, and I didn't consume resources with threads.  It wasn't the fanciest solution.  I learned a lot from Threading in C# - By Joseph Albahari.  Complete book online.


Summing CSV files row by row using Node.js events

If you want to check whether every item in an array passes a test, you should use .every for that, not .reduce. Eg

data.reduce((acc, el) => acc && el.length > 0, true)

can be switched with

data.every(arr => arr.length)

and

data.reduce((acc, el) => acc && el[0] === null, true)

can be switched with

data.every(arr => arr[0] === null)

Also, when you want to transform one array into another, .map is the right method, not .reduce. Or, when you just want to copy an array exactly, use .slice() or spread it. Change

data.reduce((acc, el) => {
  acc.push(el.shift());
  return acc;
}, [])

to

[...data]

On a broader note, I would consider the logic to be a lot easier to follow if it was separated into two parts: one part to read the files and deal with the asynchronicity, and another part to (synchronously) combine into a single array. I think mixing the two and using eventEmitter makes things more difficult to understand than they need to be.

A somewhat minor issue is that you're requiring all rows of a particular index to be kept in memory until they've all been parsed. In the case that you're dealing with a large number of files, or the rows are large, it would be better to combine them as soon as possible, as they come in, so that the only persistent data structure is the output array of arrays (rather than an array of arrays for each separate .csv).

When any row is parsed, you can call a function that combines it with the results array. You can also map each parseStream to a Promise that resolves once its end event fires, and use Promise.all to log the final results array once all parsers are completed:

const result = [];
const combineRow = (row, rowIndex) => {
  const targetRow = result[rowIndex];
  if (!targetRow) {
    result[rowIndex] = row;
    return;
  }
  row.forEach((cell, cellIndex) => {
    targetRow[cellIndex] = (targetRow[cellIndex] || 0) + cell;
  });
}
const getRows = parser => new Promise((resolve, reject) => {
  let rowIndex = 0;
  parser.on('readable', () => {
    const row = parser.read();
    if (row) {
      combineRow(row.map(Number), rowIndex);
      rowIndex++;
    }
  });
  parser.on('end', resolve);
});

Promise.all(parsers.map(getRows))
  .then(() => {
    console.log(result);
  });

https://repl.it/repls/EnchantedElaborateFiber


The Best-practice threading policy in Java is now to use the ExecutorService implementations found in the java.util.concurrent package.
Before we go there, though, your current code should be improved. The method:

public static void stringAnalysis(ArrayList<String> strData) {
    Thread t;
    t = new Thread(new SentimentAnalysis(strData));
    t.start();
}

creates and starts a thread. The thread that is started is a regular thread, as opposed to a daemon thread. The JVM will exit when all threads complete, or all the remaining threads are Daemon (background) threads: see Thread.setDaemon(boolean).
You should typically use Daemon threads (and I believe that Java has a bug in that Daemon threads should be the default).
Additionally, there is no reason to 'Declare' the t Thread variable before assigning to it.
Finally, for many reasons, it is nice to give threads names.
I would have the code:
public static void stringAnalysis(ArrayList<String> strData) {
    Thread toRun = new Thread(new SentimentAnalysis(strData), "Sentiment Analysis thread");
    toRun.setDaemon(true);
    toRun.start();
}

But, in reality, I would use an Executor service....
Executors.
Executor services work best with Daemon threads too. Here's a method that creates a Daemon thread for an Executor service:
private static final AtomicInteger sentimentThreadID = new AtomicInteger();

public static Thread createSentimentThread(Runnable toRun) {
    String name = "Sentiment Thread " + sentimentThreadID.incrementAndGet();
    Thread myThread = new Thread(toRun, name);
    myThread.setDaemon(true);
    return myThread();
}

Executors have their own Runnable that they use to create the thread. When you have your runnable, you pass it to the Executor, and the Executor runs it on one of the Executor's threads.
So, you can create an ExecutorService with something like (using Java 8):
ExecutorService sentimentService = Executors.newCachedThreadPool(
        runnable -> createSentimentThread(runnable)
    );

Java 7 would be slightly longer with:
ThreadFactory factory = new ThreadFactory() {
   @Override
   public Thread newThread(Runnable r) {
     return createSentimentThread(r);
   }

};
ExecutorService sentimentService = Executors.newCachedThreadPool(factory);

Once you have the sentimentService, you can run your analysis Runnables with:
sentimentService.submit(new SentimentAnalysis(strData));


I'll focus on the void loop() part as you ask it, even though it can't be reviewed in isolation, especially from the evals structure.

So, what is this loop all about? You want to select the correct behavior based on the way the evaluated data has been tagged. Which mean we have three levers to act upon: the selection mechanism, the tagging mechanism, and the way the data is represented. I believe you can do better with all three:

tagging your data with a char* is a bad idea. The first important thing to note is that comparing a char* with a string literal is undefined behavior. It works with most compilers, but if you enable all warnings, as you should do, you'll see it isn't guaranteed by the standard. It means that you should rely on proper string comparisons instead, character by character -e.g with strcmp- which are of course slow, if you really want to keep the string-tagging. But you don't: there are faster, simpler and more robust mechanisms such as enums.

For instance:

enum class Type : char { NULL, INTEGER, FLOATING_PRECISION, STRING, BOOL };

Representing your data with a struct containing as many members as there are possible types is a waste of space you should care about. You can use unions to make it more compact.
Selecting the correct behavior can be made in several ways, the one you chose among them. But, not wandering very far, you could have used a switch, which is arguably easier to read and can be optimized by the compiler: the program will go through the if else clauses in succession, whereas a switch can be turned into a jump-table with logarithmic look-up. If you want to explore further, and have a more scalable selection mechanism, you could have a try at a virtual function.


Fetch entire table from database after validating the table name

When looking over your code I find several things I would do differently. I may seem harsh in my review, but I have no intention of making this a painful experience. If you have any questions feel free to ask. Without further ado, let's go!

The first thing which comes to my mind is the use of static methods. When working in an object oriented manner I rarely use static methods. When I use them though I ensure they follow this simple rule:

  Static methods should be entirely self contained. If a static methods depends on an instance, it has potential side-effects.

This is a personal rule :)

To me this means that static methods should be purely input -> process -> output methods. This also implies that no kind of persistence can be done as it would not be associated with the specific instance the static method is declared in. Even if an instance is provided through its argument list you cannot be sure any persistence wasn't done inside the instance. If you use an object inside the static method it should only exists within the method's scope.

A good example for a static method is when the logic is related. Consider normalization of class names before it's instantiated.

/*
 * An entirely self contained static method. The reason it is
 * declared inside the class is, because the functionality is
 * related to the class.
 */
public function normalizeClassname($classname)
{
    $basename  = ucfirst(basename($classname));
    $namespace = substr($classname, 0, -strlen($basename));

    return str_replace('/', '\\', $namespace) . $basename;
}

Preventing side-effects helps you avoid those moments when a bug has you wondering what the !@*? is going on? (More on this in the linked resource in the link "Global State and Singletons").

Your method depends on an instance of PDO. If you adhere to the rule above this cannot happen inside a static method and it should therefore be changed.

/*
 * The 'static' keyword has been removed.
 */
public function getTable($tablename = '') {...

Then looking over the argument list of the method I find it hard to understand why the table name can be omitted (has a default value)? If you don't provide a table name what is there to search for inside the database? I would change this into a required argument.

/*
 * The default argument value has been removed.
 */
public function getTable($tablename) {...

The next may be a little weird, but try to follow me. But first we need quote, everyone loves quotes!

  A method/function should do one thing and do it good.

  - Robert C. Martin

Both checking for a valid PDO instance and checking if provided table name exists violates this rule. Your method have 2 concerns as of now (there is actually one more, but more on that later). The issue can easily be solved with 2 possible solutions. Since a PDO instance cannot be created if invalid parameters are provided you can always assume any given PDO instance is valid.

The first solution: I assume an instance of PDO is required by your database class. This would be a perfect opportunity to use dependency injection inside a __construct() method. This removes the requirement of checking if a valid PDO instance was provided to your getTable() method as you can fetch the instance from a class property.

/*
 * Example of constructor injection.
 */
public function __construct(PDO $pdo)
{
    $this->pdo = $pdo;
}

The second solution: If you do want a __constructor() method or this is the only method to use a PDO instance, you could require the PDO instance in the argument list.

/*
 * Alternative to constructor injection. Argument injection!
 */
public function getTable(PDO $pdo, $tablename) {...

If you decide to follow one of the above solutions you have removed the unrelated concern of checking the validity of the PDO instance from your method.

You then make a white-list by fetching an array of tables inside the selected database and check if your provided table name exists in the array. After this you check if the table name is valid. Checking if the table name is valid should be done before the database query is issued (saving server resources). After all there's no use checking if a table exists when the provided table name is invalid.
I would also throw exceptions instead of emitting fatal errors. The end result would be the same, but you would have a nice backtrace with the exception.

Your method should now look like the following:

public function getTable($tablename)
{
    /*
     * I have fixed your regular expression since a delimiter was missing. I
     * have also simplified the expression to be case-insensitive (using the 'i' modifier) and
     * removed the comma since (as far as I know) isn't a valid table name character.
     */
    if(!preg_match('~[^a-z0-9$_]~i',$tablename)) {
        throw new UnexpectedValueException('The provided table name contains invalid characters.');
    }

    /*
     * Notice PDO is now fetched through an instance property and
     * is not static anymore.
     */
    $whitelist = $this->pdo->query('SHOW TABLES')->fetchAll(\PDO::Fetch_ASSOC);

    if(!in_array($tablename, $whitelist)){
        return false;
    }

    // Removed the ´else´ block as it was unnecessary.

    $tbl = self::$pdo->query('SELECT * FROM `'.$tablename.'`');
    return $tbl->fetchAll(PDO::FETCH_ASSOC);

}

I would then argue that fetching everything inside the table creates 2 new (major) issues. The first is that it's another concern. As I have understood the method validates that a table exists inside the database. Therefore it should't be concerned with fetching data from it. This could also imply renaming the method to validateTableName() or something like it.

The second being a performance risk. Imagine the provided table stores 1 million rows. Are you sure the database connection allows that long a connection? Does PHP have enough memory dedicated? Is the execution time increased for this (potentially) long running task? Are you aware this halts script execution as long as the query is being processed?

There are properly more concerns when fetching entire tables. I would urge you to consider simply returning TRUE and let other methods deal with fetching data.

If you still want to fetch data you should use a prepared statement instead of interpolating the table name directly into the query string. You may reason that it's always you who decides the table name, but using defense in depth is always better. Malicious users can unfortunately do some scary things.

If you agree with me this far your method should look like this:

/*
 * Changed method name to reflect is new intent.
 */
public function tableExists($tablename)
{
    if(!preg_match('~[^a-z0-9$_]~i',$tablename)) {
        throw new UnexpectedValueException('The provided table name contains invalid characters.');
    }

    $whitelist = $this->pdo->query('SHOW TABLES')->fetchAll(\PDO::Fetch_ASSOC);

    /*
     * Added strict comparison.
     */
    return in_array($tablename, $whitelist, true));
}

The method is now more concise and shows a clear purpose. The readability has also improved by giving more space between the lines. Remember that your code shouldn't be hard to read.

Bonus

Your original method emitted an error using the native trigger_error() function with the E_USER_ERROR flag. This is the same as an exception regarding functionality. But with exceptions you give your program a chance to recover. The calling code or a generic exception handler (set using set_exception_handler()) can then decide if anything can be done before the script fails with a fatal error.

Regarding concerns: I have mentioned this several times and I think this is one of the best things you can make a habit. I have several times when I found a bug  praised myself for separating logic into small pieces from the start. This makes correcting the bug easier as you know exactly where the logic in question is defined. This also helps readability when your functions/methods are concise.

The resources linked in this awesome answer on StackOverflow has helped me along the way. Especially the second link about Clean Code III: Functions about function/method concerns is relevant to this question.

Hope this helps, happy coding!


In is_charachter (which is misspelled; it should be is_character), you left out signed char (which is a distinct type from char). The same applies for all of the fixed width types (char8_t, char16_t, char32_t).

get_type returns some arbitrary magic number values.  You could create named constants to represent the type.  If you add a "unknown_type" value, then you wouldn't need to use std::optional.


Printing a table of letter frequencies using Python

The printing portion should be simplified:

The use of OrderedDict is superfluous.  A list of pairs would suffice.
I'd prefer to stick to the same iteration variable, when it is used to refer to the same thing.  Choose either c or l.
You are not using str.format() effectively.
(total if total > 0 else 1) could just be (total or 1).

for c, n in sorted(frequency.items()):
    print('{}:{:>8}{:9.2f}%'.format(c, n, 100 * n / (total or 1)))

As for the counting process itself, you could write c in frequency instead of c in frequency.keys().  But, really, the task is so naturally suited to a collections.Counter that it would be silly not to use it.

from collections import Counter as _Counter
from string import ascii_lowercase as _ascii_lowercase

text = 'StackExchange Code Review'
frequency = _Counter({c: 0 for c in _ascii_lowercase})
frequency.update(c for c in text.lower() if c in frequency)

total = sum(frequency.values())
print('\n'.join(
    '{}:{:>8}{:9.2f}%'.format(c, n, 100 * n / (total or 1))
    for c, n in sorted(frequency.items())
))

I think that the call to sorted() should be optional as of Python 3.6.


Design
Passing data with high and low works. But is equivalent to data+low and data+high. And just passing two values.
This is what is referred to as an Iterator range. If you look at the standard library you will see that a lot of the concepts hinge around iterators you should look that up and understand how it works.
Code Review
For every call to new there should be a call to delete.
    int* sorted = new int[size];

Or so the old text books tell us. In modern C++ you probably should never call new or delete (unless you know its a good idea).
But here you are leaking memory because you don't release it. You should add a delete [] sorted; to the end of the function.
BUT leaving the new/delete in your code is not a good idea. It's not exception safe to start with. So simply declare a vector<int> here and let it manage the memory for you.
We should also note that memory management is very expensive. So rather than doing this every loop. Why not do it once at the beginning and reuse the memory.
Sure this works:
    while(low_copy < mid && mid_copy < high) {
        if(data[low_copy] < data[mid_copy]) {
            sorted[i] = data[low_copy++];
        }
        else {
            sorted[i] = data[mid_copy++];
        }
        ++i;
    }

But we could simplify it:
     for(;low_copy < mid && mid_copy < high; ++i) {
        sorted[i] = (data[low_copy] < data[mid_copy])
                       ? data[low_copy++];
                       : data[mid_copy++];
    }

Also when you see loops like this you should look at the standard algorithms to see if there is one that will do all that work for you.
Another thing to note is that you are copying the value from data to sorted. This is fine for integers, but you should be able to sort nearly any C++ type and copying a C++ type is not usually the most efficient way to get the value from one location to another. You should look up the concept of moving. When the type being sorted is a bit more complex moving it (rather than copying is usually a better idea).
These loops can definitely be done by standard algorthims:
    while(low_copy < mid) {
        sorted[i++] = data[low_copy++];
    }
    // Or
    std::copy(data + low_copy, data + mid, sorted + i);
    // Or (when you move objects)
    std::move(data + low_copy, data + mid, sorted + i);

This is subject to overflow.
    int mid = (high + low) / 2;

Common mistake. If high and low are both large then this could easily overflow. Do the division fist (on the difference). Then add to the low.
    int mid = low + (high - low) / 2;

Are you sure there are 9 elements?
    int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
    int num_elements = 9;

Common source of errors. Don't manually do stuff the compiler can work out correctly. This is especially true if data is subsequently modified (and human person can make mistakes) does not change num_elements.
    int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
    int num_elements = sizeof(data)/sizeof(data[0]);

In more modern versions of C++ we even have a standard way of doing it:
    int num_elements = std::size(data);

No need for this in main:
    return 0;


Insert multiple rows without using CURSOR SQL Server 2014

From what I can tell based on the code you've presented, you can reduce it down to the following...

DECLARE @employeeid INT;

INSERT dbo.HRMS_PayrollInfo (PayrollFK, EmployeeIdFk, Eod_ReferenceFk, Amount, PaymentDate, Status, AlertActive, Entry_By, Entry_Date, Update_By, Update_Date)
SELECT
    26,
    @employeeid,
    er.Eod_RefFk,
    er.ActualAmount,
    GETDATE(),
    1,
    1,
    1,
    GETDATE(),
    1,
    GETDATE()
FROM
    dbo.HRMS_EodRecord er
    --JOIN dbo.HRMS_Employee e
    --  ON er.EmployeeId = e.ID
WHERE
    er.Status = 1
    AND er.EmployeeId = @employeeid;


Setting up radio button click ActionListeners

What GUI framework is this? Is the View v being passed to the OnClick method actually the clicked RadioButton? If so, here are some changes to consider

final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};

final OnClickListener onClickHandler =
    new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final RadioButton checkedButton = (RadioButton) v;
            for (final RadioButton button : buttons) {
                if (button != checkedButton) {
                    button.setChecked(false);
                }
            }
        }
    };

for (final RadioButton button : buttons) {
    button.setOnClickListener(onClickHandler);
}

If View v != the checked radio button, then:

final RadioButton[] buttons = {radio_books,radio_games,radio_dvds,radio_electronics};
for (final RadioButton thisButton: buttons) {
    thisButton.setOnClickListener(
        new OnClickListener() {
            @Override
            public void onClick(final View v) {
                for (final RadioButton button : buttons) {
                    if (button != thisButton) {
                        button.setChecked(false);
                    }
                }
            }
        }
    );
}


Your code isn't exactly terrible, but this is code-review, and good code review has to be harsh, so please keep in mind that I mean this in the nicest of ways.
That said, there are some issues I'd like to address:

Redundancies - DNRY:
That old dead horse: Do Not Repeat Yourself. You have a lot of redundant code. Of course, you can get into code-golfing, and try to write everything as a one-liner. That will result in unmaintainable code, and that's not what we want, but in your case, there is room for some minor improvements that won't harm readability one bit, quite the contrary.

You say you're getting the data (prices, I take it) from a PDO resultset, why, then, don't you fill the $flattenedListings array like so:

$flattenedListings = array();
while($row = $pdoResOrStmt->fetch(PDO::FETCH_ASSOC))
{
    $flattenedListings[] = $row['Price'];
}

That's going to reduce the resources your script requires a tad, and fetches the data while at the same time constructing the flattened array.
Next, the $isLast = count($widths); variable can be ditched all together, either by a simple foreach, very close to to the loop you currently have:

$widths = range(0, 100, 10);
$bins = array();
foreach($widths as $key => $val)
{
    if (!isset($widths[$key +1])) break;//break on the last key
    $bins[] = array(
        'min' => $val,
        'max' => $widths[$key + 1]
    );
}

But, and this might be personal, I dislike this if() break; thing in a loop. Personally, I'd probably write something like:

for($i=0, $j=count($widths) -1; $i<$j;++$i)
{//count -1 = last key, but $i <$j => next to last key
    $bins[] = array(
        'min' => $widths[$i],
        'max' => $widths[$i+1],//can get last key
    );
}

Next, the $histogram. You're using a closure function + array_filter to group your values according to the price range. In itself, it's quite easy to read, and not that inefficient. But I find that closures in PHP (which are objects, instances of Closure) are 9/10 overkill. They're also not a "natural" feature of the language. PHP isn't a functional language, like Lisp, Scheme or JavaScript are. I've compared them to drag queens: A man can wear a dress, stockings, a wig and put on make-up as much as he wants, it still doesn't change the fact that he's a man.
Often, what you end up with is a grotesque, bemusing performance that leaves some feeling ill at ease.

There is a far easier way of determining the range for each price:

$histogram = array();
foreach($flattenedListings as $price)
{//assuming nothing costs 0
    $key = floor(($price -1)/10);
    $range = $bins[$key];
    $key = $range['min'] .'-'. $range['max'];
    if (!isset($histogram[$key])) $histogram[$key] = array();
    $histogram[$key][] = $price;
}

If some price can be zero, then just replace:

$key = floor(($price -1)/10);

with

$key = $price ? floor(($price -1)/10) : 0;

And you're good to go.

Simplify:
Now we've got that sorted out, it's time to simplify things a bit. As you can see by the way I've filled $histogram, I don't actually need the min and max values from the $bins array, so instead of filling that array with array('min'=> $x, 'max'=> $x+1), I could easily have written:

$widths = range(0, 100, 10);
$bins = array();
foreach($widths as $key => $val)
{
    if (!isset($widths[$key + 1])) break;
    $bins[] = $val.'-'. ($widths[$key + 1]);
}

This also makes filling the $flotHistogram array a lot easier:

$flotHistogram = array_fill_keys($bins, 0);//set all keys to 0

Then, when filling the $histogram:

$histogram = array();
foreach($flattenedListings as $price)
{
    $key = $bins[floor(($price -1)/10)];
    if (!isset($histogram[$key])) $histogram[$key] = array();
    $flotHistogram[$key]++;//add 1 count
    $histogram[$key][] = $price;
}

This leaves us with the following code:

//get prices
$flattenedListings = array();
while($row = $pdoResOrStmt->fetch(PDO::FETCH_ASSOC))
{
    $flattenedListings[] = $row['Price'];
}
//construct range-keys array
$widths = range(0, 100, 10);
$bins = array();
foreach($widths as $key => $val)
{
    if (!isset($widths[$key + 1])) break;
    $bins[] = $val.'-'. ($widths[$key + 1]);
}
//construct flotHistogram count array
$flotHistogram = array_fill_keys($bins, 0);
//construct array of prices for each key
$histogram = array();
foreach($flattenedListings as $price)
{
    $key = $bins[floor(($price -1)/10)];
    if (!isset($histogram[$key])) $histogram[$key] = array();
    $flotHistogram[$key]++;
    $histogram[$key][] = $price;
}

A bridge too far(?)
I may be taking things a bit too far, but that $flattenedListings array seems a bit redundant, now. However I don't know what else you need the db results for, but all in all, you may want to consider doing something like

$widths = range(0, 100, 10);
$bins = array();
foreach($widths as $key => $val)
{
    if (!isset($widths[$key + 1])) break;
    $bins[] = $val.'-'. ($widths[$key + 1]);
}

$flotHistogram = array_fill_keys($bins, 0);

$histogram = array();
//query data:
while($row = $pdoVar->fetch(PDO::FETCH_ASSOC))
{
    $key = $bins[floor(($row['Price'] -1)/10)];
    if (!isset($histogram[$key])) $histogram[$key] = array();
    $flotHistogram[$key]++;
    $histogram[$key][] = $row['Price'];
}

Which reduces your code even more. Of course, if you find this too hard to read (imagine, a couple of months from now, will you still be able to make sense of this code), then don't use it, add more comments and don't feel shy to be a bit more verbose or repetitive.


Finding the percentage of even numbers in an array

Potential bug: What if the array contains a single element, and it is even?

if(a.length <= 1) {
    return 0.0;
}

That's what happens.

Easy fix, change to:

if(a.length == 0) {

Your indentation is slightly screwed up, but that might just be a copy-paste error.

double even should be int even.

You could use a for-each loop,

for (int i : a) {
    if(i % 2 == 0) {

int[] a could be named int[] array or int[] values or int[] input.

When using even as an int, use the following return statement to cast only even to a double, which will then make it use double division and not int division:

return (double) even / a.length * 100;

Alternatively you could use:

return even * 100.0 / a.length;

But I think return (double) even / a.length * 100; is better.


How Long Will Your Smartphone Distract You From Family Dinner?

There's definitely an issue that will occur when a new task comes up with the same amount of time as what is left on the other person's task. Take for example the times.

MyTime | HerTime
----------------
3      | 5

Now the first loop occurs, HerTime gets reduced to 2, TotalTime gets set to 3, then MyTime gets rerolled to 2. Now, your while condition hits as MyTime = HerTime and it breaks out, but those 2 minutes were never accounted for.

An easy fix would be to add a guard condition to your while that gets set in the Else part of your If.

(Warning, the below changes are untested air code)

private static int numberOfSimulations = 100000;
static void Main(string[] args)
{
    var rand = new Random();
    var simulationTimes = new List<int>();
    for (int i = 0; i < numberOfSimulations; i++)
    {
        var totalTime = 0;
        var myTaskTime = rand.Next(1, 6);
        var herTaskTime = rand.Next(1, 6);
        var equal = false;

        do
        {
            if (herTaskTime > myTaskTime)
            {
                totalTime += myTaskTime;
                herTaskTime -= myTaskTime;
                myTaskTime = rand.Next(1, 6);
            }
            else if (herTaskTime < myTaskTime)
            {
                totalTime += herTaskTime;
                myTaskTime -= herTaskTime;
                herTaskTime = rand.Next(1, 6);
            }
            else
            {
                totalTime += myTaskTime;
                equal = true;
            }
        } while (!equal);

        simulationTimes.Add(totalTime);
    }
    Console.WriteLine(simulationTimes.Average());
    Console.ReadLine();
}


Parsing s-expression structure into tree and summing the paths

Avoid indentation.

                        print "no"

When you need this amount of spaces in front of your code, I'd say no too.

This is clearly a sign that what you're writing could be extracted into a function call, our main could be a chain of function calls instead of a big clump of code.

with open('input') as f:
    parseFile(f)

def parseFile(...):
    ...
    for pair in pairs(expr_input): parsePair(pair)
    ...

def parsePair(...):
    ...
    for i, s in enumerate(expression): addExpressionToSummation(i, s)
    ...

Of course, this won't work out of the box; that's what object-oriented programming will help with.

Also, if you need to map one-to-one, use list comprehensions or functions like map.
Regular expressions might sometimes be valuable.

value = value.replace('(', ' ( ').replace(')', ' ) ').split()

can be

value = re.sub(r'(\(|\))', r' \1 ', value).split();

which can be improved to not add multiple spaces by restricting the match or by doing another replace where you replace r' +' by r' '. Of course this example might not be worth it, but if you've got to do heavier duty then you'll quickly want to resort to a regular expression instead of much longer trial-and-error code.
Conditions can be functions, too.

# "is leaf?" ugh.
if tree and expression[i-1:i+3] == ['(',')','(',')']:

Imagine that'd be

if isLeaf(tree, expression):

Oh look, our documentation line is gone. ;)


I was expecting this to be hard as, from what I've read, most people don't create their own

Actually, there are more people who create event emitters than you think. I'm one of them, and here's my implementation. Aside from Event Emitter, it's also called "pub-sub", and here's one of the same nature under that label.

It's a basic practice of the concept of managing async and decoupled code. It also makes for a good practice in code performance, coding style and sample code when learning GIT.

  It's far simpler than most libraries I've seen.

Because it is very simple. Collect callbacks, and when triggered, you look for the right collection and fire. That's about it.

  Is there a flaw in this method?

Yes, and that's what I haven't fixed in mine. The following code in trigger is the problem:

events[evtName].forEach(function(callback) {
  callback(evtObj);
});

In your trigger, you fire the callbacks one after the other. That's fine for sequential code. But what if each of the callbacks contained operations that are synonymous to looping 100k times? And imagine if every callback listening to that fired event did that? That would freeze up the browser.

A solution to that is using timers. Timers can be "set aside" when JS is busy. They don't "block the thread", as they usually call it. That way, you have these "gaps" when executing the callbacks, allowing the browser to breathe and do something else, like render the page perhaps.

var length = events[evtName].length;
var i = 0;
var timer = setInterval(function(){       // Execute whenever possible
  events[evtName][i].call();              // Nothing special about the call()
  if(++i == length) clearInterval(timer); // Clear when done
},0);

  What are the benefits of using something like EventEmitter.js?

If you mean the concept of pub-sub, then you have decoupled of code which means it's easier to put in and pull out code without breaking the rest of the app. You also have a basic facility for managing asynchronous events.

If you meant the library itself, then you just saved your time writing, testing and maintaining a pub-sub library. Not to mention, it's all free. All you need to do is grab and go (and maybe give credits where it's due).


Calculating the prime numbers between two integers

Use better variable names. Or, alternatively, include comments to show what the variables are for.
Reformat the code with better indentation.
Do not use using namespace std. That is just bad practice.
Instead of looping j from 2 to i, you can just loop upto floor(sqrt(i) + 1).
Do not define i, j and k for such a large scope. Keep their scopes minimal.
Since your inputs would always be positive integers, use unsigned.
This is just a personal convention, and you're not bound to it. I like to define variables in the order bool, char, int, long int, float, double, ... so on.

# include <iostream>
# include <cmath>

# define ULI unsigned long int

int main () {
    bool is_prime;
    int num_cases;
    ULI cases[100][2];
    std::cin>>num_cases;

    for(int i = 0; i < num_cases; i++)
       std::cin >> cases[i][0] >> cases[i][1];
    for(int k = 0; k < num_cases; k++) {
        ULI m = cases[k][0],
            n = cases[k][1];
        for(ULI i = m; i <= n; i++) {
            is_prime = true;
            ULI max = (ULI) sqrt(i) + 1;
            for(ULI j = 2; j < i; j++)
                if(i % j == 0)
                    is_prime = false;
            if(is_prime)
                std::cout<<i<<std::endl;
        }
    }
    return 0;
}


Returning matching substrings, of n length, at the beginning and end of a string

Just some answers.

  The code passes the majority of the tests without the first if statement, so that was included to ensure it passes circumstances such as an input of xxxx. Without this statement, xxxx returns x, which is incorrect.

You if-statement solves this case... and nothing more. What about xxxxxx? The problem is that you're starting with the shortest match when you should find the longest. Reversing your loop as rolfl wrote is the way to go.

Be careful with such guard conditions. They're OK for special cases, but there's no special case here.

  Would it make sense, for readability and conciseness, to be creating some variables for things like string.substring(), as I did with strLength?

It depends. If an expression gets used a lot, is complicated, or time-consuming than surely use a local variable. In this case, I probably would not.

  Would it make sense to use a StringBuilder? I can't really see how it could be used in this particular case.

No, you're building nothing.

  Does it make sense to use separate return statements, or would it be more useful to assign the outcome to a resultant string, and use only one return statement at the end of the method?

The single-point-of-return paradigm is pretty obsolete for Java. Separate returns are usually much cleaner.


Low-latency implementation of converting non null terminated char* to unsigned int

Be careful, this code assumes that there is at least one digit in the buffer. To make it work with empty buffer too:

uint32_t result = 0;
for (int i = 0; i < len; i++) {
    result *= 10;
    result += buffer[i] - '0';
}
return result;

In terms of performance, I don't think it's possible to achieve better using clean techniques. There are some optimizations that might help performance, but hurt readability and maintainability. For example you could try loop unrolling:

if (len == 0) return 0;

if (len == 1) {
    return buffer[0] - '0';
}

if (len == 2) {
    return (buffer[0] - '0') * 10 + buffer[1] - '0';
}

// ... and so on, until the max supported length

Yes it's ugly. But loop unrolling tends to improve performance. Tends, the result may depend on your compiler, platform, or the weather. You'll have to measure performance before and after to see if this optimization actually helps our not.


Loading KML files into leaflet Javascript map

This code is quite repetitive, and doesn’t adhere to the Don't Repeat Yourself principle.

One way to DRY it out is to abstract the latter promise callback to a separate function:

const addTrackAndBoundsFromKml = kmltext => {

     // Create new kml overlay
     const parser = new DOMParser();
     kml = parser.parseFromString(kmltext,"text/xml");

     const track = new L.KML(kml);
     map.addLayer(track);

     // Adjust map to show the kml
     map.fitBounds( track.getBounds() );

};

Note that const was added before the assignment of parser to avoid a global variable from being created, and bounds was eliminated because it was only used once. Also, semi-colons were added- while they are only required after a handful of statements, it could lead to errors if somehow whitespace got removed. It is a good habit to default to terminating lines with them.

Then use (a reference to) that function whenever it is needed:

// Load kml file
fetch('lotA.kml')
  .then( res => res.text() )
  .then( addTrackAndBoundsFromKml );

fetch('lotB.kml')
  .then( res => res.text() )
  .then( addTrackAndBoundsFromKml );

//etc...

This way if a change needed to happen in that function that parses the KML, adds the track layer and fits the bounds, it could be done in one place instead of each occurrence.

The file names could also be stored in an array and iterated over:

const files = ['lotA.kml', 'lotB.kml', 'Schematic.kml', 'lotC.kml', 'lotD.kml'];
for ( const file of files ) {
    fetch(file)
      .then( res => res.text() )
      .then( addTrackAndBoundsFromKml );
}

It may not be useful but you could consider using Promise.all() though the need to call the asynchronous .text() method on each result might make that really complicated.

You could also consider using the ecmascript-8 feature async functions with the await operator on the promises, as long as the browser requirements are sufficient.


Ultra-Beginner Python FizzBuzz ... Am I missing something?

Lose the useless brackets

This:

while (count < 101):

can just be:

while count < 101:

Increment out of the ifs

Wouldn't be easier to do:

count = 0
while count < 101:
    if count % 5 == 0 and count % 3 == 0:
        print "FizzBuzz"
    elif count % 3 == 0:
        print "Fizz"
    elif count % 5 == 0:
        print "Buzz"
    else:
        print count

    count = count + 1    # this will get executed every loop

A for loop will be better

for num in xrange(1,101):
    if num % 5 == 0 and num % 3 == 0:
        print "FizzBuzz"
    elif num % 3 == 0:
        print "Fizz"
    elif num % 5 == 0:
        print "Buzz"
    else:
        print num

I've also renamed count to num since it doesn't count much, is just a number between 1 and 100.

Let's use only one print

Why do 4 different print, when what is really changing is the printed message?

for num in xrange(1,101):
    if num % 5 == 0 and num % 3 == 0:
        msg = "FizzBuzz"
    elif num % 3 == 0:
        msg = "Fizz"
    elif num % 5 == 0:
        msg = "Buzz"
    else:
        msg = str(num)
    print msg

Light bulb!

"FizzBuzz" is the same of "Fizz" + "Buzz".

Let's try this one:

for num in xrange(1,101):
    msg = ''
    if num % 3 == 0:
        msg += 'Fizz'
    if num % 5 == 0:       # no more elif
        msg += 'Buzz'
    if not msg:      # check if msg is an empty string
        msg += str(num)
    print msg

Copy and paste this last piece of code here to see what it does.

Python is a very flexible and powerful language, so I'm sure there could be other hundred and one different possible solutions to this problem :)

Edit: Improve more

There's still something "quite not right" with these lines:

if not msg:
    msg += str(num)

IMHO it would be better to do:

for num in xrange(1,101):
    msg = ''
    if num % 3 == 0:
        msg += 'Fizz'
    if num % 5 == 0:
        msg += 'Buzz'
    print msg or num

There! Now with:

print msg or num

is clear that num is the default value to be printed.


Event sourcing using functional programming

The key concept in event sourcing is having an 'updater' function that takes an event and an old state, and returns a new state. Let's capture that as a type. The type can be very generic:

module Update =
  type t<'s, 'e> = 's -> 'e -> 's

  (**
  A function that represents the operation of taking an event and an old
  state to return a new state.
  *)

The next thing to capture is your specific domain and its specific implementation of the 'updater' function:

module Account =
  type t = { logged_in : bool; balance : decimal }
  type event =
    | Login of userid:string * passwd:string
    | Deposit of decimal
    | Withdraw of decimal

  let empty = { logged_in = false; balance = 0m }
  let login_valid userid passwd = true // <- TBD
  let update t event =
    match event, t with
      | Login (userid, passwd), _ ->
        { t with logged_in = login_valid userid passwd }

      | Deposit amt, { logged_in = true; balance = balance } ->
        { t with balance = balance + amt }

      | Withdraw amt, { logged_in = true; balance = balance } ->
        { t with balance = balance - amt }

      | _, t -> t

  (* val update : Update.t<t, event>

Finally, you need some stream of events. It can be in the form of some stream data type or an observable sequence. We will use an IObservable<Account.event> because it's idiomatic in the .Net world. With this stream of events, you can 'fold' over the events and regenerate your final state (your account) by applying the update function at each step.

module Main =
  open System.Reactive.Linq

  (* For example only; real stream will be built differently. *)
  let acct_events =
    Observable.Concat(
      [| Observable.Return(Account.Login ("bob", "pass"))
         Observable.Return(Account.Deposit 1000m)
         Observable.Return(Account.Withdraw 500m) |])

  let acct =
    Observable.Aggregate(acct_events, Account.empty, Account.update)

  (** val acct : IObservable<Account.t> *)


Is returning promise form angular service bad?

Per se returning a promise from an Angular Service is not bad, however there are numerous things in Angular world that are heavily based on Observables:

usually you will likely change the change detection to ChangeDetectionStrategy.OnPush in your components and this will most likely be easier with Angular's async pipe not a problem, because async also supports Promises.
if you use your services for any kind of state and if your are using NgRx for effectively managing it, you'll be using @Effectsthat are basically a lot of RxJs magic and thus it might be easier to use Observables in the first place.
composing services for Guards is easier with Observables

Having that said, I agree with you, that typical REST services are fire and forget and thus IMO do not fit really into Observables well which are meant to be constant sources of events.

It is all about composition, Observables allow better composition for multiple async operations that need to be composed, whereas Promises can be nowadays used pretty easy with async/await for singular, isolated operations.

In the end, I'd advise to stick with the same convention throughout your whole app - either have all services return Promises and convert them to Observables when needed or always use Observables. I assume a lot of examples are using Observables because for non-trivial apps you end up needing better composition options than with pure Promises.


Two Java methods for easy writing and reading bytes in files

From your "reinventing-the-wheel" tag, I assume you're already aware of Guava's and Apache Commons' utilities. So my only nitpick is that the int cast might be clearer if it was closer to the size check:

long sizeLong = file.length();
checkSize(sizeLong);
int size = (int)sizeLong;

Or if you want to be a little more "clever":

int size = checkSize(file.length());
//...
private static final int checkSize(long size) {
    //...
    return (int)size;
}


Creating new string with only distinct letters

Of course you can eliminate the loop by using the Distinct method of the string, which won't care if the string is empty or not.  Assuming vCharCheck is the input string, it would look something like this:

Return New String(vCharCheck.Distinct.ToArray)


You have a lot of comments that are completely unnecessary, they are not needed.

int pumpPowerState = 0; //turns pump on and opens the ball valve to the laminator

The name of the variable tells me what this is and what it needs to do.  pumpPowerState that tells me the pump is either off or on and the assignment tells me we are using a 0 or a 1 to determine the on/off state of the device being controlled.

also the comments before and after the blocks are rather redundant as well, most of your blocks of code that you comment before and after are obvious what they are

///START set pins mode  ///

then there is your comment before the code inside the loop.

//// START FILL LAMINATOR FROM 70GALLON RES ///

This tells me that you should have a function that you call inside the loop, something like this

void FillLaminator() {
    startButtonState = digitalRead(startButton);
    if (startButtonState == HIGH) {
        while (checkFloat() >= 2) {
            digitalWrite(pumpPower, HIGH);
        }
    }
    digitalWrite(pumpPower, LOW);
}

And while we are at it:

void FillWaterBucket() {
    startBucketState = digitalRead(startBucket);
    while (startButtonState == HIGH) {
        digitalWrite(pumpBucketValve, HIGH); //turn ball valve to on
    }
    digitalWrite(pumpBucketValve, LOW); //turn ball valve to off
}

Then you call it like this inside of the loop

void loop() {
    FillLaminator();
    FillWaterBucket();
}

Please indent the code inside of brackets so that you can tell the scope more easily.

Do this:

void setup() {

    pinMode(floatSwitch1, INPUT);
    pinMode(floatSwitch2, INPUT);
    pinMode(floatSwitch3, INPUT);
    pinMode(pumpPower, OUTPUT);
    pinMode(pumpBucketValve, OUTPUT);
    pinMode(startButton, INPUT);
    pinMode(startBucket, INPUT);
}

instead of this:

void setup() {

pinMode(floatSwitch1, INPUT);
pinMode(floatSwitch2, INPUT);
pinMode(floatSwitch3, INPUT);
pinMode(pumpPower, OUTPUT);
pinMode(pumpBucketValve, OUTPUT);
pinMode(startButton, INPUT);
pinMode(startBucket, INPUT);
}

that should be a good start to writing cleaner Arduino code.


Small module for getting JSON to work with in Python

I think you are over-complicating the problem, I would apply the following modifications:

rename the class to, say, ChessAPI
pass username into the class constructor
check for username to exist and define the profile_url instance attribute inside the class constructor
instantiate a single Session object and re-use inside the class methods

Modified code:

"""TODO: docstring"""
import requests

class ChessAPI:
    """TODO: docstring"""
    def __init__(self, username):
        self.username = username

        self.session = requests.Session()

        self.profile_url = "https://api.chess.com/pub/player/{username}".format(username=self.username)
        try:
            if self.session.get(self.profile_url).json()['code'] == 0:
                raise ValueError("User '{username}' not found.".format(username=self.username))
        except KeyError:
            pass

    def get_monthly_archives(self, year, month):
        """Returns a JSON document from Monthly Archives endpoint."""
        archive_url = self.profile_url + "/games/{year}/{month:02d}".format(username=self.username, year=year, month=month)
        get_json_doc = self.session.get(archive_url)
        return get_json_doc.json()

Sample usage (works for me):

api = ChessAPI('alex')
archives = api.get_monthly_archives(2017, 1)
print(archives)


I am glad you asked your question here. I'm hoping to explain why what you are trying to do is a bad idea. I cannot speak much for improving your batch as that is not my strong point but that should not matter as the focus of the review is ....

Security Through Obscurity

If you are unfamiliar with that phrase as a concept Wikipedia has a good primer on it.

If I understand the script correctly it is designed to mark a folder hidden. If it is already hidden then using a password will unlock it. You have a very flawed approach to security as it would only keep the most naive of users in the dark. The following is a combination of points, in no particular order (since the really refer to each other), that illustrate why you should not bother doing this.

Hiding a folder does not prevent access to it. A simple control panel change would expose those folders and since the security of the folder has not changed a user can just walk right in. Or if you knew the full path then you can just type it in Windows Explorer or the Run menu.

  The last two things are quite cumbersome.

You have the "password" hard-coded in the script. It is a very trivial action to make changes. Again this is only keeping a certain breed of user from accessing your document location. Since neither the script or folder are technically secure then it is moot.

PowerShell code is doing nothing but masking the view. You take in a secure password but immediately unsecured it. The only thing that approach would prevent is someone directly behind you watching what you are doing and not looking directly at the keyboard.

Consider PowerShell

For reasons stated above I cannot condone this code but there are some concepts you should be aware of that PowerShell can do better. While you code is mostly batch you have a splash of PowerShell there so I think you have at least a vague familiarity with it.

Use functions

As I am sure you know there are several instances of repeated code. Those could be easily replaced with some simple functions that you could call in a loop that runs 3 times for example.

A much improved choice menu

PowerShell has a great way of creating menus guiding user input and acting on the results. It is not too hard to get a grasp at first glance so I am going to include the code snippet from the from the front of that article.

$title = "Delete Files"
$message = "Do you want to delete the remaining files in the folder?"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
    "Deletes all the files in the folder."

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Retains all the files in the folder."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0)

switch ($result)
{
    0 {"You selected Yes."}
    1 {"You selected No."}
}

Consider Encryption

If you were still concerned about the safety and security of your documents where multiple users would have access consider an encryption solution. It's too much to cover here but there are several simple approaches involving encryption software (I cannot recommend any specific one.).


Counting the number of consecutive 1's in binary

I think its quite long considering the work it does

Your instinct is right - it's quite long. It can be implemented with much fewer lines of code, especially in Python. A solution from @RomanPerekhrest highlights it quite well.

  is this the efficient solution?

From the time complexity prospective, it's not an efficient solution. It's O(n2), where n - number of binary digits in your number. Why? Because in your outer loop, you process each digit one by one regardless of the results in your inner loop. So, if your inner loop finds a segment of ones you don't move ì and index to a bit position following this segment. Instead, you pick a second bit in this segment and find the same segment without the first bit again.

For instance, let's say we have a number which binary representation is 111110. Then your algorithm will find the following segments of ones:

11111  | 4 inner loop steps
 1111  | 3 inner loop steps
  111  | 2 inner loop steps
   11  | 1 inner loop steps
    1  | 0 inner loop steps

An optimal solution has a O(n) time complexity. I'll leave it up to you to update your code based on the explanation above.

Bonus

I noticed that each answer uses bin() to calculate the longest segment of ones. However, it's not really needed since this approach has an additional O(n) space complexity (as you recall it from the previous paragraph, n - number of binary digits).

We could just use bitwise operators to achieve the same result. For example, let's say there's a number 1100011101. It has 3 separate segments of ones: Now, let's play a bit - we will calculate a left shifted version of x and then perform bitwise AND on it. Then, for the shifted version we will calculate its left shifted number and so on.

1 1 0 0 0 1 1 1 0 1 0  (x)
         &
1 0 0 0 1 1 1 0 1 0 0  (x << 1)
---------------------
1 0 0 0 0 1 1 0 0 0 0  y = ((x) & (x << 1))

1 0 0 0 0 1 1 0 0 0 0  (y)
         &
0 0 0 0 1 1 0 0 0 0 0  (y << 1)
---------------------
0 0 0 0 0 1 0 0 0 0 0  z = ((y) & (y << 1))

0 0 0 0 0 1 0 0 0 0 0  (z)
         &
0 0 0 0 1 0 0 0 0 0 0  (z << 1)
---------------------
0 0 0 0 0 0 0 0 0 0 0  ((z) & (z << 1))

So, as you can see it took us 3 steps to reach 0. But 3 is also the length of the longest segment of ones. And it's not a coincidence because bitwise AND of a number and its shifted version shortens each segment of ones by 1. Hence, the longest segment will lose all its ones after < length of the longest segment of ones > steps.

Code

def find_max_ones(number):
    maxLength = 0

    while number > 0:
        left_shifted_number = number << 1
        number = number & left_shifted_number
        maxLength += 1

    return maxLength

if __name__ == '__main__':
    number = int(input('Enter integer number:'))
    max_ones = find_max_ones(number)

    print("Length of the longest segment is ", str(max_ones))


I am not entirely sure what you are unhappy about, so I am going to assume you find it too cumbersome, so here is a "one line" way to do it:

import random
gen_coords = (lambda rows=range(5), cols=range(5): lambda width=50, height=50, side_of_scr=500: [[
    (random.randint(width/2, side_of_scr - width/2), height/2 + row * 2 * height)
    for col in cols] for row in rows])()

That is still ugly, so let us make an elegant solution, with better performance:

import random
def gen_coords(width=50, height=50, side_of_scr=500, rows=5, cols=5):
    lower = width/2
    upper = side_of_scr - width/2
    height_step = 4 * height
    gen_x = lambda : random.randint(lower, upper)
    def gen_row(row):
        y = (row + 0.25) * height_step
        return [(gen_x,y) for col in range(cols))]
    return [gen_row(row) for row in range(rows)]


You've hit the nail on the head there:

I know that the real problem is that we should not use value in concatenated string, but well it was done that way and I can't change it.

So you are in a situation where you have to over-compensate on the database end to counter a bad design decision. Many of us who write SQL regularly in production environments have been there. So let's see what we can do about it.

I have added new lines and indentations to give a better scope of what your string manipulation query is doing:
DECLARE @string VARCHAR(MAX) = 'BLABLA10;GOGOGO30;RES777;ANOTHER;';
SELECT
    CONVERT(
        INT,
        LTRIM(RTRIM(
            SUBSTRING(
                @string,
                CHARINDEX(
                    ';RES',
                    @string
                )+4,
                -4 + CHARINDEX(
                    ';',
                    SUBSTRING(
                        @string,
                        CHARINDEX(
                            ';RES',
                            @string
                        )
                        +1,
                        70
                    )
                )
            )
        ))
    )
;

Note: I have converted "s to 's so I could run it on SQL Server.
This is quite complicated. You've obviously spent a good amount of time putting this together so it would work. I'd say, to avoid WTFs from Mr. or Ms. Maintainer, you should document it.

Inspired by RegEx verbose
There's a regular expression mode in some programming languages that lets you document your regular expression. Since your SQL does similar things than RegEx does, I figured maybe we could find inspiration there. For example sake, this is a documented verbose RegEx from the Python documentation:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

Let's try and do something similar here, starting with the innermost manipulation:
SUBSTRING(  -- get keyword RES and the chars that follow (up to 70 chars max)
    @string,
    CHARINDEX(      -- find index of
        ';RES',     -- semicolon just before keyword RES
        @string     -- in @string
    )
    +1,         -- +1 to advance past the semicolon
    70          -- length of up to 70

So it starts making a bit of sense for the next person. Let's keep working our way up the chain from there:
DECLARE @string VARCHAR(MAX) = 'BLABLA10;GOGOGO30;RES777;ANOTHER;';
SELECT
    /*
    The purpose of this manipulation is to find
    get the value between RES and the next ;
    in a string of keywords and numbers. (referred to as @string)
    NOTE: Read function documentation from inner to outer to understand how this works.
    */
    CONVERT(
        INT,    -- returned value needs to be an integer
        LTRIM(RTRIM(    -- trim potential white space before or after the value
            SUBSTRING(      -- String of characters between end of RES and following semicolon
                @string,        -- in @string
                CHARINDEX(      -- find index of
                    ';RES',     -- keyword RES and semicolon just before it
                    @string     -- in @string
                )+4,        -- add 4 chars to move index just past RES keyword
                -4 + CHARINDEX( -- find index of
                    ';',        -- semicolon after the value belonging with RES
                    SUBSTRING(      -- String of keyword RES and the chars that follow (up to 70 chars max)
                        @string,
                        CHARINDEX(      -- find index of
                            ';RES',     -- semicolon just before keyword RES
                            @string     -- in @string
                        )
                        +1,         -- +1 to advance past the semicolon
                        70          -- length of up to 70 chars
                    )
                )
            )
        ))
    )
;

Looking at it now, there are already a few things that stand out:

Length 70?
Do you really need to capture RES and up to 70 characters? You are converting the string to a signed 4-byte int which will at most be 2,147,483,647 (10 digits). So, just to be safe, let's factor in the keyword RES, and the following ;, and one extra for good luck. So let's change 70 to 15.
SUBSTRING(@string, CHARINDEX(";RES", @string)+1, 15) )

If you needed to change the outermost CONVERT to say, a BIGINT, then you would need a longer string, but that seems not to be the case based on your code.

LTRIM(RTRIM(
I know that SQL operators often include this "just in case", so I don'tblame you for doing so. But since you're seeking a review, I will point out that perhaps you should think of what are the chances of this actually happening?
To illustrate, a use case of this happening would look perhaps like this:

@string = "BLABLA10;GOGOGO30;RES   777  ;ANOTHER;"

If that is not possible, then you may as well just remove the LTRIM(RTRIM( part altogether. In fact, it looks like converting to int already does that for you, so just remove it.
Demo:

SELECT CONVERT(INT, '   777  ')
-- Result: 777

Note: If you do expect that empty spaces will be present, you may need to adjust the 15 value above (instead of 70) to a higher number to account for this.

Speaking of RegEx...
Did you consider using Regular Expressions instead of this complicated manipulation? Here are a few links for you to consider:

Create a UDF to support Regular Expressions in T-SQL

StackOverflow: Regex Match all characters between two strings

If you supported RegEx it may be as simple as just search for (?<=RES)(.*)(?=;) instead of doing this whole mammoth maneuver.


Thoughts:

Variable names: I hate typing unnecessary text as much as the next dev, but variable names are not a good place to skimp. It's one thing when using i as an index variable, for example, but for others, please, please, please use meaningful names. If you have to provide a key after the fact, this should be a good clue that you've not adequately done so.
Don't pollute the global space. If the caller needs access to the function, return it instead. Or use modules (module.exports or the like).
minFontSize less than zero doesn't make much sense. I'd cap it at zero rather than –∞.
maxFontSize being capped at +∞ probably doesn't make sense either.
Your code will re-parse the minimum and maximum font sizes each time the handler is called. Cache these instead.
var a = k: Why? In this case, just use k instead.
i() does not do what you think it will: if el is an array, el.style is going to be undefined, and el.style.fontSize will error.
When iterating arrays using for (;;;), cache the length, like so:

for (let i=0, l=arr.length;i<l;i++) { ... } // for ES5 use "var"

If k = 0, what happens? Division by zero...

This is a very quick rendition of your code (in ES6), with meaningful variable names, and implementing caching and such, but it might be useful:

function fitText(el, ratio, {minFontSize, maxFontSize}) {
  el.style.fontSize = Math.max(Math.min(el.clientWidth / ratio, maxFontSize), minFontSize) + "px";
}

function attachListeners(el, ratio, {minFontSize, maxFontSize} = {}) {
  const boundFitText = fitText.bind(undefined, el, ratio, {minFontSize, maxFontSize}),
        addEventListener = window.addEventListener;
  addEventListener("resize", boundFitText, false);
  addEventListener("orientationchange", boundFitText, false);
}

export function adjustTextSize(el = [], ratio = 1,
  {
    minFontSize=0,
    maxFontSize=Number.POSITIVE_INFINITY
  } = {})
{
  if (ratio === 0) {
    return el; // prevent division by zero later; throwing an exception might be better here, though
  }

  const parsedOptions = {
    minFontSize: parseFloat(minFontSize),
    maxFontSize: parseFloat(maxFontSize)
  }

  const els = (el instanceof Array) ? el : [el];
  for (let i=0, l=els.length; i<l; i++) {
    let actualEl = els[i];
    fitText(actualEl, ratio, parsedOptions);
    attachListeners(actualEl, ratio, parsedOptions);
  }
  return el;
};


Match two dictionary keys efficiently in Python

This mechanism is so fragile that I can't tell for sure what it is supposed to do.  The main issue is that you can't reliably predict the order in which the keys of a dictionary will be enumerated.  For example, this seems to work as you intend:

>>> dic1 = {u'ShutterHours': 732, u'ShieldHours': 732, u'MaskHours': 28, u'TargetHours': 790, u'GndRingHours': 25}
>>> dic2 = {u'ShutterHours': u'Shutter Hours', u'ShieldHours': u'Shield Hours', u'MaskHours': u'Mask Hours', u'TargetHours': u'Target Hours', u'GndRingHours': u'Ground Ring Hours'}
>>> list(zip(dic1, dic2))
[('ShutterHours', 'ShutterHours'), ('ShieldHours', 'ShieldHours'), ('GndRingHours', 'GndRingHours'), ('MaskHours', 'MaskHours'), ('TargetHours', 'TargetHours')]

However, if you insert one entry into dic2, the whole thing might fall apart:

>>> …
>>> dic2[''] = 'empty string'
>>> list(zip(dic1, dic2))
[('ShutterHours', 'ShutterHours'), ('ShieldHours', ''), ('GndRingHours', 'GndRingHours'), ('MaskHours', 'ShieldHours'), ('TargetHours', 'MaskHours')]

What you probably want is a dict comprehension.

final = {dic2[k]: v for k, v in dic1.items()}

Better variable names would make the code easier to understand as well (e.g. labels instead of dic2).


Efficiently calculating differences between file using diff file

You need to parse the patch file format correctly. Otherwise the next patch that deletes an SQL comment will confuse your program, as it looks like this:

--- old_file.sql
+++ new_file.sql
@@ -1,1 +1,1 @@
--- SQL comment
+SELECT * FROM table;

Your current code interprets the removed line as a removed file.

The file format is explained here: http://www.gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html

Since there are other people who had the same problem, you could just build on their work instead of writing your own, e.g. https://github.com/thombergs/diffparser.


This code is vulnerable to TOCTOU. There is a tiny gap between the time that "plain files" are read from the process substitution (find -type f ...) and the time that readlink(1) is called on those filenames.

An attacker could create a program that waits for your program to run and then quickly deletes one of those files found by find(1) and replaces it with a symlink to somewhere else. readlink(1) will then dutifully return the target of that symlink and this is the path that will be output. The target could be outside $absolute_dir_path and a file of any type (directory, device node, ...).

Eg:

#!/bin/bash

set -o errexit
set -o nounset
set -o noclobber

# setup directory containing two plain files
# hardcode absolute_dir_path to /tmp/dir for simplicity
mkdir -p /tmp/dir
rm -f /tmp/dir/a /tmp/dir/b
touch /tmp/dir/a /tmp/dir/b

# emulate OP's find loop, but with inserted actions
# performed by an attacker (in real attack these would
# happen in an external program).
exec 9< <( find /tmp/dir -type f -print0 )
while IFS= read -r -d '' -u 9
do
        file_path_x="$(readlink -fn -- "$REPLY"; echo x)"
        file_path="${file_path_x%x}"
        ls -l "${file_path}"
        # attacker jumps in here and does:
        rm /tmp/dir/b
        ln -s /etc/passwd /tmp/dir/b
done

Output:

-rw-r--r-- 1 martin martin 0 2011-03-31 10:56 /tmp/dir/a
-rw-r--r-- 1 root root 2119 2011-03-28 11:35 /etc/passwd

The risk can be mitigated by only seeking files in directories beneath which untrusted users do not have write access. Directories such as /tmp and /var/tmp are problematic though and this is hard to solve. See the source of (eg) tmpreaper for some ideas.


Sum data that needs to be joined and grouped by

You're right, I cannot simplify it anymore ;-)

Most reviews are about commenting bad code/habits and making suggestions how to improve it. But you're lucky, to me, there is nothing bad to say about your snippet so this will be a short review (and probably a reason why there are no anwers yet).

You use clear names for the properties and variables where you use the first letter of the collection name or something derived (like type). You also use meaningfull names for the properties of the anonymous objects.

If the rest of your code looks as clean as this small sample you should be happy ;-)


The name for this type of parsing is called the shunting yard algorithm.

Your code itself seems fine, as long as you don't intend to support strings with curly braces, e.g. deserialize("{a:{b:'{{{{{{{{'}}").  The biggest issue I see is that it's not very ruby-like in the naming or formatting.  I've made brief attempt at cleaning it up a little below.

def deserialize(input)
  hash = {}                 # avoid one letter variable names
  stack = []
  curr_string = ''          # use single quotes for uninterpolated strings

  input.chars.each do |c|   # This is a better was to loop through the characters
    case c
      when '{'
        curr_string = ''
                            # whitespace makes it easier to read the different cases
      when ':'
        stack.push(curr_string)
        curr_string = ''

      when '}', ','
        stack.push(curr_string) unless curr_string.empty?  # unless is the same as "if not"
                                                           # also use one line statements when the logic is simple
        if stack.length > 0
          val = stack.pop
          key = stack.pop
          stack.push({key => val})
        end
        curr_string = ''

      else
        curr_string += c
    end
  end
  stack.each { |n| hash.merge!(n)}
  hash
end


Integer.TryParse will overwrite the value of that shared property with 0 if the value is not there. Use something like this instead:

Shared Sub New()
    Dim parsed As Integer
    If Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), parsed) Then
        _ReportRequestMaxExecuteAttemptDefault = parsed
    End If
End Sub


Function for formatting a timespan with optional trailing zero

If your goal is to reduce returns, you could use a single string.Format call and not make use of additional arguments in certain cases:

// Changed removeZeroes to includeZeroes since it read kind of like a double negative.
string format = includeZeros ? "{0:d}d {1:d}h" : "{0:d}d";

// span.Hours will not get used if there's nowhere to put it in the format string:
return string.Format(format, span.Days, span.Hours);


Matplotlib-venn and keeping lists of the entries

Perhaps something like the following?

values_to_sets = {a : (a in set1, a in set2, a in set3) for a in union}
sets_to_values = {}
for a, s in values_to_sets.items():
    if s not in sets_to_values:
        sets_to_values[s] = []
    sets_to_values[s].append(a)
print(sets_to_values)

This first identifies each item with a tuple indicating which sets that item belongs to. Then you flip the dictionary mapping, where each tuple maps to a list of items belonging to the combination of sets indicated in the tuple.

You could even expand this to an arbitrary number of sets:

sets = [set1, set2, set3, set4]
values_to_sets = {a : (a in s for s in sets) for a in union}


Find value from other dataset based on 6 variables that must be equal in both datasets

Speed

When working with data at any kind of scale, the golden rule is Do not interact directly with the worksheet. Accessing worksheet objects has huge computational overhead, and you are accessing it every time you check a cell's contents.

Dirk's answer demonstrates how to put a range of values into an Array. Operating on an Array is typically 10-100x faster than operating on a worksheet. When you're finished, just set (Range) = (Array) to print your data back to your sheet.

Magic Variables

Not the good kind of magic either. A magic variable is any hard-coded value. E.G.

  For i = 2 To 1511           'Loop over all values from total dataset
    For j = 2 To 288503       'Loop over all values from IBES file

2 to 1511, 2 to 288503, Magic Variables. Where have those numbers come from? How do you know they're still up to date? I gather they're the final row(s) in your data series. Why not determine them dynamically?

Dim finalRow as long

finalRow = ws.Cells(Rows.Count, colNum).End(xlUp).Row

For i = 2 to finalRow '/ +1 to avoid Headers

    ...

Same goes for your column numbers. They should be named variables along the lines of condition1ColNum, condition2ColNum etc. Additionally, if you know what their headers are, I would start by iterating over your header row, and dynamically determining which columns they're actually in.

The key to all this is: How easy is it to break your Macro? If the answer is just "Add an extra row" or "Add/move a column" then it's not very good.

Also, you see this: Worksheets("Data").Cells(i, 3). You have that sheetName hardcoded 8 times. What if someone renames the sheet? Do you really want to go through and re-type it every time? Instead, use the VBa object model and create a proper Worksheet object:

Dim wsData as Worksheet, wsIbes as Worksheet

Set wsData = sheets("Data")
Set wsIbes = sheets("IBES")

Then you can use it like so:

wsData.Cells(i, 3)

And should the name change, you only have to change it in one place.

Even better, have you ever heard of CodeNames? In VBA, every worksheet object has a "Name" which is displayed in Excel and the user can rename at will unless it's protected. Each sheet also has a "CodeName", which can only be seen / modified in the VBE Window. Additionally, a sheet's CodeName actsas a Worksheet variable. E.G. If I have a sheet called "Data" which has CodeName "wsData" then I can simply write

wsData.Cells(i, 3)

Without having to declare anything. And now, if the user renames your sheet to "Something Something Data", your code won't break, because the codeName will remain unchanged.

For your main loop, you shouldn't be using nested If statements. It's messy and leads to Arrow Code. I would do it something like so:

For i = 2 To wsDataFinalRow 'Loop over all values from total dataset
    For j = 2 To wsIbesFinalRow 'Loop over all values from IBES file
        boolean1 = (Worksheets("Data").Cells(i, condition1DataColNum) = Worksheets("IBES").Cells(j, condition1IbesColNum))
        boolean2 = (Worksheets("Data").Cells(i, condition2DataColNum) = Worksheets("IBES").Cells(j, condition2IbesColNum))
        boolean3 = ...
        ...
        passedTest = boolean1 And boolean2 And boolean3 And ...

        If passedTest then
            ...
        End If

    next j
next i

And now it's much clearer what's going on, and it's much easier to add/move/re-arrange your test conditions at will, and you can add more actions based on a subset of conditions being true *without* having to write out a whole extra If ... If ... If ... If ... block.


Capitalize the first character of all words (even when following a '-')

Your problem is an interesting one,but your solution is not a great use of regular expressions, since there's the better option of using the 'word boundary' anchor \b.

The boundary anchor matches a transition from a word, to a non-word, or vice versa. For this purpose, using the \w match to target word-characters after the \b is the right solution.

Note that the replace-function you give to the replace operation only needs the m argument now, there's no longer any sub-groups to process.

If your code was written as:

    String.prototype.capitalize = function(){
        return this.toLowerCase().replace( /\b\w/g, function (m) {
            return m.toUpperCase();
        });
    };

then you would convert-to-lowercase, then locate the first letter of any word, and convert that to uppercase.

Putting that in to action, like:

    <input id="myInput" type="text" value="" size="50" />

type something in the box above