Using fewer foreach loops to bind values to parameters in PDO

The PDOStatement class (which is what PDO::prepare returns, allows you to pass an array of values to the execute method. If you use that, you don't have to loop over any arrays, calling bindValue over and over:

$vals = array(
    $_SESSION['user_id']
);
$vals = array_merge(
    $vals,
    $_POST['tid']
);
$in = array_fill(
    0, count($vals),
    '?'
);//construct array containing ?
$stmt = $pdo->prepare(
    'SELECT b.name,a.users
     FROM `table1` a
       INNER JOIN `table2` b
         ON a.id = b.id
     WHERE a.id IN ('.implode(',',$in).')
     GROUP BY a.id
     ORDER BY FIELD(a.id, '.implode(',',$in).')'
);
$stmt->execute($vals);

The added benefit of this approach is that you're able to use named placeholders, with just a few minor adjustments:

$vals = array(
    ':sessionUid' => $_SESSION['user_id']
);
foreach ($_POST['tid'] as $idx => $val) {
    $vals[':uid'.$idx] => $val;
}
$in = implode(',', array_keys($vals));
$stmt = $pdo->prepare(
    'SELECT b.name,a.users
     FROM `table1` a
       INNER JOIN `table2` b
         ON a.id = b.id
     WHERE a.id IN ('.$in.')
     GROUP BY a.id
     ORDER BY FIELD(a.id, '.$in.')'
);
$stmt->execute($vals);

Of course, there are a few tradeoffs. Nothing too bad, but still:

PDOStatement::execute(array $bind) binds all of the values as PDO::PARAM_STR (ie string values). This implies you can't use array binding if you are using placeholders in, for example, LIMIT clauses. In those cases, a loop + $stmt->bindValue(':offset', $value, PDO::PARAM_INT); is required. Writing a wrapper that does this for you is not uncommon, and in some cases desirable.
re-use of placeholders is only supported if you're using PDO's emulated prepared statements:

Because you seem to be re-using the same placeholders here, you cannot disable emulated prepares. MySQL does not support the re-use of named placeholders. If you do disable emulated prepares, you will need to add a loop:

//create vals as before
$in = array_keys($vals);
$query = 'SELECT b.name,a.users
     FROM `table1` a
       INNER JOIN `table2` b
         ON a.id = b.id
     WHERE a.id IN ('.implode(','$in).')
     GROUP BY a.id
     ORDER BY FIELD(a.id, ';
foreach ($in as $idx => $key) {
    $vals[$key.$idx] = $vals[$key];//add value a second time, using a different key
    $in[$idx] .= $idx;//change values in $in
}
$query .= implode(',', $in).')';//add new placeholders to query
$stmt = $pdo->prepare($query);
$stmt->execute($vals);//should work now

Apart from that, I'd suggest you set PDO's error mode so that it actually throws exceptions. As it stands, PDO will throw an exception if the connection fails, but not if any of the other calls fail (prepare, execute,...).
To fix this, either call PDO::setAttribute, or pass an array to the constructor:

$pdo = new PDO(
    $dsn,
    $user,
    $pass,
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    )
);
//or
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

All in all, loops like you have do very little harm, avoiding them can improve readability, but their impact on performance is so minute that getting rid of them, for the sake of optimization is not a great idea. Remember "Premature optimization is the root of all evil".


Merge inserted and deleted tables in SQL trigger

For me it is not exactly clear what you are trying to achieve, but it looks like propagating a balance change up into some tree (some chart of accounts, maybe?).

First, using triggers like this is very convoluted and error prone. Max recursion level for nested triggers is 32 and it is very hard to trace what it is going on.

Maybe the following approach might be useful for you: create a temporary table based on your data to update (you may have multiple updates at once)

ID
ParentID
LevelNo -- should contain the level in the tree
OriginalBalance
NewBalance

Data can be populated using a recursive CTE, if update is touching only one node and you want to operate on that branch only.

For each level = LevelNo to 1
   Update parent with balance difference

This suggestion works only if your structure is a tree. If you provide us more details (table structure etc), we may come with a more concrete solution.


Lifecycle hooks are functions that are invoked at different stages of a component. Here constructor() and componentDidMount() works different. From my point of view, state variables are initialized inside constructor() and api calls are done in componentDidMount() hook. we are not supposed to define function definitions inside lifecycle hooks. Your above component can be converted to

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isActive: false
    };
  }

  setToActive = (e, id) => {
    const {
      setTaskID,
      arrowStyleToDone,
      closeAllTasks,
      closeAllDoing,
      disableArrowButton
    } = this.props;
    setTaskID(id);
    arrowStyleToDone();
    if (!e.target.classList.contains("active")) {
      e.currentTarget.classList.add("active");
      e.currentTarget.classList.add("border-done");
      closeAllTasks();
      closeAllDoing();
    } else {
      e.currentTarget.classList.remove("active");
      e.currentTarget.classList.remove("border-done");
      disableArrowButton();
    }
  };

  componentDidMount() {} // no need for this lifecycle since we are not making any initial function call, like fetch from api etc.

  render() {
    const { done } = this.props;
    const { isActive } = this.state;
    return (

        Done
        {done &&
          done.map(item => (
            <div
              className={`done ${isActive ? "active" : ""}`}
              key={item.id}
              onClick={e => this.setToActive(e, item.id)}
            >

          ))}

    );
  }
}

Basic structure of React component is

Class component

class Class_Name extends Component{
    constructor(){
      this.state = {} // state variable
      this.toggleTab = this.toggleTab.bind(this);
    }

   // other functions
   toggleTab = ()=>{} // these are example functions.

   // life cycle hooks if you are using any

   render(){
    return (

    )

   }

}


Performing substitutions according to a word list in a database

This whole approach seems flawed to me. It's hard to predict how people will misspell words and you therefore end up with a very big list of possible misspellings.

Why not do it the traditional way: Start with a list of correct words ($correctWords), and use that to find the words not in that list. If you convert the text ($text), you want to correct, to an array of words you can use:

$textWords       = explode(' ',mb_strtolower($text));
$misspelledWords = array_diff($textWords,$correctWords);

I would remove punctuation before starting this process. When you have the possibly misspelled words, you can decide what to do with them.

You could, for instance, compare the misspelled words with the list of correct words, using one of these functions:

http://php.net/manual/en/function.levenshtein.php

http://php.net/manual/en/function.similar-text.php

The closest one is probably the correct one. This comparison might be slow, but there are probably only a few misspelled words, so it won't take long.

You could also still use your list of misspellings, if you want to.

After you've decided, what the misspelled words should be replace by, you can do:

$text = str_replace($misspelledWord,$replacementWord,$text);

Note that str_replace() will accept arrays, like this:

$text = str_replace($misspelledWords,$replacementWords,$text);

and after that you're done.

This only shows you the basic idea. It needs a lot of refinement to be of any practical use.


Maximum score, using only elements near the beginning or end of a list

1. Analysis

(The code in the post was edited after I wrote this analysis, so the list of operations does not correspond to the latest version of the code. But the asymptotic result is the same.)

I'll write \$n\$ for the length of the score list, and \$k\$ for the number of team members.

On each iteration of the loop we have these operations:

slices score[m] and score[-m:];
a list concatenation score[m] + score[-m:];
a call to max on the concatenated list;
a call to score.index;
a call to score.pop.

Operations 1–3 take time proportional to \$m\$, and operations 4–5 take time proportional to \$n\$. The loop executes \$k\$ times, so the overall runtime is proportional to \$k(m + n)\$.

In the worst case, \$k\$ and \$m\$ are both \$Θ(n)\$, and so the overall runtime is \$Θ(n^2)\$, that is, quadratic in the size of the input.

We can demonstrate this behaviour by timing some random test cases:

from random import random
from timeit import timeit

def test(n, f=teamFormation):
    score = [random() for _ in range(n)]
    return timeit(lambda:f(score, n, n // 2 - 1), number=1)

and plotting the timings:

2. Better algorithm

In order to improve the performance of the code, we need to rewrite the code so that within the main loop, we avoid operations that take time proportional to the length of the slices, \$m\$, or to the length of the whole list, \$n\$.

What we'd like to do is to maintain a data structure containing the \$2m\$ values from the two ends of the list. The data structure must allow us to efficiently find and extract the maximum value. Then we can repeatedly extract the maximum value, and then replace it with the next value from the appropriate end of the remainder of list (the left end if the maximum value came from the left side, and right end otherwise).

The data structure we need for this is a heap, and Python provides us with the heapq module for manipulation of heaps.

I'll give the revised code below; read it and see if you can figure out how it works.

from heapq import heapify, heappop, heappush, nlargest

def best_team_score(score, k, m):
    """Return the maximum sum of k elements from the sequence score,
    subject to the condition that only the first m and last m can be
    selected at each stage.

    """
    n = len(score)
    if n < k:
        raise ValueError("Not enough scores to make a team.")
    if n <= 2 * m:
        return sum(nlargest(k, score))

    # Heap of (-score[i], i) pairs. The score is negated because
    # Python's heaps are min-heaps, but we want the maximum score. By
    # pairing with the index we can ensure that the leftmost score is
    # returned in case of a tie, and that we can tell whether the
    # maximum score came from the left or the right side.
    heap = [(-score[j], j) for i in range(m) for j in (i, n - i - 1)]
    heapify(heap)

    # score[left:right] are the elements of score that have not yet
    # been added to the heap.
    left = m
    right = n - m

    total = 0
    for _ in range(k):
        # Leftmost maximum score in the heap.
        s, i = heappop(heap)
        total -= s
        if right <= left:
            # All scores are now in the heap.
            pass
        elif i < left:
            # Maximum score came from left side.
            heappush(heap, (-score[left], left))
            left += 1
        else:
            # Maximum score came from right side.
            assert right <= i
            right -= 1
            heappush(heap, (-score[right], right))
    return total

We can check that this is correct by testing against the original code:

from itertools import product
from random import random
from unittest import TestCase

class TestBestTeamScore(TestCase):
    def test_best_team_score(self):
        for n in range(50):
            score = [random() for _ in range(n)]
            for k, m in product(range(1, n + 1), repeat=2):
                found = best_team_score(score, k, k)
                # teamFormation modifies score, so take a copy.
                expected = teamFormation(score[:], k, k)
                self.assertEqual(expected, found, score)

The heappush and heappop functions take time proportional to the logarithm of size of the heap, which is at most \$2m\$ so we expect the runtime to be propertional to \$k\log 2m\$, and since \$k\$ and \$m\$ are \$O(n)\$, the overall runtime is \$O(n\log n)\$:

3. Appendix: plotting

In case you're interested in how I drew the plots:

from functools import partial
import matplotlib.pyplot as plt
import numpy as np

def plot1():
    emin, emax = 1, 5
    x = 10 ** np.arange(emin, emax + 1)
    y = np.vectorize(test)(x)
    plt.xlabel("n")
    plt.ylabel("t (seconds)")
    a, = np.linalg.lstsq(x[:, np.newaxis] ** 2, y)[0]
    xx = 10 ** np.arange(emin, emax, 0.01)
    plt.loglog(xx, a * xx**2, label="least squares fit to $t = an^2$")
    plt.loglog(x, y, 'r+', label="data")
    plt.legend()
    plt.grid(alpha=0.25)
    plt.show()

def plot2():
    emin, emax = 2, 7
    x = 10 ** np.arange(emin, emax + 1)
    y = np.vectorize(partial(test, f=best_team_score))(x)
    plt.xlabel("n")
    plt.ylabel("t (seconds)")
    a, = np.linalg.lstsq((x * np.log(x))[:, np.newaxis], y)[0]
    xx = 10 ** np.arange(emin, emax, 0.01)
    plt.loglog(xx, a * xx * np.log(xx),
               label="least squares fit to $t = an\log n$")
    plt.loglog(x, y, 'r+', label="data")
    plt.legend()
    plt.grid(alpha=0.25)
    plt.show()


Linked object for creating chains without lists

Rule your own Find extension method instead of redoing it all over again.

public static LinkedListNode<T> Find<T>(this LinkedList<T> list, Predicate<T> pred)
{
    var node = list.First;
    while (node != null)
    {
        if (pred(node.Value))
        {
            return node;
        }
        node = node.Next;
    }
    return null;
}


Async Queue implementation without locking

The only difference is that I got rid of the internal locks that implementation uses.

  Since a ConcurrentQueue is already thread safe, I can't figure out why they chose to use a lock in their implementation.

From my understanding of the meaning of "thread safety":

  All public and protected members of ConcurrentQueue<T> are thread-safe and may be used concurrently from multiple threads.

A class being "thread safe" just means its members are, but only individually. So one method being called from many threads will not cause problems. Interacting with many members from many threads might not be "thread safe".

In some sense, the meaning of "thread safety" depends on your application.

If you look at the lock from the answer:

lock (_syncRoot)
{
    if (_promisesQueue.TryDequeue(out promise) &&
        !promise.Task.IsCanceled &&
        promise.TrySetResult(item))
    {
        return;
    }
    _bufferQueue.Enqueue(item);
}

All those statements in the block are combined together to be accessed only by one thread, which is something the "thread safety" of the class alone cannot guarantee.

The lock allows you to group code into a thread-safety-wise "atomic" block.


I'm not sure that delegating to a normal array is not the best solution. Normally when I create classes like this the intent is to provide a more rigid interface over an array and delegation would be the best solution. What you have will certainly work but is going to be extremely in-efficient speed wise since those get/set/defined methods are quite slow. i.e. This is great as an exercise but I would never write code like this in a real world app.

Some changes I would make:

The set method does no checking so it is currently possible to add items to the array
Instead of instance_variable_defined? I would use (0..size).include?(index)
I would extract the index checking into a method and use it in both set/get:

def check_index!(index)
  raise OutOfBoundsError unless (0..size).include?(index)
end

I would add [] and []= aliases for get and set

Also most style guides recommend against using self. redundantly to prefix method names.


Some suggestions:

Pass the code through pycodestyle to make it more idiomatic.
Use with open() (or try/finally for a more complicated solution) to make sure files are closed whenever they are done with.
You can do .readlines() on a file pointer to avoid stripping newlines.
The dictionary is presumably controlled by you. Sort and lower-case it once, and then you don't have to do that every time the script runs.
These are logically equivalent:

    for x in y:
        if x == target:
            return True
    return False

and

    return target in y

Use descriptive names such as for word in words and `def linear_search.
Put the timing code around the lines you are trying to time. If you want to know the aggregate time of linS then get the start and end times just before and just after the last loop (which will count the time it takes to write to disk buffers) or accumulate a sum of run times within `linS`.


I suggest not codifying the derived types suggested in the type. Only note the ultimate base, size and alignment. Thus you are open to later change.
Add a templated alias to get the proper type from base plus candidates.

Assure that no over-sized object is ever assigned in PolyUnionSize, probably best using SFINAE. No need to defer to the user.

Don't assume constructing the new object will never fail.

PolyUnionSize::PolyUnionSize<class D>(D&& d) and PolyUnionSize::operator=<class D>(D&& d) use perfect forwarding. You don't account for that by using std::decay_t where needed, nor heed it when computing noexcept.

The implicit copy-/move- ctor / assignment are only appropriate for trivial types. And in that case, why override the dtor?

As casts should be used sparingly, consider delegating between op* and op->.


Decimal to binary and binary to decimal convertor

Validate User Input:

Always check user input is what you expect. The user may enter a valid number, or they may enter a number too long to be stored in the given type, or they might enter "fifty-three".

The code should handle these cases, rather than crashing, entering an infinite loop (option 2) or producing incorrect output (option 1). These are bugs in your program that need to be fixed. Check the answers here for ideas.

One way to do this is to loop and re-request data until the user enters an expected value. This pattern can be applied to significantly improve the overall structure of your program, e.g.:

while (true)
{
    auto conversionType = ask_conversion_type();

    if (conversionType == ConversionType::BinaryToDecimal)
    {
        // ... ask user for binary input with another loop
    }
    else if (conversionType == ConversionType::DecimalToBinary)
    {
        // ... ask user for decimal input with another loop
    }
    else
    {
        // error...
    }

    // maybe we also need an exit option?
}

Testing

Write unit tests, so you can check that the various components of the code work. In the simplest case, this can be done by adding a little function like so:

void test(bool condition)
{
    if (condition)
        std::cout << "pass" << std::endl;
    else
        std::cout << "FAIL" << std::endl;
}

and then writing some tests at the start of main() to make sure you get the output you expect for each function:

test(decimal_to_binary(0) == std::vector<ulli>{ 0 });
test(decimal_to_binary(2) == std::vector<ulli>{ 1, 0 });
//test(decimal_to_binary(-5) == um??? );

This will also help with thinking about edge cases!

Types

If each number in the vector will only store 0 or 1, maybe it doesn't need to be a vector<ulli>...

Context

What is the purpose of this code? If it's an excercise doing a particular thing (i.e. you have a special definition of a "binary number" you must adhere to, or you have to write your own functions), then you need to share that with us, lest it all be "optimised" away.

For example, we could just use std::bitset:

#include <bitset>
...

case 1:
{
    std::cout << "\nEnter Decimal number\n";
    unsigned long long num;
    std::cin >> num;
    // check input... then:
    std::bitset<64> bits(num);
    std::cout << "The binary equivalent of " << num << " is :\n" << bits << "\n";
    break;
}
case 2:
{
    std::cout << "\nEnter Binary number\n";
    std::bitset<64> bits;
    std::cin >> bits;
    // check input... then:
    std::cout << "The decimal equivalent of " << bits << " is :\n" << bits.to_ullong() << "\n";
    break;
}

The code is certainly shorter! But maybe doesn't fulfill some other requirements?


Querying the same fields for many different values on AppEngine

With Objectify, you have the option to use the "in" operator in a query. Moreover, it becomes clear from the second block of nested loops that you are only looking for the intersection of the two sets of measuredUserIds and standardIds. So, a single statement should do the trick:

public List<StandardScoreDAO> getStandardScores(
        ArrayList<Long> studentIdLongs, ArrayList<Long> standardIdLongs) {
    ObjectifyService.register(StandardScoreDAO.class);
    Objectify ofy = ObjectifyService.begin();

    Iterator<StandardScoreDAO> i = ofy.query(StandardScoreDAO.class)
                    .filter("measuredUserId in", studentIdLongs)
                    .filter("standardId in", standardIdLongs)
                    .iterator();

    List<StandardScoreDAO> ret = new LinkedList<StandardScoreDAO>();

    while (i.hasNext()) {
        ret.add(i.next());
    }

    return ret;
}

If you access a list merely by iteration (and not by random access or by index), and do not know its size on creation, LinkedList might give you a performance benefit.


Counting how many times each distinct word appears in an input

Old book:

The age of the book starts to get noticable. May be before 2011 it would be still very effective, but not that much now. May be not in 5 lines, but it is possible write it pretty shortly and neatly in upcoming C++17

#include <iostream>
#include <iterator>
#include <vector>
#include <map>

int main() {
    std::vector<std::string> all_words{std::istream_iterator<std::string>(std::cin),
                                       std::istream_iterator<std::string>()};
    std::map<std::string, std::size_t> unique_words;
    for (const auto& word: all_words)
    {
        ++unique_words[word];
    }

    for (const auto& [word, count]: unique_words)
    {
        std::cout << "word " << word << " occured " << count << " times\n";
    }
}

live demo. Be sure to checkout stdin though, I'm not sure if it is preserved.

Unfortunately there are not many books about recent versions of C++, but knowing the basics should be enough to learn new stuff.

It is also possible to write this without using a map, albeit much more sophisticated:

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <string>

int main()
{
    std::vector<std::string> all_words{std::istream_iterator<std::string>(std::cin),
                                       std::istream_iterator<std::string>()};

    std::sort(all_words.begin(), all_words.end());
    auto first_duplicate_pos = std::unique(all_words.begin(), all_words.end());

    for (auto first = all_words.begin(); first != first_duplicate_pos; ++first)
    {
        auto count = std::count(first_duplicate_pos, all_words.end(), *first);
        ++count; //since occured once in non duplicate part
        std::cout << "word " << *first << " occured " << count << " times\n";
    }
}

The idea here is that after using std::unique<>(), the vector is divided into two ranges: one that has only unique elements, and other has duplicates of unique elements, if any. Now, map is not needed, because in fact the first range is map keys with value equal to 1 (remember that unique counts too). Then we just iterate through the other half searching for one of the keys at a time.

Do note that both versions are invincible to the problem mentioned by @jvb. Thus, it is much better to learn to use standard library first, rather than trying to implement it by hand.

Code Review:

int main ( int argc, char** argv )

No need to have arguments if code is not using it.

sort(input_arr.begin(), input_arr.end());

It would be better to just use std::unique<>() after this and count every occurrence of the elements in range.

Using std::endl should be avoided. It flushes the stream, which is pretty slow. Even Bjarne Stroustrup (original creator of the language) avoids that himself. Instead just use '\n'. std::endl is not only portable way to print a newline, but it also incurs overhead.

for (int j = 0; j <= count; j++)

This lines seems dangerous. I was not able to comprehend the counting logic, but usually when <= count appears, it means getting out of range, which is undefined behavior if it would be the whole vector. I'm pretty sure it should be < count. Anyway, it should've been possible to just use range loop and not worry about the comparison operator.

using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::endl;

This probably didn't buy anything, but instead increased amount of code needed to write. I recommend just sticking with std::. If the namespace is too long, for example std::experimental::filesystem, I recommend doing

namespace exfs = std::experimental::filesystem;

at function scope!

update:

People in the comments mentioned that std::unique<>() is not a partitioning algorithm and the right side of the sequence has unspecified values. It is true. I present another solution, which is standard compliant (I actually went on searching if std::unique<>() always performs swap, but it seems like it is not the case).

#include <algorithm>
#include <iterator>
#include <iostream>
#include <functional>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> all_words(std::istream_iterator<std::string>(std::cin),
                                       {});
    std::sort(all_words.begin(), all_words.end());

    auto first_occurence = all_words.begin();
    while (first_occurence != all_words.end())
    {
        auto next_word_occurence = std::find_if_not(first_occurence, all_words.end(),
                                                    [&first_occurence](const auto& val)
                                                    {
                                                        return val == *first_occurence;
                                                    }
        );

        std::cout << "word " << *first_occurence << " occured "
                  << std::distance(first_occurence, next_word_occurence)
                  << " times\n";
        first_occurence = next_word_occurence;
    }
}

I didn't use std::adjacent_find<>() because it obfuscates the main goal, in my opinion. Using std::find_if_not<>() and its non not version is arguable, but I just went with not version because I usually read on high speeds and sometimes tend to confuse != and ==. Do note that this version is still immune to the point mentioned by @jvb.


Calculate sum, mean, sum of squares, and standard deviation of array elements

Let the compiler help you

The first thing to do is to compile with a decent compiler and look at the warnings. With gcc -O -Wall -W:

dassouki.c: In function ‘main’:
dassouki.c:70: warning: implicit declaration of function ‘rand’
dassouki.c:70: warning: implicit declaration of function ‘time’
dassouki.c:90: warning: control reaches end of non-void function

You're missing two headers, stdlib.h and time.h, where the functions rand and time are declared. Once you add them you see another error:

small_fixes.c: In function ‘main’:
small_fixes.c:72: error: too many arguments to function ‘rand’

For now, to get code that compiles, remove the arguments to rand, it doesn't take any. I'll explain about rand below.

The last warning is there because main function returns an int value; you neglected to do that. If your implementation conforms to C99 (few do, and the one I compiled with doesn't), there is a special dispensation for the main function: you can omit the return statement, and it's as if you'd written return EXIT_SUCCESS. For utmost portability, return EXIT_SUCCESS to indicate success, or EXIT_FAILURE to indicate failure. On unix and Windows, EXIT_SUCCESS is 0 and EXIT_FAILURE is 1, though any nonzero value (positive and up to 255, though you should stick to small values) indicates failure. If you don't return a value from main (and aren't using a C99 compiler), the effect on most platforms is that your program returns whatever was in a particular register when main finishes executing, which is not good.

General style

Generally speaking, your code is well-organized and well-presented, congratulations. Here are a few minor improvements:

The array x doesn't actually need to be global, you can make it local to main. If you make it global, give it a longer name — global variables should be used sparingly and should be easily noticeable and searchable.
Don't use abbreviations in the names of global variables or functions. Call your functions square_sum or sum_of_squares, standard_deviation.
The proper type for an array length is size_t. On some machines, you can have arrays whose size doesn't fit into an int. Note that size_t is an unsigned type, which has the advantage that you won't run into the occasional difficulties of signed arithmetic, but you need to be careful with downwards loops (for (i=n; i>=0; i--) is an infinite loop if i is unsigned).

Output

You're missing newlines (\n) at the end of several printf calls.
The printf conversion specifier for a double is %f (or %e or %g), not %lf. Many implementations allow %lf as a synonym for %f, but this is not universal.
The printf conversion specified for a size_t is %z, but that only exists if your implementation conforms to C99, which is still not the norm today. In C89 (the prevalent standard today), your best bet is to cast to unsigned long, e.g.

printf("[%lu] %lf\n", (unsigned long)i, x[i]);

Why are you printing i+1 next to element number i? It's confusing. Print i and x[i] (as above).

Random number generation

rand() generates a random integer between 0 and RAND_MAX. On many platforms, RAND_MAX is 32767. Here, you're storing this into a floating point array, so it looks like you want to generate a random floating-point number. This is a difficult problem, and the solution depends on what distribution you want. On unix/POSIX platforms, there is a function drand48 which generates a random floating-point number in the range [0,1] with a uniform distribution. This issue is unrelated to the meat of your program, so you may be content with generating a random integer with rand().

A second issue is that rand() and friends use a pseudo-random number generator. This means that they will always return the same sequence of numbers if they are initialized in the same way. Initializing a random generator is called seeding it, and the function to seed the PRNG is srand(int). If you never call that function, your program will always fill the array with the same values. A common way of initializing the PRNG for testing is srand(time(NULL)); this will make your program use different values every second (on most machines).

Random number generation is a fairly complex topic; I recommend reading the clc FAQ, questions 13.15–13.20, especially Each time I run my program, I get the same sequence of numbers back from rand() and How can I generate floating-point random numbers?.

For the time being, add srand(time(NULL)); near the beginning of your main() function, and fix the call to rand().

Input validation

You read an integer with scanf. This function is convenient for quick tests but tricky to use correctly. It's difficult to react properly if the user enters garbage.

Since num should be a positive integer, make it an unsigned type. In C99, make it size_t and call scanf("%z", &num). In C89, make it unsigned long and call scanf("%lu", &num).

Perform at least some token validation of num. The number should be positive (if you want to allow 0, you need to add a special case to some of your calculations). And it must not be larger than the size of the array.

scanf("%lu", &num);
if (num == 0 || num >= sizeof(x)/sizeof(x[0])) {
  printf("Invalid number of elements, goodbye.\n");
  return EXIT_FAILURE;
}

sizeof(x)/sizeof(x[0]) (which can also be written sizeof(x)/sizeof(*x)) is an idiom to denote the number of elements in the array x: it's the size of the array divided by the size of one element. Note that this only works if x is an array, not if x is a pointer. Pointers to arrays don't contain any indication of the size of the array, and the size needs to be specified separately (hence your arr_count argument when you pass a pointer to the array to the various functions).


Merge and sorting arrays of String and int in more efficient methods

mergeAndSortStringArrays looks good to me. What comes to mergeAndSortIntArrays, you can clean it a bit:

public static int[] mergeAndSortIntArrays(int[] firstInt, int[] secondInt){
    List<Integer> merged = new ArrayList<>();
    IntStream.of(firstInt) .forEach(merged::add);
    IntStream.of(secondInt).forEach(merged::add);
    Collections.sort(merged);
    return merged.stream().mapToInt((Integer i) -> (i)).toArray();
}

Generic implementation

Also, you could do

public static <E extends Comparable<? super E>> E[]
mergeArrays(final E[] firstArray, final E[] secondArray) {
    final E[] ret = Arrays.copyOf(firstArray,
                                  firstArray.length + secondArray.length);
    System.arraycopy(secondArray,
                     0,
                     ret,
                     firstArray.length,
                     secondArray.length);

    Arrays.sort(ret);
    return ret;
}

This, however, will not accept an int[] as the argument type, yet it will gladly work on Integer[] and other object arrays.

A minor tip

Instead of writing for loops for printing arrays, you can always say:

System.out.println(Arrays.toString(mergeArrays(first, second)));

Hope that helps.


Improving Fibonacci recursion with BigIntegers

Every time you call theBigFib, you allocate a new BigInteger[] a object.  As a result, you're not caching any previous results.


Web crawler that filters out non diseases

Here are some suggestions:

More comments and docstrings would be nice, so the reader/reviewer can see what you intend the code to do (why was the code written this way?). It makes it easier to follow, because your intention is clear, and also then I can spot bugs where the implementation doesn't match the indentation.
Add more whitespace! Particularly vertically; breaking up the functions with newlines will make it substantially easier to read/
At the top of the file, you construct a list of lowercase letters alpha. You’ve also imported, but not used, the string module. It would be better to use string.ascii_lowercase, which works as follows:

  string.ascii_lowercase

  The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.

Then you can get rid of the alpha variable, and just use this.
disease_spider()

You should use a for loop rather than a while loop:

for i in range(maxpages):
    # do some stuff

Rather than constructing the request URL using string concatenation, use new-style format strings:

url = 'http://www.cdc.gov/DiseasesConditions/az/{}.html'.format(
    string.lowercase[i]
)

I’m guessing that this function goes through the pages from A to Z, yes? But there’s no guard against the user calling this function with maxpages ≥ 26, which would throw an IndexError here. You should add some sort of check.

Use a better variable name than l in your soup.findAll loop. How about link?

Then I’d have a list of forbidden names, and just check than link.text isn’t in that list. For example:

forbidden_text = ['USA.gov', 'Inspector General', '']
if link.text not in forbidden_text:
    # do some more stuff

diseasechecker()

I noticed when reading this function that you use this block of code in all three functions:

source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)

You should consider pulling this out into its own function, that takes a URL and returns the corresponding BeautifulSoup object. It would slightly tidy up the code.

The variable names in this function are all short and undescriptive; pick something that tells me what the value of this variable represents.

This function mutates a global list w, although it’s the only function to do so. I think it would be better if you moved the definition of w inside this function, and returned it at the end. That makes the function more self-contained.

You loop over all p and li elements separately, but do the same thing with each. Why not combine the loops, so you only have to write out the body of the loop once:

for element in soup.findAll('p') + soup.findAll('li'):
     # do some stuff with elements

I believe you can also tidy up the if statement:

if (url2 not in w) and ('symptoms' in str(y) or 'symptoms' in y.text):
    w.append(url2)

The parens aren’t strictly necessary, but I think they’re useful here for readability. I also got rid of the x and txt variables, which I don’t think aid readability. This is more direct.
level3()

Again, pick some better variable names that x and y.

And you can tidy up the if statement:

if 'symptoms' in str(y) or 'symptoms' in y.text:
    return 1

In the final loop, you’re looping over the index:

for i in range(len(w)):
    print w[i]

It is far cleaner and more Pythonic to loop over the list directly; i.e.,

for word in w:
    print word


I think you are missing the point. Different objects can produce same hashcode. This can happen:

obj.Equals(otherObj)  // false
obj.GetHashCode() == otherObj.GetHashCode() //true

If for some reason you want your Equals methods to return true when hashcodes are equal, then by all means. Make sure to document this behavior though.

However if you want to compare references , then use ReferenceEquals method instead. Hashcode comparison will not work for that scenario, because hashcode equality does not guarantee that object are (reference-)equal.

P.S. Also keep in mind, that hashcodes should not change, otherwise hash-tables might break. Make sure that Id and TypeName are read-only properties.


Naming

In Clojure, there's a similar function named juxt.  Not saying that's a better name by any means, just mentioning what it happens to be called in one other place.  Upon further reflection, what you are doing is really just a recursive form of function application.  So a suitable name might reflect that.  Perhaps apply_rec?
Use the shortest name that conveys sufficient meaning.  For example, list_of_functions could be shortened to functions (or even just fs).  possible_function could be shortened to f.  (Single-character names are not good names in general, but for generic entities that have a well-known mathematical notation, they are a good fit.)

Use Better Checks for Callable / Iterable

You check if something's callable by trying to call it and catching a TypeError exception.  However, if you call a function, and that function happens to through a TypeError, then your code will incorrectly assume it's not a function.  You can use the callable function instead, to determine whether or not something is callable.

A similar situation exists in the way you check for iterables.  In this case, you can use the iter function as a fail-fast way to check if something's iterable.

Consider Using a List Comprehension

Reading your code, I thought it was a bit ironic that you used a list comprehension in the docstring to describe the functions behavior, but not in the code itself.  Granted, due to the recursive nature, it's not quite as straight-forward.  But with just a little refactoring, it should be possible.  Here's how I would do it:

def apply_rec(f, x):
  """
  If f is a function, applies f to x and returns the result.
  Otherwise, if f is iterable, applies every element in f to x,
  returning a list of the results.
  If f is neither callable nor iterable, returns f.
  """

  if callable(f):
    return f(x)
  else:
    try:
      fs = iter(f)
    except:
      # Not iterable => return f
      return f

    return [apply_rec(f, x) for f in fs]

I've omitted the recursion limit, but that should be trivial to add.


Avoid using namespace std
Avoid using namespace std, it is considered bad practice. It saves only a little bit of typing, but you can run into issues if names of local classes and variables clash with those defined in the standard library.
Use INT_MAX instead of INF
Don't #define INF to some arbitrary value, just set it to exactly the largest possible value an int can have. This is already defined as INT_MAX in <climits>.
Create a struct Edge
Using a std::pair<int, int> is convenient, especially since you can sort them, but it has some drawbacks. It is unclear from just looking at the definition of this type whether the first element is the node number and the second the weight, or the other way around. You actually use both conventions in your code: the adjacency list has the vertex number first, whereas the priority queue has the vertex number second. Create a proper struct to remove the ambiguity and increase type safety. Also, since an edge is a property of a graph, define struct Edge inside class Graph, like so:
class Graph {
    struct Edge {
        int vertex;
        int weight;
    };

    std::list<Edge>* adj;
    ...
};

Instead of calling adj[u].push_back(std::make_pair(v, w)), you should now write:
adj[u].push_back({v, w});

For the priority queue, you also want to create a separate struct for the elements. Since only Graph::shortestPath() uses this, you can define this inside that function. To make it sortable, define an operator<() in this struct, like so:
void Graph::shortestPath(int src) {
    struct VertexDistance {
         int vertex;
         int distance;
         bool operator<(const VertexDistance &other) {
             if (distance != other.distance)
                 return distance > other.distance;
             else
                 return vertex > other.vertex;
         }
    };

    std::priority_queue<VertexDistance> pq;
    ...
}

Avoid manual memory allocation
It is a bit strange to see you use STL containers like std::list and std::vector and std::priority_queue, but then use new to allocate the array adj. Why not use a std::vector for that too? For example, like so:
std::vector<std::list<Edge>> adj;

This avoids the need for new, and fixes the memory leak you have because you never call delete. It also allows you to remove the member variable V, since the vector already keeps track of its size.
You can make it a bit easier to read by creating an alias for the list of edges:
using AdjacencyList = std::list<Edge>;
std::vector<AdjacencyList> adj;

Use std::vector instead of std::list
std::vector and std::list can both store a list of elements, but they have different tradeoffs in performance, memory requirements, and other aspects. In your code, you only ever add elements to the back of an adjacency list, you never insert or remove elements from the middle. In that case, a std::vector is a much more efficient data structure, so I would just write:
using AdjacencyList = std::vector<Edge>;
std::vector<AdjacencyList> adj;

Use range-based for loops
Unless you cannot use any features from C++11 or later, I strongly recommend you start using range-based for-loops. They save typing, make the code more readable and reduce the possibility of errors. For example, when iterating over an adjacency list in Graph::shortestPath(), you can write:
for (auto &edge: adj[u]) {
     int v = edge.vertex;
     int weight = edge.weight;
     ...
}

The same goes for printing the contents of dist:
for (auto &distance: dist)
    file << distance << " ";

Check for errors when reading and writing files
A lot of things can go wrong when reading from and writing to files: the files might not exist, be corrupted, you might not have permissions to read and/or write, the disk might get full halfway writing a file, and so on. You should therefore ensure that you have completely read and written files without errors.
You don't have to check every I/O operation; the file objects will remember if an error condition has occured in the past. So the simplest way to get proper error checking is to do this after reading or writing the whole file. This can be done by checking the I/O state bits. In your case, just checking that good() returns true should be sufficient, like so for the input file:
int main() {
    ifstream file("...");
    ...
    if (!file.good()) {
        std::cerr << "An error occured while reading the input!\n";
        return 1;
    }

    g.shortestPath(0);
}

And like so for the output file:
void Graph::shortestPath(int src) {
    ...
    ofstream file("...");
    ...
    file.close();
    if (!file.good()) {
        std::cerr << "An error occured while writing the output!\n";
        // TODO: ensure the error propagates to main, or call exit(1)
    }
}

It is imporant to call close() first here, since the act of closing the stream will ensure its output buffer is completely flushed.
When you detect an error, it is important that you don't continue using any bad data you might have gotten, that you print a helpful error message to std::cerr, and that if your program returns a non-zero exit code. The latter is important in case your program is called from a script for example, so the script won't continue with bogus data.
Move file output out of Graph::shortestPath()
Following the principle of separation of concerns, you should remove the file output functionality from shortestPath(). Instead, make that function return the shortest path, and let the caller write it to disk. This can simply be done like so:
std::vector<int> Graph::shortestPath(int src)
{
    ...
    while (...) {
        ...
    }

    return dist;
}

int main()
{
    ...
    auto path = g.shortestPath(0);
    std::ofstream file1(...);

    for (auto &distance: path)
        file1 << distance < " ";

    file1.close();

    if (!file1.good()) {
        std::cerr << "An error occured while writing the output!\n";
        return 1;
    }
}

You might also consider moving the file input and output into separate functions, so that main() is simplified to something that looks like this:
int main() {
    auto graph = readGraph("C:\\Tests\\21");
    auto path = graph.shortestPath(0);
    writePath(path, "C:\\Tests\123.txt");
}


Designing unit tests for paramiko wrapper

Single responsibility principle

This function does too many things:

maybe it copies a remote file
maybe it prints info

The function may also print timing stats, which probably doesn't make much sense when not copying the remote file.

Unit testing is most effective when testing small independent units that have a single responsibility, well-defined inputs and outputs, and ideally no side effects.

As a first step, it would be good to split this function to multiple smaller functions:

def get_remote_file(filepath, time=False):
    # ...

def get_local_file(filepath):
    # ...

def get_file(filepath, time=False, copy_to_local=False):
    if copy_to_local:
        return get_remote_file(filepath, time)
    return get_local_file(filepath)

def print_file_info(filepath, file):
    # ...

Each of these functions have well-defined, simpler responsibilities.
The get_file function may seem to do multiple things,
but it's ok, as it only orchestrates those things,
it's more of a controller and has trivially simple implementation.

Now that you have smaller units,
you can think about testing them individually, if necessary.
Actually I don't see much to test here,
because of the code is either printing,
or making paramiko API calls.
Testing that the paramiko calls work and you can fetch files will not be unit testing anymore,
because it will require external factors correctly setup,
such as a remote server with a file at a specific location,
which would violate the principle of unit testing.
That is not to say it's not worth testing,
maybe it is, to test your setup,
but it's not "unit testing", it's integration testing.

Code review

There is just one part that might be worth testing:

user = filepath.split(':')[0].split('@')[0]
host = filepath.split(':')[0].split('@')[1]
rfile = filepath.split(':')[1]

I suggest to put this in a function of its own:

def split_ssh_filepath(filepath):
    user = filepath.split(':')[0].split('@')[0]
    host = filepath.split(':')[0].split('@')[1]
    rfile = filepath.split(':')[1]
    return user, host, rfile

And eliminate the repeated calls to filepath.split:

def split_ssh_filepath(ssh_filepath):
    user_host_rfile = ssh_filepath.split(':')[:2]
    user, host = user_host_rfile[0].split('@')[:2]
    rfile = user_host_rfile[1]
    return user, host, rfile


The trick to this problem is that you shouldn't check each number. It takes way too long.

An important thing I noticed is that there's only 3 digits that count. If N is 10, then there are 3 lucky numbers, because there are 3 lucky digits. And if N is 100, then there are 12 lucky numbers, because there are 3*3 combinations of lucky numbers. But there's 12 in total, because we write '01' and '07' and '09' as 1, 7 and 9.

So by looking at each digit of N, we can solve the problem faster.

Have a look at this table, where I wrote all the lucky numbers up to N = 1000.

  1     7     9 = 3
 11    17    19
 71    77    79
 91    97    99 = 12
111   117   119
171   177   179
191   197   199
711   717   719
771   777   779
791   797   799
911   917   919
971   977   979
991   997   999 = 39

Take N = 1000 with lucky digits 2, 7, 9.

This one is easy. 1000 means we score all the 3 digit numbers (which is 3 + 3^2 + 3^3). The first digit does not match a lucky digit, so we are done.

N = 1000 with lucky digits 1, 7, 9 is a tad harder to explain: First, we get all the 3 digit numbers because N is a 4 digit number. Next, since the first digit is a lucky digit, we need to score all the points you can make with the next digit. But because the next digit is not equal to or greater than a lucky digit, that score is 0.

N = 1150 with lucky digits: again, score 39 for having 4 digits. Next, score 150, but without taking the free score for having 3 digits. Since the first digit of 150 is a lucky digit but not greater than a lucky digit, you get 0 times all the 2 digit lucky numbers. So 0. 50, however, starts with 5. 5 is greater than 1, but smaller than 7, so you get 1 * the amount of lucky numbers with 1 digit. N = 1150, score is 42.

N = 1750:

39 points for being 4 digits (3 + 3^2 + 3^3)
1 is not bigger than any lucky digits, so 0 * 3^3
1 is a lucky digit, so continue with the next digit
750 starts with 7, 7 is bigger than 1 but not bigger than 7 or 9, so 1 * 3^2 = 9 points here
7 is a lucky digit, so continue with the next digit
50 starts with 5, 5 is bigger than 1 but not bigger than 7 or 9, so 1 * 3^1 = 3 points here

Makes for a total of 39 + 0 + 9 + 3. = 51.

N = 11:

3 points for being 2 digits (3)
1 is not bigger than any lucky digits, so 0 * 3
1 is a lucky digit, so continue with the next digit
it's the last digit, so count each lucky digit the last digit is equal to or greater than as 1 points - in this case, that's only '1', so 1 point it is

So for N = 11, 4 lucky numbers.

N = 2000:

39 points for being 4 digits (3 + 3^2 + 3^3)
2 is bigger than 1 lucky digit, so 1 * (3^3) = 27
2 is not a lucky digit, so end there

makes 39 + 27 = 66.

Here's a table to check:

   1     7     9 = 3
  11    17    19
  71    77    79
  91    97    99 = 12
 111   117   119
 171   177   179
 191   197   199
 711   717   719
 771   777   779
 791   797   799
 911   917   919
 971   977   979
 991   997   999 = 39
1111  1117  1119 - 3
1171  1177  1179 - 6
1191  1197  1199 - 9
1711  1717  1719 - 12
1771  1777  1779 - 15
1791  1797  1799 - 18
1911  1917  1919 - 21
1971  1977  1979 - 24
1991  1997  1999 = 27 + 39 = 66

So, why does this matter?

Because this algorithm I just explained is about \$O(log n)\$. That is, N = 1000 takes 4 times as long as N = 1. N = 10^12 would take 12 times as long as N = 1.

Your algorithm is \$O(n)\$,  as it checks each number. That means N = 1000 takes a thousand times (1000) as long as N = 1. This means that for the higher cases, your code takes too long, as N = 10^12 means your code takes 1.000.000.000.000 times longer to complete than for N = 1.


// keep track of visited nodes so we don't visit them twice
std::vector<node> visited_nodes;
auto visited = [&visited_nodes] (node n) {
    return std::find(visited_nodes.begin(), visited_nodes.end(), n) != visited_nodes.end();
};

Every time you have to check whether a point has been visited, this is going to scan over the entire list of visited_nodes. Better to do a std::set

// path is currently from end to start, so reverse it
std::copy(path.rbegin(), path.rend(), ret.second);

Rather then constructing the path and reversing it, you could construct the path backwards.

When it comes to constructing all of the child nodes, I think your approach is confusing. You'd be better of constructing a new node rather then reusing the node. As it is, its not clear what you are doing. That section of code is also repetitive. I'd do something like

int x_dir = {0, 0, 1, -1}
int y_dir = {1, -1, 0, 0}

for(int pos = 0; pos < 4; pos++)
{
    node child = parent;
    child.first += x_dir[pos];
    child.second += y_dir[pos];
    ...
}

Other notes:

The use of map is going to O(log), if you use a multidimensional array to hold the information for each point you can do it in O(1) time.

Using pairs to hold co-ordinates is easy. However, I suggest that its better to have a point class with x and y members. I think it makes what is going on clearer. Additionally, the point class can encapsulate the neighboring cell logic.


Aggregate query for drawing temporal statistic

Here your doing something very redondant :

if you move the $match stage at the begining of the aggregation, you no longer need to check wether startTime is null in your project stage:

Plus, a $match stage should always be at the beginning of you aggregation pipeline, as it will reduce the number of documents treated in the next stage.
from MongoDB documentation:

  Pipeline Optimization

  Place the $match as early in the aggregation pipeline as possible.
  Because $match limits the total number of documents in the aggregation
  pipeline, earlier $match operations minimize the amount of processing
  down the pipe.

  If you place a $match at the very beginning of a
  pipeline, the query can take advantage of indexes like any other
  db.collection.find() or db.collection.findOne().

so your query becomes:

db.runs.aggregate([
    {$match: {
        "startTime" : {$ne:null}
    }},
    {$project: {
        "month": {$month:"$startTime"},
        "year": {$year:"$startTime"},
        "nbItem": 1,
        "cleanUp.nb": 1,
        "startTime": 1
    }},
    {$group: {
        "_id": {
            "month":"$month",
            "year":"$year"
        },
        "nbRun": {$sum:1},
        "sumItem": {$sum:"$nbItem"},
        "sumInserted": {$sum:"$cleanUp.nb"}
    }}
])

Now we can push it even further by merging the $project and the $group stage into a single $group stage like this :

db.runs.aggregate([
    {$match: {
        "startTime" : {$ne:null}
    }},
    {$group: {
        "_id": {
            "month": {$month: "$startTime"},
            "year": {$year: "$startTime"}
        },
        "nbRun": {$sum:1},
        "sumItem": {$sum:"$nbItem"},
        "sumInserted": {$sum:"$cleanUp.nb"}
    }}
])

The query should run faster and is now way more readable.

Finally, you can look at the explain() of the query to understand exactly what happens. Make sure that the startTime field is properly indexed.

If the query still does not run fast enough, consider adding the field year and month directly in your documents to get rid of the $year and $month operators


Not much to say I think, but here goes:

You're using clear, descriptive variable names, which is good. Such names make code easier to understand, which is especially important when you're working on large, complex projects.
Calculating the number of demerit points can be simplified to int demeritPoints = speedDifference / 5;.
Your code always displays the demerit points and suspension message, but from the requirements it looks like it should only do so when the speed exceeds the limit.
Instead of writing "SPEED LIMIT : " + speedLimit, you can use an interpolated string: $"SPEED LIMIT: {speedLimit}", which makes formatting a little easier.


This function has very slightly different boundaries, but you may find it does better than what you have right now:

function degreesToOrientation(degrees){
    return 1 + Math.floor(((Number(degrees) + 180 + 11.25) % 360.0) / 22.5);
}

one sixteenth of a circle is 22.5 degrees. centering that is at 11.25 degrees.

So, you add 11.25 degrees to your angle, rotate it a further 180 degrees, Use the Modulo to bring the value back in to range, then divide it by the size of each segment.

This returns a value from 0 through 15 (for the 16 segments). So, add 1 to get your 'orientation'.

It does not care about the degree amount as long as it is greater than -191.25 ... to start with... (the modulo operation is funny with negative numbers...)

Here is a jfiddle


For starter, congratulations, the code is clean and uses rather good constructs. I just have two nitpicks about the layout:

I prefer to indent lists before the first row:

patterns = [
        # 0) 1-12-1963
        r'(\d{1,2})-(\d{1,2})-(\d{4})$',
        # 1) 1789-7-14
        r'(\d{4})-(\d{1,2})-(\d{1,2})$',
        # 2) '1945-2'
        r'(\d{4})-(\d{1,2})$',
        # 3) 2-1883
        r'(\d{1,2})-(\d{4})$',
]

PEP8 recommends two blank lines before top-level function definition.

You can also simplify the boilerplate of a try: … except Something: pass by using the contextlib.suppress context manager instead:

with suppress(ValueError):
    return str(int(date))

Lastly your pattern manipulation:

a match object can return all groups at once using its groups method, no need to special parse them;
you can unpack the groups tuple as arguments to format directly;
you can compile all your regexp beforehand instead of letting the regexp engine do it on-the-fly;
you should associate the output format string to each pattern to remove the need to search back which pattern matched and how it should be processed.

Proposed improvements:

import re
from contextlib import suppress

PATTERNS = [
        # 0) 1-12-1963 => 1963-12-01
        (re.compile(r'(\d{1,2})-(\d{1,2})-(\d{4})$'), '{2}-{1:0>2}-{0:0>2}'),
        # 1) 1789-7-14 => 1789-07-14
        (re.compile(r'(\d{4})-(\d{1,2})-(\d{1,2})$'), '{0}-{1:0>2}-{2:0>2}'),
        # 2) 1945-2 => 1945-02
        (re.compile(r'(\d{4})-(\d{1,2})$'), '{0}-{1:0>2}'),
        # 3) 2-1883 => 1883-02
        (re.compile(r'(\d{1,2})-(\d{4})$'), '{1}-{0:0>2}'),
]

def cleanup(date):
    with suppress(ValueError):
        return str(int(date))

    for pattern, formater in PATTERNS:
        match = pattern.match(date)
        if match is not None:
            return formater.format(*match.groups())
    return date

def main():
    dates = 1858.0, '1-12-1963', '1945-2', '7-2018', '1789-7-14',
    for date in dates:
        print(f'in: {date}, out: {cleanup(date)}')

if __name__ == '__main__':
    main()


Processing files in directories with multithreading

FolderProcessor
if (inputfile.isDirectory()) {
    processFolder(filePath, outputPath + filename);
}

This is why you're not seeing any benefits from parallelism; you're processing subfolders within the same thread!  But even so, you'd be making a new ExecutorService each invocation; pool should be a class-level field:
private final ExecutorService pool;

public FolderProcessor(ExecutorService pool){
    this.pool = pool;
}

After running some tests, I noticed that your path resolution is broken; the path separator isn't being added for subpaths!  You can use all the operating system's rules by switching to Paths:
String filePath = inputFolder.toPath().resolve(filename).toString();

Some quick cleanup and a change to lambda notation (Java 8 is so much cleaner):
class FolderProcessor{
    private static final Logger log = Logger.getGlobal();
    private final ExecutorService pool;

    public FolderProcessor(ExecutorService pool){
        this.pool = pool;
    }

    void processFolder(String inputPath, String outputPath){
        File inputFolder = new File(inputPath);

        for (String filename : inputFolder.list()) {
            String filePath = inputFolder.toPath().resolve(filename).toString();
            String writeTo = new File(outputPath).toPath().resolve(filename).toString();
            if (new File(filePath).isDirectory()) {
                pool.execute(()->processFolder(filePath, writeTo));
            } else {
                pool.execute(()->{
                    log.info("Start processing " + filePath);
                    DocumentWriter.write(filePath, writeTo);
                });
            }
        }
    }
}

Note: My IDE warns me that inputFolder.list() could throw a NullPointerException if the File isn't a directory.  While your current usage ensures that it is, you may want to put in a check down the line.
DocumentWriter
Since we're missing the meat of the method (the contents of the for loop), it's hard to make too many recommendations.  I am concerned with the shift in naming convention (Java uses camelCase), and the lack of checking for errors in file creation.  Also, you create a file and discard it as soon as you've made your checks, when you could save the FileWriter some work by passing it along.
After some cleanup:
class DocumentWriter{
    private static final Logger log = Logger.getGlobal();

    public static void write(String inputPath, String outputPath) {
        try {
            File outputFile = new File(outputPath);
            if(outputFile.getParentFile().mkdirs()){
                outputFile.createNewFile();
                FileWriter outputWriter = new FileWriter(outputFile);

                List<Document> docs = DocProcessor.processDocs(inputPath);
                for(Document doc : docs){
                    // Missing code
                }
            }else{
                // You may want to log this
                log.config("File could not be created: " + outputPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

DocProcessor
I assumed you wanted the typo fixed.  There's not much else to say about this class, since all the logic is either tied up in a class we can't see (TextThread) or omitted.  I will say that if you're running this method in parallel, you're going to be creating an ExecutorService for each invocation, possibly creating hundreds of threads.  A shared ExecutorService, (could be static, but preferably a final instance variable) would be a better solution.
Other Notes
You probably want to use Executors.newWorkStealingPool(10) since it keeps the threads active while waiting for I/O operations, which will give you better performance.  newFixedThreadPool(10) tends to work better for CPU-intensive operations as opposed to I/O-intensive operations.


Let's start with your input parameters, since that is SEDE-specific. Did you know you can add parameter hints to make the experience easier for users? See the SEDE Help Page. So we could do something like this:

-- SearchKeywords: Search for word(s) "No need for quote marks"
DECLARE @search_keywords NVARCHAR(MAX) = ##SearchKeywords:string##;
-- SearchTypeId: post / comment "No need for quote marks"
DECLARE @search_type_id NVARCHAR(MAX) = ##SearchTypeId:string##;##;

That way it looks like this instead, including the little tool tip:

That said, there are some things we could improve. As it stands, when you search for a post there are a few deficiencies in the result set:

No indication whether it is a Question, Answer, or Other type of post.

This is easy to improve. Let's declare two new variables. We will reuse them for your comments query, so let's declare them at the top.

DECLARE @question INT = (SELECT Id FROM PostTypes WHERE Name = 'Question');
DECLARE @answer INT = (SELECT Id FROM PostTypes WHERE Name = 'Answer');

Then we can simply use a CASE statement to add in the type of post, like this:

, CASE
    WHEN PostTypeId = @Question THEN 'Question'
    WHEN PostTypeId = @Answer THEN 'Answer'
    ELSE 'Other'
    END AS [Post Type]

This will show you another deficiency:

Non-Question posts are missing tags!

The reason, as I'm sure you know, is that only Question posts have Tags. What we can do then is use a self-referencing join to get the Tags from the parent questions, again using a CASE statement, like this:

, CASE
    WHEN PostTypeId = @Question THEN Tags
    WHEN PostTypeId = @Answer THEN (SELECT parent.Tags FROM Posts AS parent INNER JOIN Posts AS child ON child.ParentId = Parent.Id WHERE child.Id = Posts.Id)
    ELSE NULL END AS [Tags]

You could break down that one-liner subquery with line breaks, if it makes it easier to read for you.

So we're in pretty good shape for the post search now! Let's look at the comment query.

I think it would be good information to know what kind of post the comment was made on, so why don't we add a join to the Posts table, and get that information from there, using again a CASE statement:

SELECT TOP 10
    Comments.Id AS [Comment Link]
  , Comments.UserId AS [User Link]
  , CASE
      WHEN Posts.PostTypeId = @Question THEN 'Question'
      WHEN Posts.PostTypeId = @Answer THEN 'Answer'
      ELSE 'Other'
      END AS [Post Type]
  , Comments.Score
  , Comments.Text

FROM Comments
INNER JOIN Posts ON Posts.Id = Comments.PostId

Note that I had to reference the tables for each column otherwise it would be an ambiguous join and give you an error.

If you wanted to you could also use the same method as above to get the post tags, although that may not be desired with comments. Also, in both cases, perhaps consider adding the CreationDate field which is useful for sorting.

With everything put together, I came up with this query:

-- SearchKeywords: Search for word(s) "No need for quote marks"
DECLARE @search_keywords NVARCHAR(MAX) = ##SearchKeywords:string##;
-- SearchTypeId: post / comment "No need for quote marks"
DECLARE @search_type_id NVARCHAR(MAX) = ##SearchTypeId:string##;

DECLARE @question INT = (SELECT Id FROM PostTypes WHERE Name = 'Question');
DECLARE @answer INT = (SELECT Id FROM PostTypes WHERE Name = 'Answer');

IF (LOWER(@search_type_id) = 'post')
BEGIN

  SELECT
      Id AS [Post Link]
    , OwnerUserId AS [User Link]
    , Score
    , CASE
        WHEN PostTypeId = @Question THEN 'Question'
        WHEN PostTypeId = @Answer THEN 'Answer'
        ELSE 'Other'
        END AS [Post Type]
    , CASE
        WHEN PostTypeId = @Question THEN Tags
        WHEN PostTypeId = @Answer THEN (SELECT parent.Tags FROM Posts AS parent INNER JOIN Posts AS child ON child.ParentId = Parent.Id WHERE child.Id = Posts.Id)
        ELSE NULL END AS [Tags]
    , CreationDate
  FROM Posts
  WHERE
    LOWER(Body) LIKE LOWER(
      CONCAT('% ', REPLACE(@search_keywords, ' ', '%%'), ' %')
    )
  ORDER BY Score DESC;
END

ELSE IF (LOWER(@search_type_id) = 'comment')
BEGIN
  SELECT
      Comments.Id AS [Comment Link]
    , Comments.UserId AS [User Link]
    , CASE
        WHEN Posts.PostTypeId = @Question THEN 'Question'
        WHEN Posts.PostTypeId = @Answer THEN 'Answer'
        ELSE 'Other'
        END AS [Post Type]
    , Comments.Score
    , Comments.Text
    , Comments.CreationDate AS [Comment Creation Date]
    , Posts.CreationDate AS [Post Creation Date]
  FROM Comments
    INNER JOIN Posts ON Posts.Id = Comments.PostId
  WHERE
    LOWER(Text) LIKE LOWER(
      CONCAT('% ', REPLACE(@search_keywords, ' ', '%%'), ' %')
    )
  ORDER BY Score DESC;
END

ELSE
BEGIN
  PRINT 'SearchTypeId must either be "comment" or "post".';
END


Simple string hashing algorithm implementation

Don't check for NULL pointer argument. The function should expect a valid null-terminated string, it's responsibility of the caller to ensure correct argument.
You don't need to know the string length. Check for null-terminator right in the hash loop.
It's possible to write it shorter and cleaner.

static size_t getHash(const char* cp)
{
    size_t hash = 0;
    while (*cp)
        hash = (hash * 10) + *cp++ - '0';
    return hash;
}

It's not quite clear what do you mean by "ASCII decimal value". Are you referring to this expression in your code: c - '0'? Well, suppose at some moment c == 'Z', so this expression amounts to 'Z' - '0'. If we substitute ASCII codes for these characters, then we get 90 - 48, this is equal to 42 which is ASCII code for '*' character. So you have transformed 'Z' into '*'. Is this somehow supposed to improve the quality of your hash function? I'm in doubt.
Are you aware that for the same expression c - '0' for a number of possible c values (e.g. ' ', '!', and anything with ASCII value less than 48) you will get a negative result and when you add it to the hash it will be sign-extended and converted to a huge unsigned value, something like 0xffffffffffffffxx?
If you are looking for a short and simple hash function then perhaps either of these might work for you.

/* D. J. Bernstein hash function */
static size_t djb_hash(const char* cp)
{
    size_t hash = 5381;
    while (*cp)
        hash = 33 * hash ^ (unsigned char) *cp++;
    return hash;
}

/* Fowler/Noll/Vo (FNV) hash function, variant 1a */
static size_t fnv1a_hash(const char* cp)
{
    size_t hash = 0x811c9dc5;
    while (*cp) {
        hash ^= (unsigned char) *cp++;
        hash *= 0x01000193;
    }
    return hash;
}


Testing individual nodes launched by naught using supertest

I think you should write more code before submitting, the fun part to review is the code that you wrote after the prototype ;)

From a quick once over:

JsHint finds no fault except for some mixed use of tabs and space
Consider 'use strict', it can save lives
Consider something better than console.log, especially if you are going to use this code for performance testing
Use lowerCamelCase consistently: testport -> testPort


My implementation is very similar to yours, with only a few small tweaks:

module Enumerable
  def map_with(accessor, default_value: nil)
    map { |e| e.respond_to?(accessor) ? e.send(accessor) : default_value }
  end
end

Use Enumerable, not Array, so that the method can be applied to other objects such as instances of Hash, Set, etc.
Use respond_to? rather than a type-check against nil, for better duck-typing robustness.
Use a named parameter, for improved code clarity.


Calling a function on an object if not null

To be sure it always works you should add a constraint to the method:

where TInput : class

This will ensure that TInput is a reference type.

It makes no sense to call it on structs. For them, you need another overload with a different constraint and some ? question marks:

public static TResult IfNotNull<TInput, TResult>(
     this TInput? obj,
     Func<TInput, TResult> expression
) where TInput : struct
{
    if (!obj.HasValue) return default(TResult);
    var value = expression(obj.Value);
    return value;
}

Someone may ask at this point: but why do we need two extensions if theoretically a single one does the job too?

Consider this:

((decimal?)2).IsNotNull(x => x.Value * 2)

With a single extension you need to use the .Value property for nullable types. With two extensions you get a clean value so you just do

((decimal?)2).IsNotNull(x => x * 2)

But isn't this just a convenience? Of course it is. Don't we write extensions  exactly for that reason?

As a matter of fact I use a similar code myself:

public static TResult IIf<TArg, TResult>
(
    this TArg arg,
    Func<TArg, bool> predicate,
    Func<TArg, TResult> ifTrue,
    Func<TArg, TResult> ifFalse = null
)
{
    if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); }
    if (ifTrue == null) { throw new ArgumentNullException(nameof(ifTrue)); }

    return predicate(arg) ? ifTrue(arg) : (ifFalse == null ? default(TResult) : ifFalse(arg));
}

but you can create a simplified version of your method and combine it with the IIf

public static bool IsNotNull<TInput>(this TInput obj) where TInput : class
{
    return obj != null;
}

to do this

Person
    .IIf(p => p.IsNotNull(), p => p.User)
    .IIf(u => u.IsNotNull(), u => u.Name, u string.Empty);


Read employee number and salary (exercise to use static keyword)

No.

You use a setter to modify an existing employee. But it makes no sense to change the id and salary together. In fact, you should never change the id of an employee.

This should be the constructor of the class instead. In your main I would expect to see the folowing flow:

Scanner kb=new Scanner(System.in);
int id,sal;
System.out.println("Enter Employee Id: ");
id=kb.nextInt();
System.out.println("Enter Salary: ");
sal=kb.nextInt();
System.out.println("The Values entered are :");
Employee e=new Employee(id, sal);

A second thing to note is that a method with prefix "get" is expected to return some value of the object. Either rename that getValue() method to something like printInfo() or provide actual getters:

public String getId() {
    return id;
}

public static int getNbOfEmployees(){
    return count;
}

These can then be used somewhere else to print out the info, for example in your main:

System.out.println("EmpId = " + e.getId());
System.out.println("Salary =" + e.alary());
System.out.println("Number of employees: = " + Employee.getNbOfEmployees());


Splitting one line into multiple ones given a separator

Why are you first removing the quotes and then putting them back?

And why are you removing the brackets and them putting them back?

This does the same thing, except change ' to ". It also doesn't handle commas in names,
so if you have that it won't work. In that case I'd probably use a regexp.

import sys

ifile = sys.argv[1]
ofile = sys.argv[2]

with open(ifile) as ifile, open(ofile, "w") as ofile:
    for address in ifile.readline().split(","):
        ofile.write(address.strip() + '\n')

Update:

"surname, name <name.surname@example.com>" sucks, and that means your format is inconsistent and not parseable without horrid hacks. In that case your code seems OK, although I'd probably do it differently. I would most likely use a regexp to find all cases of commas that are NOT preceded by > and followed by a space to something else, say chr(128) or something like that. I'd then parse the code with my code above, extract the email from withing the brackets, strip all quotes and brackets from the remander, and replace back chr(128) with commas.

And the lastly write that to the outfile.

The difference there is that I don't try to handle a horrid format, I first try to fix the problems. It makes for cleaner code, IMO.

Update 2:

I instead replaced the commas that should be split on, making it simpler, like so:

import sys

ifile = sys.argv[1]
ofile = sys.argv[2]

with open(ifile) as ifile, open(ofile, "w") as ofile:
    data = ifile.read()
    data = data.replace('>,', '>\xF0')
    for line in data.split('\xF0'):
        name, email = line.split('<')
        email = email.replace('>', '').strip()
        name = name.replace('"', '').replace("'", "").strip()
        ofile.write('"%s" <%s>\n' % (name, email))

and then I realized I could simplify it even more:

import sys

ifile = sys.argv[1]
ofile = sys.argv[2]

with open(ifile) as ifile, open(ofile, "w") as ofile:
    data = ifile.read()
    for line in data.split('>,'):
        name, email = line.split('<')
        email = email.strip()
        name = name.replace('"', '').replace("'", "").strip()
        ofile.write('"%s" <%s>\n' % (name, email))

And as this point I'm basically doing what you are doing, but much simplified.


Letter Combinations of a phone number using a Dictionary

Review

LetterCombinations returns an IList<string> but I see no reason to return a modifiable collection. Consider returning IEnumerable<string> instead.
A method's name should be a verb. Change LetterCombinations to GetLetterCombinations, FindLetterCombinations or PermutateLetterCombinations.
You did good by creating a private function that performs the recursion with intermediate parameters. This way, the user of this API only needs to think about the public endpoint. However, it could have used the same name as the public method. An overload would not resulted in a conflict. The postfix *Function is weird.
Prefer the use of var if the type can be read from code: var lettersMap = new Dictionary<char, char[]>();
You are looking to get familiar with LINQ, however the next statement did not require the LINQ wrapper Count() of a string's Length property: if (sb.Length == digits.Count()).
Use more consistent indentation for your class members.
Having the opening curly brace on the same line is ok, but it's more a convention in Java than in C#, where the opening curly brace is usually on the next line.
See Jesse C. Slicer's answer to move the static data out of the method.

Peculiarities

Did you plan to return the empty result list or throw an exception on this edge case?

if (String.IsNullOrEmpty(digits)){
    return result;
    throw new ArgumentNullException(nameof(digits));
}

The next line is followed by a loop over values but doesn't care whether the operation succeeded:

lettersMap.TryGetValue(digits[pos], out char[] values);

Did you plan to write this instead?

if (lettersMap.TryGetValue(digits[pos], out char[] values))
{
    // ..
}

You are using both char and Char in the next line. Is there a specific reason to use both these types?

Dictionary<Char, Char[]> lettersMap = new Dictionary<Char, char[]>();


Welcome to Code Review! Hopefully you find the feedback here and in other posts useful!
Good things
The code makes good use of const for items that shouldn't be re-assigned (e.g. screen, btnStart, screen, etc.) and let for re-assignable values (e.g. counter, intervalID).
Suggestions
This code uses some ES6 features like arrow functions - thus it could use the class syntax. Until then, each instance of StopWatch has methods defined using this.[method]. This works but isn't as efficient as using the prototype. Such a change might likely require changing local variables to instance variables (e.g. screen => this.screen).
The naming of methods on UI could be more appropriate - e.g. toggleClass would be more appropriate as toggleActiveClass because it toggles the activeBtn class, and removeClass would be more appropriate as removeActiveClass for the same reason.
I see that the Error is thrown when clicking the button with text Start twice, which makes sense, but perhaps the click event handler should only call the function sw.start (as well as ui.toggleClass(this)) if intervalID === 0 - if that is a case then perhaps a public method to determine if the Stopwatch is started is necessary.
I noticed the HTML for the buttons labeled Stop and Reset have attributes on the close tag:

<button type="submit" id="btnStop" class="btn">Stop</button type="submit">
<button type="submit" id="btnReset" class="btn">Reset</button type="submit">

Setting attributes on the closing tags will either be ignored by the browser, or could lead to an error - see answers to this SO question for more of an explanation.


os.walk gives you the filenames already. There is no need to use glob to get them from the OS again. The looping could be done like this:

for path, dirs, filenames in os.walk(usePATH):
    for f in filenames:
        if f.endswith('COMPARE.mat'):
            ...

Updating a GUI can be slow. While I'm not familiar with what you are using, I would try if eliminating update_idletasks from the inner loop speeds it up.


Automatically update one-to-many bi-directional relationship

The best way to accomplish this is to have each World, Structure, and anywhere else a unit can move to inherit an interface IEnterable, which looks like

public interface IEnterable
{
    void Enter(Unit unit);
    void Leave(Unit unit);
}

Your unit would then have this as a property, and a MoveTo(IEnterable location) method

public class Unit
{
     // ...

     public IEnterable CurrentLocation { get; set; }

     // ...

     public void MoveTo(IEnterable location)
     {
         if (CurrentLocation != null)
         {
              CurrentLocation.Leave(this);
         }

         location.Enter(this);
     }
}

The Enter and Leave would handle all the logic for the Unit movement.

If you wanted to get more fancy, you could have a Movement class that could describe the movement a little more accurately.

public class Movement
{
     private readonly IEnterable _destination;

     public Movement(IEnterable destination)
     {
         if (destination== null) throw new ArgumentNullException("destination");

         _destination = destination;
     }

     public MoveResult MoveUnit(Unit unit)
     {
         if (unit == null) throw new ArgumentNullException("unit");

         var currentLocation = unit.CurrentLocation;
         if (currentLocation  == _destination) return MoveResult.SameLocation;

         if (!IsValidMove(currentLocation, _destination) return MoveResult.InvalidMovment;

         currentLocation.Leave(unit);

         _destination.Enter(unit);
     }
}

This will get the movement logic out of the Unit class because a unit should not care about how it has to move, just that it has.

I might be missing something, but my main point is to use an interface for each object that a Unit can enter, and the ease of moving a Unit becomes much better.


Building and getting a form of objects that have multiple properties

Your code is quite ok and I have no idea how to improve this particular piece.

You have used several identical forms and processed it manually. Django have formsets for this purpose. Why don't you use them?

Then I don't see validation in your code. What happens when product_0_width contains not-numeric or empty value? Formsets would solve this problem.


By and large, I think this approach makes sense and has a fine grasp of Python idiom. Nonetheless, if I'm going to go straight CR on this (maybe this should be at https://codereview.stackexchange.com/), I think there is a short list of things that're a little funky.

Local variables don't need to be underscore prefixed -- since they're closed over by the function and can't be published, there's no need to mark them as private. The underscore prefix is normally only used for module-level or class-level names, or, occasionally, for a name that would otherwise shadow a built-in (for example, _id or _list -- but really, you can just rename stuff in that situation).

Your construction of list_of_params (which should be declared with a literal [], btw) adds a couple of extra lines when it should just use dict.update.

list_of_params = []
for combined_param_product in combined_param_products:
    params = {}
    for param_dict in combined_param_product:
        params.update(param_dict)
    list_of_params.add(urllib.urlencode(params))

pytz.UTC.localize is preferable to datetime.replace, although it makes no difference in this situation.

This is totally inconsequential, but it bothers me when I see people doing a if value in CONSTANT_LIST. I just see the O(n) time over and over in my head, and it could just be O(1) if two characters were changed. Of no real importance, but could probably be {"day", "week", "days_28"}.

Oh, and don't raise ValueError -- raise a subclass of it. Your client code will love you forever.

Lastly, this isn't Python-specific, but it seems like there's some factoring out to do. Pretty much any one of these wrappers is going to construct a variable number of param option lists and some urls. I propose:

def _finalize_urls(base_urls, *param_options_lists):
    """
    :type base_urls: list[str]
    :type param_options_lists: tuple[list[dict[str]]]
    :rtype: list[str]
    """
    pass

This function would contain pretty much all of your code after your declaration of date_params, and be invoked by wrappers like so:

urls = finalize_urls(base_urls, base_params, date_params)

Actually, I'd probably even make it a static constructor of RequestManager

return RequestManager.for_urls_and_params(base_urls, base_params, date_params)

Anyway, by and large totally solid.


C# Better structure in my code & any other critiques

Two assumptions (because it is simplet for me with them)

Code works as it should
This code should be prepared to go "the enterprise road" (e.g. we assume many people maintaining it for a long time in the future).

Note belows are opinions only, please do not treat is as a source of truth because your company might have a different guidelines. Since it is C# code I'm trying to stick to MSFT gudielines and, where not possible, with my own preference.
Overall comments

I'm really happy that you provided a working 'ready to run' example.
I think you should start thinking about unit testing your code if you haven't already. Simple unit tests as a start. For example 'does Upvote() increases the score`'.
I really like 'make your functions as short as it is convinient and logical' approach to writing code. Here, it would mean that ideally we would split the main function to a couple of small ones. I would be very happy if you refactored it to small logical functions and posted a new question so we can pick it up from there. I would suggest something similar to the below.

Main(){
    WriteWelcomeMessage();
    var userInput = ReadUserInput();
    var newPost = CreateNewPost(userInput);
    while(val){
        DisplayPost(newPost);
        userInput = ReadUserInput();
        ExecutePostAction(userInput, newPost);
    }
}

Or something similar, I think you get the idea. This can be further split so Main has only two or one function calls.
I consider this approach an implementation of separation of concerns and single responsibility principle.

This is still early in the project but if you would proceed with this as an enterprise application I would suggest reading on dependency injection. Here you can inject classes like reader, writer, postFactory or similar. This will make the testing much simpler in the future.
I highly recommend to include some style checker (e.g. stylecop) this will ensure that you can spot more guidelines issues.

Main function

Don't couple your implementation to Console class. I personally would write a class that would encapsulate writing/reading (or maybe two classes?) so you can easily replace it with for example reading from a WPF textbox or writing to a file.

I strongly believe in descriptive variable naming, variable always should be describing its content. Below variables are IMHO missnamed:

post - should be 'postContent'
val - shouldContinue (?)
inputData - userChoice

If you would rename the variables to be descriptive, you can drop type declarations. string or bool are not giving much context. See here for more info.

Post class

I like that you encapsulated upvoting and downvoting to functions.
Is there any reason why content of the post is not passed through the constructor? This might lead to null reference exception if the user of this class would forget to call AddPostMessage.
I would add private infront of the fields
You could inject a writer class to Post in order to decouple it from Console class.
You could also inject some DateTime provider in order to unit test this class easier.
I prefer using DateTime.UtcNow instead, this makes handling multiple timezones easier.


A few suggestions:

Possibly I’m using the given code incorrectly, but it doesn’t seem to work for me. I defined a send_message() function that would always fail:

class MessageSendFailed(Exception):
    pass

def send_message(msg):
    raise MessageSendFailed

but when I run it, it immediately fails with the following error:

$ python expofailed.py
Traceback (most recent call last):
  File "expofailed.py", line 29, in <module>
    time.sleep(backoff_generator.send(False))
TypeError: can't send non-None value to a just-started generator

Alternatively, if I have a copy of send_message() that never throws an error, I get the same error.
I’m not a big fan of the foo = bar if condition else baz style of Python ternary operator, because it tends towards unreadability by cramming everything onto a single line. I prefer splitting it into an explicit if block like so:

if succeeded:
    num_failed = 0
else:
    num_failed += 1

And now you extend those branches more easily, and write a comment about why each branch behaves it does (because it’s not entirely obvious to me).
Use a better variable name than k as the argument to your function – perhaps interval? Don’t skimp on variable names – characters are cheap.
Your generator should have a docstring and a comment.
You’ve misspelt “succeeded”.


The biggest performance boost you could make would be to issue fewer print() and println() calls.  Each call involves a lot of overhead for locking, which you normally don't think about.  Coalesce everything down to one single print() for optimal performance.

The number of variables isn't that bad.  The problem is, rather, that i, j, k, and n are cryptic and headache-inducing.  The headache remedy would be to introduce a helper function and rename the variables to be more meaningful.  Note that in assigning meaning to the variables, you'll want to reverse one of the i loops to be a countdown, so that i serves the same role in both loops.

public class Triangle {
    public static void show(int maxWidth) {
        // Top
        for (int width = maxWidth; width > 1; width--) {
            System.out.println(repeat(" ", maxWidth - width).append(
                               repeat("* ", width)));
        }

        // Middle and bottom
        for (int width = 1; width <= maxWidth; width++) {
            System.out.println(repeat(" ", maxWidth - width).append(
                               repeat("* ", width)));
        }
    }

    private static StringBuilder repeat(CharSequence block, int n) {
        StringBuilder sb = new StringBuilder(block.length() * n);
        while (n --> 0) {
            sb.append(block);
        }
        return sb;
    }

    public static void main(String[] args) {
        show(5);
    }
}

You could try writing one loop to handle both the top and bottom triangles.  Unfortunately, this clever solution is not as elegant as it could be, due to the need to skip 0.

    public static void show(int maxWidth) {
        for (int i = -maxWidth + 1; i < maxWidth; i++) {
            int width = Math.abs(i) + 1;
            System.out.println(repeat(" ", maxWidth - width).append(
                               repeat("* ", width)));
        }
    }


CSV Creation from two tables with URL for user to click on

One thing that will help is to replace the ArrayList with a List(Of String).  This will eliminate all the calls to ToString every time you want to get the value of an item in the list.  Also you can build the output string as you add the items, rather than iterating over it again.

Dim arrNames As New List(Of String)
With arrNames
    .Add("UPRN")
    str.Append("=" & Chr(34) & "UPRN" & Chr(34) & ",")
    .Add("BuildingNo")
    str.Append("=" & Chr(34) & "BuildingNo" & Chr(34) & ",")
    .Add("Street")
    str.Append("=" & Chr(34) & "Street" & Chr(34) & ",")
    .Add("Postcode")
    str.Append("=" & Chr(34) & "Postcode" & Chr(34) & ",")
    .Add("ItemRef")
    str.Append("=" & Chr(34) & "ItemRef" & Chr(34) & ",")
    .Add("SurveyDate")
    str.Append("=" & Chr(34) & "SurveyDate" & Chr(34) & ",")
    .Add("OverallRiskCategory")
    str.Append("=" & Chr(34) & "OverallRiskCategory" & Chr(34) & ",")
    .Add("SurveyorsComments")
    str.Append("=" & Chr(34) & "SurveyorsComments" & Chr(34) & ",")
End With

Also in this line:

str.Append("=" & Chr(34) & Trim(Replace(If(TryCast(datarow(arrNames(i).ToString).ToString, String), ""), vbTab, " ") & Chr(34) & ","))

The TryCast is redundant since calling the ToString method will always return some sort of a string.


Your fullName() function will return the same result but only when called.  The computed will always have the updated value and can be used as a trigger for other code if needed.  For example, you can subscribe to fullNameComp but you cannot subscribe to fullName as it doesn't extend from KO's observable.

If the function fullName meets your needs then use it.


What is OOP?

There is more to OOP than just class inheritance and your example shows painfully clearly why class hierarchy is almost always completely unable to represent the real world. If a student is a specialized type of a person, then a person can not be a student and a teacher at the same time (e.g. an assistant to a teaching professor). Also, that person can no longer be a part time employee at the cafeteria either, because the person's status has been locked into being a student and student only. Clearly, class inheritance is the wrong tool here. The relation should be composition:

public class Student {
    private final StudentId studentId;
    private final Person person;

    public Student(StudentId studentId, Person person) {
        this.studentId = studentId;
        this.person = person;
    }

    ...
}


Scala BitSet implemented with Java BitSet, for use in Scala Enumerations to replace ValueSet

After studying your code for a good long while, I realized that the reason you haven't gotten an answer is that there isn't really much to say about your code. Well done!

I would recommend adding some thorough ScalaDoc though. It has been my experience that Scala library developers have far too much faith in the ability of library users to magically understand what they really meant. Examples are wonderful things.


Copy directories while excluding or isolating certain extensions

Is the use of global sys.argv in include() and refuse() ok?

At the moment it's not really readable, since sys.argv[4] doesn't say much... This could be solved by using argparse or naming your sys.argv to variables

  How can I handle the different ways a user might use the script in the best possible way? Not quite happy about the if statements in the __main__.

Use argeparse that will relieve the clutter from the if __name__ == '__main__' and make it easier to add optional parameters in your script.

def parse_arguments():
    """Arguments parser."""

    parser = argparse.ArgumentParser(usage='%(prog)s [optional] <source> <destination>',
                                 description='Copy master',
                                 formatter_class=argparse.RawDescriptionHelpFormatter,
                                 epilog='''<your help string>''')

    # Next you can add arguments like this...
    parser.add_argument('source', type=str, help='source directory')
    parser.add_argument('destination', type=str, help='destination directory')
    parser.add_argument('-t', '--types', type=str, help='included types')
    ...

    # Parse the arguments to the object
    args = parser.parse_args()

    # Check if all args are set or something
    if not args.types:
        parser.error('No typyes are specified')
    return args

# Now you can call this from the main
if __name__ == '__main__':
    import argparse
    args = parse_arguments()
    # And call your arguments like...
    # args.source, etc...

Bonus

imports should be at the top of the file!

At the moment when this script is imported to another module, it will not import all dependencies.

Note that you can import argparse in __main__, since this will on be executed from the cli
(Subjective style) You might consider to chop lines for better readability

return [f for f in files if any(f.endswith('.' + x) for x in sys.argv[4].split(',')) and not os.path.isdir(os.path.join(d, f))]

Could be this:

return [file
        for file in files if any(file.endswith('.' + x)
        for x in sys.argv[4].split(','))
        and not os.path.isdir(os.path.join(d, f))]

At your help string consider using a heredoc string

"""Heredoc string""" Or consider setting it as the docstring __doc__ = """Help"""


For proper encapsulation, you want the interface logic to be completely separate from your atomic behaviours like withdrawing funds.

Something to consider: Where are the funds going? In a traditional banking system all operations are done in pairs as an atom. You withdraw from one account and deposit to another account, or into the cash withdrawal ledger, et al.

Your Withdraw method should return a result containing enough information that the caller can determine how to act. This would include whether the operation was successful (and if not, why not). For a simple case, you could probably do this with an enum. The method should take a decimal in (always use decimal for money, since you're concerned with precision and double is an approximate). Your calling routine should handle the validation and conversion, and if necessary the prompt back to the user to enter a valid number.

public enum OpResult = { Complete, Failed_Insufficient_Funds, Failed_Account_Frozen, Failed_Invalid_Amount };

    ...

public OpResult Withdraw(decimal amount)
{
   if (amount <= 0)
   {
       return OpResult.Failed_Invalid_Amount;
   }
   else if (balance - amount < odLimit)
   {
       return OpResult.Failed_Insufficient_Funds;
   }
   ...
   else
   {
       balance -= amount;
       return OpResult.Complete;
   }
}