JavaScript library to notify watchers of changes

Note: this ended up catching a typo instead of fixing what I said below: it was not meant to be executed immediately.

Why do you need something that's effectively an IIFE? Can't you just use:

const watchMap = new Map();

const watch = (objId, obj) => {
    if (isObjWatched(objId))
        throw objectAlreadyWatched(objId);

    watchMap.set(objId, {
        obj: obj,

        onChange: () => {}
    });
};

// ...

module.exports = {
    watch,
    unwatch,
    onChange,
    get,
    set,
    reset
};


Getting death row inmates' last statement

Types
Here:
def clean(first_and_last_name: list) -> str:

list should more specifically be List[str].
Fluent syntax
Consider using fluent syntax for your clean, which - in this case - is basically just a reformat:
    return (
        "".join(first_and_last_name)
        .replace(" ", "")
        .replace(", Jr.", "")
        .replace(", Sr.", "")
        .replace("'", "")
        .lower()
    )


Given a sorted array in increasing order, create a BST of minimum height

Your code will only work one time, because of the static int i in your inorder_traversal function. You have no way to reset i to 0
Splitting creation and filling into two parts is not what I'd call efficient. This way you have to traverse the tree twice: once while creating it and once while filling it. And if you do not depend on a complete binary tree, managing a queue is a wast of time and unnecessary complexity to whom ever is trying to read your code.

My advice would be, work recursive on recursive data. The recursive way is much shorter and much easier to read, isn't it?

node* create_bst(vector<int> const& arr)
{
  return create_bst(arr, 0, arr.size());
}

node* create_bst(vector<int> const& arr, int start, int end)
{
  if (start >= end)
    return null;

  int m = (start + end) / 2;

  node* root = new node(arr[m]);

  root->left = create_bst(arr, start, m);
  root->right = create_bst(arr, m + 1, end);

  return root;
}


Without actually code-golfing, there are still a few shortenings possible:

def ask(n):
    return float(input("Give %s number " % n))

ans = ask("first") + ask("second")
print(int(ans) if not ans % 1 else ans)

This uses a function for asking for the numbers, does not store the intermediate values, uses a ternary expression for printing and the fact that zero evaluates to False.

If you actually want it as small as possible (in bytes), this is a start, but can probably be golfed down a lot further (e.g. by encoding the strings):

a=lambda n:float(input("Give %s number "%n))
r=a("first")+a("second")
print((int(r),r)[r%1>0])

Have a look at the tips for golfing in python.

If you also want to forego the interface:

r=sum(float(input())for _ in"_"*2)
print((int(r),r)[r%1>0])


Calculating and improving time and memory complexity

It is possible to make it much more efficient by using a completely different algorithm. The idea is to take a closer look at prefix sums. Let's assume that a subarray [L, R] is divisible by 3. It means that prefixSum[R] - prefixSum[L - 1] == 0 (mod 3), or prefixSum[R] == prefixSum[L - 1] (mod 3). It results in a simple solution: iterating over all elements of the array from left to right and maintaining the current prefix sum modulo 3 and keeping track of the first occurrence of each value modulo 3. The code can look like this:

int getLongestSubarray(int[] a) {
    int[] firstOccurrence = new int[3];
    firstOccurrence[0] = -1;
    firstOccurrence[1] = a.length;
    firstOccurrence[2] = a.length;
    int prefixSum = 0;
    int result = 0;
    for (int i = 0; i < a.length; i++) {
        prefixSum = (prefixSum + a[i]) % 3;
        if (prefixSum < 0)
            prefixSum += 3;
        result = Math.max(result, i - firstOccurrence[prefixSum]);
        firstOccurrence[prefixSum] = Math.min(firstOccurrence[prefixSum], i);
    }
    return result;
}

The time complexity is O(n) and the space complexity is O(1). It is optimal because it is not possible to find the longest subarray divisble by 3 without seeing all elements of the input array.


Class Design : Parsers for different file type and ParserFactory

The method Parser.fileFormatSupported looks great. Letting each parser declare which file types it can process allows for information hiding. Android uses the same style for deciding the "Which app can handle which file types?" question.
The method Parser.supports uses an inferior style. If you can, you should also switch to a declarative style by replacing this method with Set<Class<?>> getSupportedClasses(). Maybe you only need Class<?> getSupportedClass().
In the supports methods, you currently use isAssignableFrom. This looks wrong to me, since each of these parsers probably only supports exactly this one class. Therefore these methods should return clazz == Device.class.
The CSVToDeviceportServer class is missing the Parser in its name.
In the afterPropertiesSet method, you don't need to check for this.parsers == null. The code will fail in the for loop below. The chances of your custom exception being thrown are close to zero. And even if this.parsers were null, it would be very easy to see in the stack trace.
In the afterPropertiesSet method, you should use a Multimap (from Guava) instead of a HashMap of lists. This makes the code shorter and easier to understand.
Instead of the @PostConstruct method, you may think about having an @Autowired void setParsers(List<Parser> parsers) method that initializes everything. This method is easier to use in unit tests. This method should be package-private since it is not intended to be used by any other code.


I have never written code against a RavenDB, and very seldom use Json (actually, "never" is almost accurate). The way I see it, the classes that end up Json-serialized and persisted to the database, are analoguous to Entities (Entity Framework), or POCO's.

They are part of your data model.

It might seem (/be) code duplication, but if you had a domain model (which might mirror your data model... or not) and a way to "translate" a domain entity to a data entity (and vice-versa), you could very well use an enum in your domain model, and have it serialized as a string.

Basically: the shape of the data shouldn't drive, nor define, the shape of the objects your application is going to work with.

Your business logic (well, the actual game!) should work with the domain model objects, and then you'll have a data access layer that will do its job with RavenDB and Json - the business logic shouldn't be bothered with these concerns.

The Label is a good example of why presentation concerns and data concerns need to be separated: serializing and storing it is a waste, you already have all the necessary information in the other fields.

If you had a domain model Condition, it could have a Label property, with logic to build the string out of the other values.


Magic Numbers

arr = [randint(0, 30) for _ in range(20)]

What are 0, 30, and 20 supposed to represent? I would assign these to variables to make it more clear

Type Hints

This

def swap(array, a, b):

can be this

def swap(array: list, a: int, b: int) -> None:

These allow you to show what types of parameters are accepted, and what types are returned from the functions.

Main Guard

This

arr = [randint(0, 30) for _ in range(20)]
print(arr)
quick_sort(arr)
print(arr)

should be put in a main guard, like so

if __name__ == '__main__':
    arr = [randint(0, 30) for _ in range(20)]
    print(arr)
    quick_sort(arr)
    print(arr)

This prevents this code from running if you decide to import this module from another module/program.


A function that gives you the sequence of month lengths in a given year:

(defn month-seq [year]
  (map
    (if (leap-year? year) leap-year-month-length month-length)
    months))

... is all that your count-number-of-times-day-on-nth-of-month function needs.

I've extended it to accept a year-range as well as day and
date.
I've replaced

flatten with the simpler mapcat and
reduce  with reductions, to simplify the algorithm.

The result is ...

(defn count-number-of-times-day-on-nth-of-month
  [year-range day date]
  {:pre [(>= (first year-range) 1900)]}
  (let [month-lengths (mapcat month-seq (range 1900 (inc (last year-range))))
        day-seqs (reductions
                   (fn [s n] (drop n s))
                   week-days
                   month-lengths)
        first-days (map first day-seqs)]
    (->> first-days
         (drop (+ (* 12 (- (first year-range) 1900)) date))
         butlast
         frequencies
         day)))

For example,

(count-number-of-times-day-on-nth-of-month (range 1901 2001) :sun 0)

Odds and ends

Your zip function (unused) and main function are each missing a pair of parentheses.
If there is only one arity, there is no need for parentheses around
the argument list and body.

For example,

(defn zip
  [coll-1 coll-2] (map list coll-1 coll-2))

Edited to correct a sign error in dealing with the date argument to count-number-of-times-day-on-nth-of-month.


Stack implemented using a single linked list

No, your implementation is broken:

You forgot to check whether allocation succeeded.

Reviewing your code, you are going way overboard following the "small methods"-mantra in your library-code:

While the Single responsibility principle means every function should do one thing, and only one thing, the size of each task should be properly chosen.

Too little, and the function isn't a useful abstraction, using, writing and remembering it takes more effort than it saves.
(The performance-cost may be negligible (or even non-existent), if it is inlined. Consider marking it static to promote inlining and avoid exporting.)

Too much, and reusability and composability suffer.

Header:

I would avoid a typedef for the element-type. What does it buy you?
Using an opaque pointer is a good idea allowing you to replace the implementation with something more performant later. So, well done there.
Consider leaving the parameter-name out of the declaration when it doesn't make it more descriptive.
You should add a variation on stack_push which signals success, so a caller can opt in to handling failure gracefully:

bool stack_tryPush(Stack, StackElement);

Some more useful additions:

StackElement stack_peek(Stack);
StackElement stack_replace(Stack, StackElement);

Sourcefile:

You should re-order your includes: Always include the header you are implementing first, then all other headers, sorted for consistency (use the IDE's sorting-macro).
That way, you will know that your header is self-sufficient and you didn't forget a crucial dependency.
There's abort() for abnormal termination. Consider writing a helper-function if you need to output an error-message and abort in multiple places:

static void die(const char* message);

All your internal functions should not have external linkage, for performance and correctness reasons: Mark them inline.
Putting next first is more common, and possibly slightly more efficient. Also, for a single value value is more idiomatic than data.
Is there any reason why your typedef-name and struct-tag aren't quite equal? That's ittitating.
node_create is a waste: It's literally more work to read, write, and use it than leaving the single use inline.
As a rule of thumb, extracting 2 lines into their own function is a net loss of readability. Exceptons are often-used pieces of code.

Actually, that can be generalized to all your internal functions, with the possible exception of node_delete, which is marginal.
There are two kinds of precondition-checks:

Sanity checks, verifying that the programs logic is sane. These are normally disabled in a release build for performance reasons, and use assert().
Tests of untrusted input. How far you can/should/must trust an API's user must be decided in each case. It's your task as API-designer to decide how much you should penalize your users to catch egregious abuse even in release-mode, and whether there's also a debug-mode.
But there's no excuse for making your internal helper-functions re-assert preconditions even in release-mode.

As you are using C99 (see <stdbool.h>), you can use compound-literals to set all members of a struct-type comfortably even after initialization.

void stack_push(StackCDT *s, StackElement value)
{
    Node *new = malloc(sizeof *new);
    *new = (Node){s->top, value};
    if(!new) die("Failed to allocate a new node.");
    s->top = new;
}

Testprogram:

return 0; is implicit in main since C99.
Any reason for extracting your whole main into a different function?


What do you think of my Recursive FizzBuzz?

It's worth to mention a disadvantage of recursion: the possibility of stack overflow. Calling recurse(1, 6500) throws a StackOverflowError on my machine.
a % 3 == 0 && a % 5 == 0 could be a % 15 == 0. (Deleted, based on @QPaysTaxes's comment.)
recurse isn't a descriptive method name. printFizzBuzz would be better.
Use longer variable names for the parameters which explain the purpose, for example: lowerBound and upperBound.
They're easier to read and maintain.

  Without proper names, we are constantly decoding and reconstructing the
  information that should be apparent from reading the code alone.

(From codesparkle's former answer.)
System.exit isn't the nicest way to stop the recursion. You could use a simple return or omit the whole else block since the method returns anyway.


I don't think you need recursion. Just a simple loop will do. We can just keep a reference to the last element in the document, which we update every time we append a new element, and we keep appending to that.

$tagNames = "this     is a somewhat long string" -split "\s+"
$XML = New-Object System.Xml.XmlDocument

$lastElt = $XML

$tagNames | % {
    $elt = $XML.CreateElement($_)
    $lastElt = $lastElt.AppendChild($elt)
}

$xml.OuterXml # <this><is><somewhat><long><string /></long></somewhat></is></this>

I also changed it to split the string on \s+, which is a regular expression meaning "one or whitespace characters", so that multiple consecutive spaces (or tabs or whatever) will be counted as a single thing as far as -split is concerned.

I change $string to $tagNames because it is important to name variables accurately otherwise you will confuse yourself.


Binary search modification for "swaped" array

General Advise

Your methods are difficult to read because you chose to use predominantly single character variable names. Multi-character descriptive variable names are much easier to associate with a value, making the code magnitudes easier to read & maintain. Also, when implementing a binary search it is typical to use hi, lo & mid as variable names.
Whenever you nest a ternary statements, this should be an immediate red flag, that you are not writing clear & maintainable code. As soon as you write a nested ternary statement I would advise you to pause, and consider what functionality you are trying to achieve and consider different ways to express that functionality. I'm not going to say that nested ternary statements are always a sign that your doing something wrong, but nested ternary statements is always a sign you should stop and think about what your doing.

Algorithmic Advise

I am assuming the algorithm is locating the largest element in a semi-sorted array that has two (and only two) distinctly sorted sequences with a pivot index contains largest value in the array.

The three conditions in your switch case are, generally doing the same thing. Each case is returning the largest element in a the array, but can't use the loop because the array is too small. We can cover these conditions in the final return.
You should also check for general error cases such as null or the empty set (new int[0]) being passed into the function.
Since the logic for checking if the current value of the binary search is the pivot index contains a lot of logic to do correctly, I would create a method isPivotIndex().

Putting all that together, your solution could look something like this.

Java Code: (ideone example link)

int findLargestValueInSemiSortedArray(int arr[]) {
  if(arr==null || arr.length==0)
    throw new IllegalArgumentException();

  int hi  = arr.length; /* exclusive upper bound */
  int low = 0;          /* inclusive lower bound */
  int mid;
  while(low < hi) {
    mid  = low/2 + hi/2;
    if(isPivotIndex(arr,mid))
      return arr[mid];
    if(arr[hi-1] < arr[mid])
      low = mid + 1;
    else
      hi  = mid;
  }
  /* Array was actually sorted, either ascending or descending    */
  /* Note that return this covers corner cases of arr.length <= 3 */
  return max(arr[0], arr[arr.length-1]);
}

int max(final int a, final int b) {
  return (a > b) ? a : b;
}

boolean isPivotIndex(final int[] arr, final int index) {
  int b = arr[index];
  int a = (index > 0) ?            arr[index-1] : Integer.MAX_VALUE;
  int c = (index < arr.length-1) ? arr[index+1] : Integer.MAX_VALUE;
  return a <= b && b > c;
}

The above is much more readable, has fewer lines of code, and is easier to check for correctness.

It immediately throws an exception on invalid input.
It uses isPivotIndex() method to isolate complex logic & maintain a single level of abstraction.
It uses a clever final return to handle corner cases.

Let's consider how the final return covers the corner cases in your original switch statement.

Case 1: (arr.length == 1)

max(arr[0],arr[arr.length-1]) will compare the same values and return arr[0].

Case 2: (arr.length == 2)

max(arr[0],arr[arr.length-1]) will evaluate exactly the same as your ternary statement.

Case 3: (arr.length == 3)

max(arr[0],arr[arr.length-1]) will return the larger of arr[0] and arr[2]. If arr[1] happened to be the max value it would have been the pivot index in the binary search loop and the method would have already returned.


Continuing on Peter Kiss's answer, the static keyword is indeed hard to test, but you don't have to worry about it when it's in a dependency container. If you use Inversion of Control and have your objects ask for a DB connection, rather than getting one, you don't have to worry about using singletons or static class properties – you just let the dependency layer manage connections, and this can be done with a simple static variable inside a closure (see below).

This answer is verbose, because I'm going to assume ignorance and try to explain Dependency Injection in as simple terms as possible (I still haven't found a concise explanation of DI). Afterwards, I'll explain how you can use DI to ensure no more than one DB connection is created.

You need to create a very generic container object to contain dependencies. At runtime, you insert these dependencies into this container (typically before you do anything else). Then, you pass this container to the constructor of any object with a dependency. The object then retrieves the dependency it needs from the container.

This allows the dependent object to be completely ignorant of how the dependency was constructed: e.g. a database object could have been constructed from PDO rather than MySQLi (though you'd want them to share the same API). This aids in making your code much easier to test by keeping object graph construction and application logic separate.

If you're using PHP 5.3+, I'd recommend looking into PIMPLE. Here's how you'd set things up.

// Construct the container and all dependencies
// This is usually done in a separate file

$container = new Pimple();
$container['db'] = function() {
    $db = ...; // Construct the DB connection
    return $db;
}

// Define a class that depends on the DB
class SomeObjectThatUsesDB {
    function __construct($container) {
        $this->container = $container;

        // No `new` keyword – this is a good thing!
    }

    function doSomething() {
        $db = $this->container['db'];
        // Do something with the DB
    }
}

// Use the class to do some work with the DB
$obj = new SomeObjectThatUsesDB($container);
$obj->doSomething();

The advantage here is $container['db'] can be anything as long as it shares the same API.

OK, so now let's talk about ensuring only one DB connection exists at any given time. Since the DI dependencies are just anonymous functions, you can just use the static keyword inside of the dependency definition; however, Pimple makes this even easier by providing a share() method that does this for you. As per the documentation:

  By default, each time you get an object, Pimple returns a new instance
  of it. If you want the same instance to be returned for all calls,
  wrap your anonymous function with the share() method

Here's what it looks like:

$container['db'] = $container->share(function($container) {
    $db = ...; // Construct the DB connection
    return $db;
});

This will make sure that sure only one $db is ever created. Here's the source code from Pimple's share() method for demonstration purposes:

/**
 * Returns a closure that stores the result of the given closure for
 * uniqueness in the scope of this instance of Pimple.
 *
 * @param Closure $callable A closure to wrap for uniqueness
 *
 * @return Closure The wrapped closure
 */
public static function share(Closure $callable)
{
    return function ($c) use ($callable) {
        static $object;

        if (null === $object) {
            $object = $callable($c);
        }

        return $object;
    };
}


Is my code thread safe? If not, how do I make it thread safe?

No, of course it's not thread-safe. You don't do anything to make it thread-safe.

A more nuanced answer would be: It's thread-safe as long as you don't use it in an unsafe way. For example, calling Logger::log(FATAL, "hello world") from two different threads concurrently would of course be unsafe. But if your program has only one thread... :)

If you want to allow calling Logger::log from two threads concurrently, you'll have to do something to eliminate the data race on m_logfile which is caused by the two threads' both calling m_logfile << levels[static_cast<int>(s)] at the same time. For example, you could throw a mutex lock around addLog.

  Is there a way to make the interface a bit cleaner for use? Right now #define feels a bit hacky.

The only place you use #define is in #define FATAL Logger::Level::Fatal and so on. (By the way, technically #define ERROR ... triggers undefined behavior, because all macros of the form EXXXX are reserved for use by POSIX error codes.) My question is, if you wanted these values to be referred to as FATAL, ERROR, etc., why didn't you just declare them that way?

inline constexpr int FATAL = 0;
inline constexpr int ERROR = 1;
inline constexpr int WARNING = 2;
// ...

Or, probably better:

namespace Logger {
    enum Level {
        FATAL, ERROR, WARNING, // ...
    };
}

Making this an enum (rather than an enum class) allows your user to refer to the enumerators without needing to redundantly name the enum type: just Logger::FATAL, Logger::ERROR, et cetera.

Personally, I would consider writing convenience functions to eliminate the boilerplate:

namespace Logger {
    void log_fatal(const std::string& msg) { log(FATAL, msg); }
    void log_error(const std::string& msg) { log(ERROR, msg); }
    // ...
}

By the way, I think your numbering scheme is backwards. "Level" represents the severity of the message, right? Some messages have higher severity than others? So how would I test whether one message had a higher severity than another? Well, I think I'd write:

if (one_severity > another_severity) ...

But with the values you gave your enumeration, this is actually going to be completely backwards! And so my code for testing severity levels is going to have a bug (or else I'll catch the bug, but then have to write unintuitive code that uses < to mean "greater than"). So, I recommend switching the values around.

  Is there a way to avoid the use of a global unique_ptr?

Sure; declare it static! And to make it really non-global, stick it in a function. It'll still have static lifetime, though. There's not much getting around that.

inline Log *get_glog() {
    static std::unique_ptr<Log> glog = std::make_unique<Log>();
    return glog.get();
}

void startLog(const std::string& filepath) {
    Log *glog = get_glog();
    glog->set_filepath_and_open(filepath);
}

  Should I just make it a header only library? Is there any benefits in doing so?

The big benefit of a header-only library is that it's super easy to incorporate into another project — the user just drops the header file into his include/ directory and he's good to go.

Single-header libraries are particularly nice because they can easily be dropped into Godbolt or Wandbox.

In your case, the tradeoff is that presumably this header is going to get included all over the place (because logging is ubiquitous), and so the bigger you make it, the more work you're forcing the compiler to do in every translation unit.

Since you said "C++17", consider rewriting all your void foo(const std::string& s) signatures into void foo(std::string_view sv) signatures. (Yes, pass string_view by value.)


PHP ideal way to check function returns true

Actually, both methods assign the value first before comparing its value. Therefore, in terms of efficiency, there's no difference.

For code readability, you could write extra parentheses around the assignment if you choose method A. Method B has a slight advantage when you have to perform debugging before the branch, i.e.:

$res = $db->getResult(95);
var_dump($res); // added for debugging without having to move the code out of the condition
echo $res ? $res : 'fail';

The ternary operator I've used above is yet another way to do your branching; its efficiency is in the same ballpark though. Since the variable itself is used solely in the truthy branch you can also use the shortened ternary operator (>= 5.3) like so:

echo $res ?: 'fail';

Although ternary operators are a powerful concept, they're easy to abuse as well and can cause either bugs or a WTF during code review. My personal guideline is to start favouring an if/else construct when either the condition has multiple sub-expressions or when the manual is opened under operator precedence.


Optimizing matrix multiplication algorithm

I have to admit I'm a bit confused, you did the hard parts and have a question on the easy parts? I might be misunderstanding your question.

I am also keen on understanding how I can make it robust such that it doesn't crash when non-rectangular matrices are passed as argument i.e. matrix that has uneven number of elements in different Vds it holds.

You could validate that you have a well formed matrix by
inline bool isValid(const Md& mat)
{
    if (mat.m.size())
    {
        int size = mat.m[0].v.size();
        for (int i = 1; i < mat.m.size(); i++) {
            if (size != mat.m[i].v.size())
            {
                return false;
            }
        }
    }

    return true;
}

and incorporating it into the matrixDot function for validation similar to the shape validation you have right now
    if (m1.m[0].v.size() && m2.m.size())
        if (m1.m[0].v.size() != m2.m.size())
        {
            LOG("Shape mismatch: " << "matrix1 columns: " << m1.m[0].v.size() << ", " << "matrix2 rows: " << m2.m.size());
            throw std::exception();
        }

    if (!isValid(m1))
    {
        LOG("Invalid matrix :: " << std::endl);
        std::cout << m1;
        throw std::exception();
    }

    if (!isValid(m2))
    {
        LOG("Invalid matrix :: " << std::endl);
        std::cout << m2;
        throw std::exception();
    }

Any optimizations I can think of are around utilizing std::array instead of std::vector as you are aware of row and column lengths at time of creation.


Improving performance of Ruby socket programming

You shouldn't read from the client one byte at a time.  Call client.gets to take a line at a time.


this is already simple, it follows Devise wiki: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update

but if you really want to make it shorter and remove "if" you can use skip_before_filter on controller level, i.e.

class AccountsController < ApplicationController
  skip_before_filter :store_last_page, only: [:new, :index]


Is this the right way to handle Exceptions in PHP?

You are using Exceptions correctly, however its possible to catch more than one type of exception with the same try block. Instead of specifically catching the LinkException in your logging routine, you should probably just catch any Exception, but prefix the error string with the Exception's class.

I also recommend putting the declaration of the $link object inside the try block in case the Url class throws an exception from inside the Link class's constructor.

try {
    // execute code
    $foo = new Foo();
} catch ( \Exception $e ) {
    // log exceptions
    $logger->add( get_class( $e ) . ': ' . $e->getMessage() );
}

Push your logging as high up in your application as possible so you are collecting all exceptions, not just your custom ones.


Don't use a bare except statement if it's not absolutely necessary. Catch the errors you anticipate and explicitly want to handle.

Also, there's no reason for the duplicated try/except/else statements, and no use, in this case, of the else statements at all. You can collapse everything into a single try/except, since you do the same thing regardless of which line throws the error.

You also have a little code duplication. Don't Repeat Yourself (DRY).

def get_names(link):
    res = requests.get(link)
    soup = BeautifulSoup(res.text,'lxml')
    for content in soup.select(".row-fluid"):
        try:
            element = content.select_one(".span5 b")
            name = element.get_text(strip=True)
            title = element.next_sibling.next_sibling.strip()
            print(name,title)
        except AttributeError:
            continue


Given entrance and exit logs, find the population maximum

Algorithm
I don't understand the purpose of comparing the timestamp of the next datum here:

if (i < len(data)-1 and data[i][0] == data[i+1][0]):
  continue

The two events happened during the same second, but it's reasonable to assume that they are ordered, and therefore we should consider the total within that single second, unless the problem statement says otherwise.
Without that constraint, we have no need for the index i, and can consider just the members of the input data; we can give the elements meaningful names:
  for time,quantity,direction in data:

Now, we know we won't find a new maximum when people are exiting (assuming we're not given negative numbers of people), so we can move the test into the += branch:
    if direction == 1:
      # Some people entered
      people += quantity
      # Have we reached a new maximum?
      if people > max_people:
        max_time, max_people = time, people
    elif direction == 0:
      # Some people left
      people -= quantity
    else:
      raise ValueError(direction)

General review

PEP8 recommends four spaces per indent level.

This doc-comment is both incomplete and incorrect:

"""
output: 1487800378 # since the increase in the number of people
                   # in the mall is the
"""

The doc-comment is in the wrong place (it should be just within the function body).

We should use a main guard.

Consider using doctest to provide more test cases.

Improved code
def find_busiest_period(data):
    """
    Find the timestamp when the greatest number of people
    are in the building.

    >>> find_busiest_period([]) is None
    True

    >>> find_busiest_period([ [0, 0, 2] ])
    Traceback (most recent call last):
        ...
    ValueError: 2

    >>> find_busiest_period([ [0, -5, 0] ])
    Traceback (most recent call last):
        ...
    ValueError: -5

    >>> find_busiest_period([ [0, 5, 1], [2, 5, 1], [3, 5, 0] ])
    2

    >>> find_busiest_period([ [1487799425, 14, 1], \
                              [1487799425, 4,  0], \
                              [1487799425, 2,  0], \
                              [1487800378, 10, 1], \
                              [1487801478, 18, 0], \
                              [1487801478, 18, 1], \
                              [1487901013, 1,  0], \
                              [1487901211, 7,  1], \
                              [1487901211, 7,  0] ])
    1487901211
    """
    people = 0
    max_time = None
    max_people = 0

    for time,quantity,direction in data:
        if quantity < 0:
            raise ValueError(quantity)
        if direction == 1:
            # Some people entered
            people += quantity
            # Have we reached a new maximum?
            if people > max_people:
                max_time, max_people = time, people
        elif direction == 0:
            # Some people left
            people -= quantity
        else:
            raise ValueError(direction)

    return max_time

if __name__ == "__main__":
    import doctest
    doctest.testmod()


Combining arbitrary number of lists inside json

First

but without forEach not able to return a value i'm struggling for a succinct solution.

Addressing this in your post, in the future it may help to know you can use the .map() function, which does return values to an array, unlike forEach()
an example using .map() and what you have:

const config = {"levels": {"first": ["a", "b", "c"], "second": ["d", "e", "f"]}};
const accessor = config.levels

let combine = Object.keys(accessor).map(key=>{return accessor[key]});
let levels = [].concat.apply([], combine);

console.log(levels);
// levels == ["a", "b", "c", "d", "e", "f"]

More Succinct Solution
That said, something like this may be what you're looking for:

const config = {"levels": {"first": ["a", "b", "c"], "second": ["d", "e", "f"]}};
const accessor = config.levels

const combine = Array.prototype.concat(...Object.values(accessor));
console.log(combine)

NOTE 1: Accessor is pulled out in case it needs to change, but is not necessary


Processing text files for data extraction and analysis

I think your program needs to be more Haskell-style (and shorter). Here is my rewrite:

import qualified Data.ByteString.Lazy.Char8 as L

processContents :: L.ByteString -> L.ByteString
processContents contents = L.unlines out
    where out = zipWith f [1..] (L.lines contents)
          sep = L.pack ";"
          f n l = l `L.append` sep `L.append` L.pack (show n)

main = do
    contents <- L.readFile "myfile.csv"
    L.putStr (processContents contents)

Need better speed? It is trivial to convert this code into parallel one.

import qualified Data.ByteString.Lazy.Char8 as L
import Control.Parallel.Strategies
import GHC.Conc(numCapabilities)

processContents :: L.ByteString -> L.ByteString
processContents contents = L.unlines (out `using` parListChunk chunks rdeepseq)
    where out = zipWith f [1..] (L.lines contents)
          sep = L.pack ";"
          f n l = l `L.append` sep `L.append` L.pack (show n)
          chunks = 1 + (length out `div` numCapabilities)

main = do
    contents <- L.readFile "myfile.csv"
    L.putStr (processContents contents)

To compile it use the following command:

ghc -O2 -threaded -with-rtsopts=-N program.hs


Randomly pick a host from a list, subject to an uptime requirement

Naming

by calling pickRandomMachine() where I pass a List<MachineInfo> I would assume that I will get a MachineInfo. Better name it to getRandomMachineHostName()
if you name the parameter holding the List machines you should rename info to machine.
hostname should be hostName, because it is camelCase casing for variable names.

General

A Random should be created once and be reused.
You should place and use the String hostname inside the loop, to remove the need to accessing machine two times.
You should extract the shuffeling of the machines to a separate method.
By returning out of the loop we can reverse the if condition

Refactoring

Implementing the above will lead to

public static String getRandomMachineHostName(List<MachineInfo> machines) {

    shuffleMachines(machines);

    for (MachineInfo machine : machines) {
        String hostName = machine.getHostName();
        if (checkHostUptime(hostName)) {
            return hostName;
        }
    }

    return null;
}

private static Random random = new Random(System.nanoTime());
private static void shuffleMachines(List<MachineInfo> machines) {
    Collections.shuffle(machines, random);
}


First, at the top you list all the consonants out. There are two things that can be improved here:

Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the [] with {}.

consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}

Second, there's a slightly less painful way to generate those letters. Python's string module contains a ascii_lowercase built-in that holds 'abcdefghijklmnopqrstuvwxyz'. You can use that along with a set of vowels to limit what letters need to be hard-coded:

import string as s

vowels = {'a', 'e', 'i', 'o', 'u'}
consonants = set(s.ascii_lowercase) - vowels  # Consonants are the set of letters, minus the vowels

I personally prefer this way.

You could also just change your algorithm to use vowels directly.

Just to clear something up,

word_copy = word

does not create a copy of word. This just creates a second name for the word string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:

my_list = []
list_copy = my_list  # Does not actually create a copy!
my_list.append(1)
print(my_list, list_copy)  # prints [1] [1]

Notice how both lists were added to. This happens because there's actually only one list. Both names are referring to the same list.

For the sake of clarity, I'd rename it to say what it's purpose is. Offhand though, I can't see the need for word_copy at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at word_copy[0], and since you never reassign word, you could just do word[0]. I'd simply get rid of word_copy.

Along the same lines, I'd reconsider ay. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:

pig_latin_suffix = ['a', 'y']

I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:

" ".join(['a', 'y'])
'a y'

" ".join("ay")
'a y'

Strings are iterable just like lists are.

I think pig_latin is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:

def process_word(word):
    ay = ['a', 'y']
    listed_word = list(word)
    word_copy = word
    moved_consonants = ''

    for letter in listed_word.copy():
        if letter.lower() == 'y':
            if letter in word_copy[0]:
                moved_consonants += letter
                listed_word.remove(letter)
            else:
                break
        elif letter.lower() in consonants:
            moved_consonants += letter
            listed_word.remove(letter)
        else:
            break

    listed_word.append('-' + moved_consonants + ''.join(ay))

    return ''.join(listed_word)

def pig_latin(message):
    new_message = ''

    for word in message.split():
        processed_word = process_word(word)

        new_message += processed_word + ' '

    return new_message

process_word could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:

print(process_word("Can"))  # Prints 'an-Cay'


Follow standard identifier conventions.  Variable are lower_case, class names should be CamelCase, and constants should be UPPER_CASE.  With this in mind, your block of colours at the start should be altered:

# Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#... etc ...

Named colours are fine, but what are you using them for?  Maybe, after naming colours, name some of the usages, and assign the named colours.

BALL_COLOUR = RED
SCORE_COLOUR = WHITE

Note the spacing above.

ux+=ax*t
uy+=ay*t
x+=ux*t
y+=uy*t

... I find hard to read.  Add a space before and after operators, a space after commas, etc.

ux += ax * t
uy += ay * t
x += ux * t
y += uy * t

... is much easier to read.

score, lives=0,3

Tuple unpacking assignment is a wonderful feature.  But don’t use it for unrelated values, like score and lives.  Use two separate assignment statements. But when you do use it, remember spaces around the equals, and after the commas.

Declare variables as close as possible to where you use them.  What is this running = True statement, near the start?  Is there someone walking and running as well as bouncing a ball?

running = True
while running:
     # ...

This is much clearer.  The value controls the loop.

Watch for “if condition, do something, else if different condition, do same thing”.  Use an “or” in the test.

if ev.key == pygame.K_UP or ev.key == pygame.K_DOWN:
    ay = 0

Don’t intermix unrelated code.

textDisp = ...
pygame.draw.circle(...)
display.blit(textDisp, ...)

Keep the two textDisp lines together; the circle draw code is unrelated and should be moved before or after this code.

Elephant in the room:  Variable names. They are terrible.  I’d suggest better ones, but I’d suggest using classes for player/projectile even more.  And maybe a function or two for organization. But as this is your third project, I don’t want to confuse you with constructs you may not have learned yet.

Let us know what you know, and perhaps we can help further.

Inefficiency: repeating the same test 20 times.  Both y and yp1 remain constant in this loop:

for g in range(20):
    if x>xp1[g]-10 and x<10+xp1[g] and y>yp1-15 and y<yp1+15:

Instead, check for a y-collision first, and only if it is a possibility, then check the 20 x-collisions.

if y > yp1 - 15  and  y < yp1 + 15:
    # loop over all xp1 values

Hard-coded numbers. You repeat 20 multiple times throughout the code.  What if you want to change that?  Find every place it is used and change it?  Better: use a variable for num_projectiles.  Even better, just iterate over the storage structure itself:

if y > yp1 - 15  and  y < yp1 + 15:
    for xp in xp1:
        if x > xp - 10  and  x < xp + 10:
            # collision code


Caching an integer - distinguishing no value from zero

Your current method is slightly violating SRP, it's both checking is a cache exists, and creating one if needed. I'd prefer to separate the two:

public int GetData(string cacheKey, Func<int> getDataCallback)
{
    int? cachedData = (int?)HttpContext.Current.Application[cacheKey];

    return cachedData.HasValue
                        ? cachedData.Value
                        : CreateCache(cacheKey, getDataCallback);
}

private int CreateCache(string cacheKey, Func<int> getDataCallback)
{
    int intData = getDataCallback();
    HttpContext.Current.Application[cacheKey] = intData;
    return intData;
}

The first method only checks the existing cache and, if missing, calls the second method, which will create a new cache.

The code could be refactored to slightly shorten it, but that would be at the cost of readability.
I renamed GetOrSet to GetData for clarity's sake. The method exists to give you the data, regardless of whether it's cached or created on the fly. Pedantically, you'd need to name it Get_or_SetAndThenGet for it to be an accurate description. I prefer GetData, it sticks to the important facts and remains concise.
Nkosi is also correct in the comments that you should ideally abstract this snippet away from using HttpContext, but that's not necessary for the question at hand.

Note that you could also stop using int? if you find it confusing:

public int GetData(string cacheKey, Func<int> getDataCallback)
{
    object cachedData = HttpContext.Current.Application[cacheKey];

    return cachedData != null
                        ? (int) cachedData
                        : CreateCache(cacheKey, getDataCallback);
}


Elegant Method for Sleeping with Selenium Webscraper

WebDriverWait

Your intuition about time.sleep() not being ideal here is correct. A better alternative is to use the Selenium WebDriverWait API to wait for elements of interest to appear/disappear. More specifically,

after entering a query in the query field, we want to wait for the list elements to show up in the DOM so we can retrieve the first element
after clearing the query field, we want to wait for any of the aforementioned list elements to disappear from the DOM, as a sanity check to ensure we've reset the page to a state that is ready for our next query

For waiting for the elements to show up in the DOM, we can use presence_of_all_elements_located:

first_element = WebDriverWait(driver, 5).until(
    EC.presence_of_all_elements_located(
        (By.XPATH, "//div[@class='_0ea0377c _4343c2a0 _50f34a35']")
    )
)[0]
ticker = first_element.text

For waiting for any of the above elements to disappear from the DOM, we can use staleness_of or invisibility_of_element_located:

WebDriverWait(driver, 5).until(EC.staleness_of(first_element))

# also works, but we're repeating ourselves a bit here
WebDriverWait(driver, 5).until(
    EC.invisibility_of_element_located(
        (By.XPATH, "//div[@class='_0ea0377c _4343c2a0 _50f34a35']")
    )
)

Query field: retrieve once then reuse

  for isin in isin_list:
    try:
        WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))).send_keys(f"{isin}")

We only need to wait for the search query field to become clickable once. So we can move the WebDriverWait line outside of the loop and save its return value (reference to the query field element) in query_field:

query_field = WebDriverWait(driver, 5).until(
    EC.element_to_be_clickable((By.XPATH, "//input[@name='yfin-usr-qry']"))
)
for query in queries:
    try:
        query_field.send_keys(query)
    # ...

Incorrect assumption about modal always appearing

  driver.find_element_by_xpath("//button[@type='submit' and @value='agree']").click()

This appears to handle a pop-up modal by clicking past it, but I don't think the modal shows up all the time. When I ran the original script the above line threw a NoSuchElementException.

To handle the case when the modal doesn't appear, ignore NoSuchElementException when it is raised from that line:

try:
    driver.find_element_by_xpath(
        "//button[@type='submit' and @value='agree']"
    ).click()
except NoSuchElementException:
    pass

Use None to represent the absence of a value

  If there is no suggestion the code should write f"nan_{what_ever_the_entry_was}".

I would highly recommend against doing this. Instead, use None to represent the absence of a value (see typing.Optional).

get_ticker_symbols would then return a List[Optional[str]], which is a clear way of expressing in the function signature that it is possible for a search query to return an "empty" result.

As for the current function signature,

  def get_ticker_symbols(isin_list: List) -> List:

this can be improved by specifying the types of elements in each list:

def get_ticker_symbols(queries: List[str]) -> List[Optional[str]]:

Also, isin_list is not a very descriptive name and it almost sounds like a boolean, which is misleading, so I'd go with something like queries instead.

Specify the exceptions you are handling

Avoid using bare except clauses, which catch all exceptions and can obscure/hide real issues or bugs. Instead, specify the exception you are handling:

try:
    # some code that could throw a `TimeoutException`,
    # e.g. `presence_of_all_elements_located`
except TimeoutException:
    # ...

Close resources after use

It's a good idea to call close() or quit() on the WebDriver to exit the browser once we're done using it. That said, if we invoke the WebDriver as a context manager, we don't have to worry about this:

with webdriver.Chrome(options=options) as driver:
    driver.get("https://finance.yahoo.com/")
    # ...

Selenium allows us to invoke the WebDriver as a context manager as shown above, which means we don't need to call driver.close() or driver.quit() explicitly because it will be done for us when the flow of execution leaves the indented block.

Refactored version

#!/usr/bin/env python3

from typing import List, Optional

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("headless")

def get_ticker_symbols(queries: List[str]) -> List[Optional[str]]:
    with webdriver.Chrome(options=options) as driver:
        driver.get("https://finance.yahoo.com/")

        try:
            driver.find_element_by_xpath(
                "//button[@type='submit' and @value='agree']"
            ).click()
        except NoSuchElementException:
            pass

        query_field = WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable(
                (By.XPATH, "//input[@name='yfin-usr-qry']")
            )
        )
        ticker_list = []
        for query in queries:
            try:
                query_field.send_keys(query)
                first_element = WebDriverWait(driver, 5).until(
                    EC.presence_of_all_elements_located(
                        (
                            By.XPATH,
                            "//div[@class='_0ea0377c _4343c2a0 _50f34a35']",
                        )
                    )
                )[0]
                ticker = first_element.text
            except TimeoutException:
                ticker = None

            ticker_list.append(ticker)
            # web_element.clear() doesn't fire any keyboard events, and
            # as a result the change to the text field isn't registered
            # as we would expect. So as a workaround, we delete the query
            # via Keys.BACKSPACE
            query_field.send_keys(Keys.BACKSPACE * len(query))
            WebDriverWait(driver, 5).until(EC.staleness_of(first_element))

    return ticker_list

if __name__ == "__main__":
    queries = ["GB00BD2ZT390", "bmw", "dasdas", "nike", "GB00BK8FL363"]
    print(get_ticker_symbols(queries))

Alternative solution: Use undocumented API

This is a bit out of scope for this code review, but I do think it deserves a mention. Simply put, there is an even better way of doing all of this without using Selenium or other web scraping libraries.

Using something like Chrome Developer Tools, we can track the XHRs made when typing in the search field and figure out which API call is providing the data we care about.

In this case it's an undocumented API https://query1.finance.yahoo.com/v1/finance/search which we can call directly with requests:

#!/usr/bin/env python3

import requests

from typing import Any, Dict, Optional, List

def get_ticker_symbols(queries: List[str]) -> List[Optional[str]]:
    def get_params(query: str) -> Dict[str, Any]:
        return {
            "q": query,
            "lang": "en-US",
            "region": "US",
            "quotesCount": 1,
            "newsCount": 0,
            "enableFuzzyQuery": False,
        }

    ticker_list = []
    with requests.Session() as session:
        for query in queries:
            response = session.get(
                "https://query1.finance.yahoo.com/v1/finance/search",
                params=get_params(query),
            )
            response.raise_for_status()
            quotes = response.json()["quotes"]
            ticker_symbol = quotes[0]["symbol"] if quotes else None
            ticker_list.append(ticker_symbol)

    return ticker_list

if __name__ == "__main__":
    queries = ["GB00BD2ZT390", "bmw", "dasdas", "nike", "GB00BK8FL363"]
    print(get_ticker_symbols(queries))


There is a simple efficient solution for this problem which uses the following observation: if \$ A ⊆ B \$, then \$ \gcd(A) ≥ \gcd(B) \$. Proof: if \$ g = \gcd(B) \$ then \$ g \$ divides all elements of \$ B \$. But all elements from \$ A \$ are in \$ B \$, thus \$ g \$ divides all elements in \$ A \$. Hence, \$ \gcd(A) ≥ g \$.

This means that we can simply check that the GCD of all elements of the given array is \$ 1 \$.

What about duplicates? They don't matter because they do not affect the value of the greatest common divisor.

How to compute the GCD of an array? We can use the following property: $$ \gcd(a_0, a_1, a_2, \dotsc, a_{n - 1}) = \gcd(\gcd(a_0, a_1), a_2, \dotsc, a_{n - 1}). $$ To compute the GCD of two numbers one can use Euclid's algorithm.

The time complexity is \$ O(n + \log \max A) \$, where \$ \max A \$ is the maximum element of the array \$A\$.


Url building

$id = $row['id'];
$word = rawurlencode(getName($row['name_eng']));
//getName is a simple function which does some trimming and cleaning up of string
$url = 'https://www.google.com/inputtools/request?text='.rawurlencode($word).'&ime=transliteration_en_te&id='.rawurlencode($id);

Could be simplified with the use of http_build_query() with encoding type PHP_QUERY_RFC3986 to replace the rawurlencode:

$row['text'] = getName($row['name_eng']);
//unset $row['name_eng'] or select it as "text" in the SELECT statement
$row['ime'] = 'transliteration_en_te'; //or move into SELECT fields in query?
$url = 'https://www.google.com/inputtools/request?'.http_build_query($row, '', '&', PHP_QUERY_RFC3986);

Obviously that will likely result in extra parameters tacked onto the URL (e.g. word_indic, word_eng). You could update the select query to specifically select those fields:

$q = "SELECT id, name_eng as text from $table where word_indic is null limit 500000";

And you could select that ime parameter as a hard-coded value, so as to not need to assign it to each row in the while, but then that would make the result set larger...

Global variables

I see this line:

global $conn; global $table; global $urls; global $n;

In general it isn't a good habit to be referencing variables globally. Obviously this is in the context of a callback function but there are ways to avoid that. I would suggest creating a wrapper class and storing the connection, table and other info in member/instance variables while calling the method using the array syntax.

The Singleton Pattern could be used to create a wrapper class on the database code and call a static method to get a connection to the database, instead of referencing $conn globally.

Also, $urls and $n don't appear to be used after that line anyway...


As requested on vi.SE, here is my little view.
First, I see a great quality in most patterns you have used: autoload plugin, plug-mappings, and so on. Good work!
If I really had to nit-pick, it would be that:

I find l: prefix to be cumbersome and useless in many situations
I like to annotate my functions with abort in order to simplify error messages in case I'd introduce errors in future versions. abort should have been the default, but unfortunately, this is not the case.
"\<Esc>" and "\<ESC>" and "\<eSc>" are the same character, using a case-insensitive comparator doesn't really make any sense. !=# would make more sense. I have an old habit, personally I simply use != ^^'

Regarding your question regarding finally, it could make sense to make sure to reset the highlighting used with :echo in case make_status_line() could fail. I don't see any other place where it could make sense.
Regarding catch around <c-w> + {key}, it would depend on the user experience you want to provide. Use your plugin for some time, make some mistakes, and see how you'd like to see your plugin react.
Regarding the highlight color, in my plugin I use StatusLineNC as it's similar to what :substitute/pat/txt/c seems to use. In another plugin, I use Question.

Do you think it could be useful?

Well. I know I could do without it. And yet a few times, I've been bothered by the number of times I had to hit <c-w><down>. In the end I use the mouse. So... Why not. I'd have to make sure though that I never use <c-w> in a non-nore mapping.


Using another function on modified dictionary

You overwrite inv with the return value of addToInventory

inv = addToInventory(inv, dragonLoot)

Yet add to inventory does not return anything.
In order to first get your code to work, just return the inventory:

def addToInventory(inventory, addedItems):
    draft = {}
    for i in addedItems:
        if (i not in draft):
            draft[i]=1
        else:
            draft [i]= draft [i] + 1
    for i in draft:
        if i not in inventory:
            inventory[i]=draft[i]
        else:
            inventory[i] = inventory[i]+draft[i]
    return inventory

And then lets improve that function using the collections library such as:

from collections import Counter

def addToInventory(inv, loot):
    loot_counter = Counter(loot)
    return dict(loot_counter + Counter(inv))

Further, for the second displayInventory function, you iterate over dict.items(), yet you then try to use the item itself as an index. Instead iterate over dict.keys() and you will be fine:

def displayInventory(inventory):
    print ("Inventory: ")
    total=0
    for i in inventory.keys():
        total+=1
        print (str(inventory[i])+" "+str(i))
    print("Total number of items is"+str(total))


What you're looking for is all (ordered) integer partitions (of supplies) up to a maximum length (months).

Here is a solution in C#, as I'm not that comfortable with JavaScript.

private static IEnumerable<int[]> GetPartitions(int n, int length)
{
    return GetPartitions(n, length, n);
}

private static IEnumerable<int[]> GetPartitions(int n, int length, int max)
{
    if (n == 0)
    {
        // Only one way to partition 0.
        yield return new int[length];
        yield break;
    }

    if (n > length * max)
    {
        // No ways to partition n, as each of the elements
        // must be <= max.
        yield break;
    }

    for (var i = Math.Min(n, max); i > 0; i--)
    {
        foreach (var partition in GetPartitions(n - i, length - 1, i))
        {
            var newPartition = new List<int>(length);
            newPartition.Add(i);
            newPartition.AddRange(partition);
            yield return newPartition.ToArray();
        }
    }
}

And the output of GetPartitions(9, 5):

9, 0, 0, 0, 0
8, 1, 0, 0, 0
7, 2, 0, 0, 0
7, 1, 1, 0, 0
6, 3, 0, 0, 0
6, 2, 1, 0, 0
6, 1, 1, 1, 0
5, 4, 0, 0, 0
5, 3, 1, 0, 0
5, 2, 2, 0, 0
5, 2, 1, 1, 0
5, 1, 1, 1, 1
4, 4, 1, 0, 0
4, 3, 2, 0, 0
4, 3, 1, 1, 0
4, 2, 2, 1, 0
4, 2, 1, 1, 1
3, 3, 3, 0, 0
3, 3, 2, 1, 0
3, 3, 1, 1, 1
3, 2, 2, 2, 0
3, 2, 2, 1, 1
2, 2, 2, 2, 1

And here is my attempt in JavaScript:

function getPartitions(n, length, max) {
    if (n === 0) {
        // Only one way to partition 0.
        var result = [];
        for (var i = 0; i < length; i++) {
            result[i] = 0;
        }
        return [result];
    }

    if (n > length * max) {
        // No ways to partition n, as each of the elements
        // must be <= max.
        return [];
    }

    var partitions = [];
    for (var i = Math.min(n, max); i > 0; i--) {
        getPartitions(n - i, length - 1, i).forEach(function(partition) {
            partition.unshift(i);
            partitions.push(partition);
        });
    }

    return partitions;
}

getPartitions(9, 5, 9).forEach(function(partition) {
    console.log(partition);
});


This code is simply incorrect. It is even not a stack (because it lacks
pop operation and it is impossible to implement it in a type-safe way).
Here is an example:

runStack $ do
  newStackRef (5:: Int)
  newStackRef False
  newStackRef 'x'

according to the definition of the newStackRef it just pokes Storable
representation of the value into the memory block and advances the pointer.
Any information about the type of that value is lost.

To pop a value from such a stack you need to specify correct type and
compiler (or RTS) is not able to warn you if the type is not correct.

To the monad part of the question. From the instance Monad
definition it is easy to see that it almost the same as the State monad (here is how it defined in
Control.Monad.State.Trans.State.Lazy)

instance (Monad m) => Monad (StateT s m) where
    return a = state $ \s -> (a, s)
    m >>= k  = StateT $ \s -> do
        ~(a, s') <- runStateT m s
        runStateT (k a) s'

The only difference is that it operates on top of IO an has fixed type of state. So it is actually StateT (Ptr ()) IO.

It is even not clear what it is for a stack to be an instance of Monad.
E.g. list monad allows nondeterministic computations (in prolog-like
style), Maybe monad allows computations that fail.

To enable computation to access and operate stack it is easier to use existing State monad with some stack implementation as a state. I see no reason to implement your own Stack monad.


React - am i overusing props or is it exactly how they are suppoused to be used?

Use Props !

Using props to highly customize your component is good practice, but too many props isn't always good ! You need to ask yourself:

Am I trying to overly handle every situation possible ?
Is it ok if a second component handles different cases ?
Are these props absolutely required for my component to work as intended ?

If 1. and/or 2. is a yes and/or 3. is a no then you should probably rethink your component logic.

For your example, you're not overly using props.

Don't assume your props exist !

<input type={this.props.type} .../>

Get the props and set default values for them if they are undefined. Use destructuring for this:

render(){
  const {
      type        = "text",
      placeholder = "Type something",
      id          = null,
      className   = null
  } = this.props;

  return (
   <input type={type} placeholder={placeholder} id={id} className={className} />
  )
 }

Use PropTypes !

  You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.

Using many props gets messy and it's easy to forget which props are being used and which props are required for your components.

Example:

export class Input extends React.Component{
   /** code here */
}

Input.propTypes = {
  id: PropTypes.number.isRequired, //required will throw error if id is not set
  placeholder: PropTypes.string,
  className: PropTypes.string, //optional
  type: PropTypes.string, //optional
}

When to use classes and when not to use classes

Keep in mind that all your components don't need to be a class. Only use a class if the object becomes complex.

Keep things simple like so:

export const Input = props => {

  const {
      type        = "text",
      placeholder = "Type something",
      id          = null,
      className   = null
  } = props;

  return (
   <input
     type={type}
     placeholder={placeholder}
     id={id}
     className={className} />
  )
}


Serializing types with a common superclass

I think in this case you want a generic method, something on this general order:

static <T> private void saveGeneric(ArrayList<T> data, Path path) {
    try {
        OutputStream fos = Files.newOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(data);
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you might want to write the individual wrappers to match the functions you started with:

private void savePipeCableList(Data data) {
    saveGeneric(new ArrayList<PipeCable>(data.getPipeCableList()),
                Paths.get(Strings.dataPipeCableFileName));
}

private void saveElementList(Data data) {
    SaveGeneric(new ArrayList<Element>(data.getElementList()),
                Paths.get(Strings.dataElementFileName));
}

private void saveValveMotorList(Data data) {
    SaveGeneric(new ArrayList<ValveMotor>(data.getValveMotorList()),
                Paths.get(Strings.dataValveMotorFileName));
}

As for the code otherwise, the point that seems most obvious to me would be to replace the mostly manual opening and closing of the stream with a try with-resources statement:

// Note: I generally avoid Java, so I probably got at least a few details of
// the syntax wrong here.
OutputStream fos = Files.newOutputStream(path);
try (ObjectOutputStream oos = new ObjectOutputStream(fos))
{
    oos.WriteObject(data);
}
catch(FileNotFoundException e) {
    // ...

This will automatically close oos upon exit from the try block, regardless of whether you exit normally or via an exception. With the code as you've written it, if an exception is thrown while writing, oos.close() won't execute.

It's not immediately clear whether fos might benefit from similar treatment--without knowing how File.newOutputStream works and what it does, I can't really even guess about that (but perhaps you now know more about what to look for and consider). Right now, you have the Files.newOutputStream inside the try block (which I don't) but if you're just getting an existing object that you know exists, that won't matter. If it could throw an exception, you may have a more difficult problem, where you'd need nested try blocks (the inner of the "with resources" variety) to ensure correct behavior.

One other point. I hesitate to mention it, because I might just be demonstrating my ignorance of Java, but at least offhand, it seems like you probably don't need to create a complete copy of the data in memory before you write it to the output stream:

oos.writeObject(new ArrayList<ValveMotor>(data.getValveMotorList()));

At least offhand, it seems like it should be sufficient to use:

oos.writeObject(data.getValveMotorList());

The obvious reason we'd copy the data before serializing it would be if writeObject were asynchronous, and we need want to ensure we get a stable snapshot of the data at the time we started the serialization. If memory serves, writeObject is synchronous though.


Inserting a user sign-up record using mysqli

Like it was said in the comments, this code needs not a review but just some basic practices. That said, good basic practices are a rare specimen in the wild, so you cannot be blamed, given the number of awful tutorials out there. Luckily I am the renowned collector of good practices and here you are

Connectivity

There ate many things that could be improved in your connectivity file. To name a few

the connection character set must be configured to avoid issues with characters
the proper error reporting mode for mysqli must be set
the connection error smust be not bluntly echoed out

All these issues are covered in my article How to connect properly using mysqli: so let's take the code from there:

$host = '127.0.0.1';
$db   = 'webchat_data';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $conn = new mysqli($host, $user, $pass, $db);
    $conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
     throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}

Password hashing

In two words, never store passwords in plain text. Use password_hash() function instead. This topic is thoroughly explained in the question: https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely

Prepared statements

Just never add a variable to SQL query directly, but mark its place with a question mark instead. Then bind the actual variable and finally call execute()

In detail this matter is explained in this question: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php

So here is your signup code reviewed

<?php
include 'connectivity.php';

$uname = $_POST['uname'];
$email = $_POST['Email'];
$pass  = password_hash($_POST['Password'], PASSWORD_DEFAULT);

$sql = "INSERT INTO `sign-up`(USERNAME,EMAIL_ID,PASSWORD) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $uname,$email,$pass);
$stmt->execute();

header("Location:index.php");


Calculating difference between cached period and requested

I would suggest moving this method into the TimeSpan class. Let a TimeSpan tell you about its overlaps. Don't interrogate it for internal details and then figure it out for yourself. Private helper methods will make the compareTo calls more readable.
Assorted other thoughts:
A checked exception is probably not right here. I'd suggest preferring IllegalArgumentException, since that's what the problem is. Using a more specific exception than Exception is highly recommended.
Returning early would be preferable to assigning a return value and only returning once. That is a holdover from C, which only allowed a single return.
It's generally preferable to use the List variable type when you don't care about the type of list you're using.
Traditionally, variables are defined at the top of a class, not the bottom.
Traditionally, whitespace is added between if and (, and between ) and {.
The Date class already has an after() method, which would make the TimeSpan constructor cleaner.
Your error message in the constructor is incorrect. The from date also cannot be equal to the to date.
You should strongly consider using java.time instead of the java.util time classes. They are effectively deprecated.
Returning null is probably strictly worse than returning an empty collection, though it's difficult to say that authoritatively without seeing the client code.
If you made all these changes, your code might look something like:
public final class TimeSpan {

    private final Date from;
    private final Date to;

    public TimeSpan(Date from, Date to) throws IllegalArgumentException {
        if (!from.before(to)) {
            throw new IllegalArgumentException("Start date cannot be greater than or equal to end date");
        }
        this.from = from;
        this.to = to;
    }

    /**
     * Subtracts the timeSpan argument from this TimeSpan. This will result in a list of between
     * zero and two TimeSpans, ordered by start time.
     * @param timeSpan the span to subtract from this timespan. May not be null.
     * @return a list of TimeSpans covering the time that is in this timespan and not the argument timespan. Will
     * never return null.
     */
    public List<TimeSpan> minus(TimeSpan timeSpan) {
        // This TimeSpan is completely inside the argument.
        if (timeSpan.contains(this.from) && timeSpan.contains(this.to)) {
            return Collections.emptyList();
        }

        // This TimeSpan is either fully before or fully after argument
        if (this.endsBeforeOrAt(timeSpan) || this.startsAfterOrAt(timeSpan)) {
            return listOf(this); // only OK because this class is immutable
        }

        // This TimeSpan starts before and ends inside the argument
        if (timeSpan.contains(this.to)) {
            return listOf(new TimeSpan(this.from, timeSpan.from));
        }

        // This TimeSpan starts inside and ends after argument
        if (timeSpan.contains(this.from)) {
            return listOf(new TimeSpan(timeSpan.to, this.to));
        }

        // This TimeSpan starts before and ends after argument
        List<TimeSpan> results = new ArrayList<>();
        results.add(new TimeSpan(this.from, timeSpan.from));
        results.add(new TimeSpan(timeSpan.to, this.to));
        return results;
    }

    private boolean endsBeforeOrAt(TimeSpan timeSpan) {
        return this.to.compareTo(timeSpan.from) <= 0;
    }

    private boolean startsAfterOrAt(TimeSpan timeSpan) {
        return this.from.compareTo(timeSpan.to) >= 0;
    }

    private boolean contains(Date date) {
        return (this.from.compareTo(date) >= 0) && (this.to.compareTo(date) <= 0);
    }

    // If you're using Guava, replace this with Lists.of()
    private static List<TimeSpan> listOf(TimeSpan timeSpan) {
        List<TimeSpan> results = new ArrayList<>();
        results.add(timeSpan);
        return results;
    }

}


Personally here's what I would do :

Use the Membership type to create derived class; this will remove the if chain completely.
Avoid side effects in setters; bad practice in my opinion.
Avoid using properties with private sets; bad practice in my opinion.

This results in the following code :

public abstract class Customer
{
     protected int benefits;

     public abstract void UpdateBenefits(int newBenefits);

     public bool HasBenefits()
     {
         return benefits != 0;
     }

     public int GetBenefits()
     {
         return benefits;
     }
 }

 public class MembershipACustomer : Customer
 {
     public override void UpdateBenefits(int newBenefits)
     {
     }
 }

 public class MembershipBCustomer : Customer
 {
     public override void UpdateBenefits(int newBenefits)
     {
         benefits = newBenefits * (4 + 2);
     }
 }

 public class MembershipSomethingElseCustomer : Customer
 {
     public override void UpdateBenefits(int newBenefits)
     {
         benefits = newBenefits;
     }
 }

IMO it would also be a good idea to make a hierarchy with a new Benefit class, instead of customers. You can pass the benefit type to the customer by DI and that way it is the Benefit class that is responsible for calculating the benefit, not the customer. This would respect SRP a little more.


JavaScript and callback: apply an action on each element of a callback input

First you can realize that function(x){return f(x)} == f, so you can reduce one line there:

$.getJSON(DATA_URL +'/groups', function(groups){
  groups.forEach(appendDropdownItem)
})

It is harder to go further with these builtin functions. But if you have a curried forEach, with the arguments in the right order, such as the one in Rambda, or in Essentialjs (shameless plug), then you can reduce it even more:

$.getJSON(DATA_URL +'/groups', forEach(appendDropdownItem))

There you got a one readable one-liner.

You can implement your own curried forEach in any case:

var forEach = function(f) {
  return function(xs) {
    return xs.forEach(f)
  }
}

But these libraries include many other helpers that provide a more functional workflow that leads to these one-liners often by means of currying and composition.


Python script to renew key from Vault every 30s

You don't need a class here. Neither you need a Timer.

import hvac
import time
import threading
import os
import sys

VAULT_URL, VAULT_TOKEN = sys.argv[1:]

def read(client, *keys):
    client.renew_token()
    return {k: client.read(key) for key in keys}

if __name__ == '__main__':
    client = hvac.Client(url=VAULT_URL, token=VAULT_TOKEN)
    while True:
        print(read(client, 'secret/key'))
        time.sleep(30)


Variable capitalization

IT IZ PRETTY GUD LOLCODE
HOWEVEZ ME THINKS THAT TEH LOLCODEZ R EZYR 2 READ IF TEH VARZ R lowercase
ZIS BECUZ ALL CAPS IS HARD TOO READ
(all spelling "mistakes" made by my cat, who assisted me in that part of this review)

More seriously, it is an issue that there are no good LOLCODE syntax highlighters. To be "stylish" and keep everything uppercase is a choice you can make, but personally I prefer to use lowercase or camelCase variable names whilst keeping the language constructs all caps. Similar to SQL, this allows you to see what parts of the code are variables, and what parts are language constructs.

Compare:

I HAS A NAUW ITZ A NUMBR
I HAS A LEZZ ITZ A NUMBR
IM IN YR LOOPZ NERFIN YR COWNTR TIL BOTH SAEM COWNTR AN DIFF OF 1 AN NUMAH
  NAUW R SUM OF NUMAH AN COWNTR
  LEZZ R DIFF OF NAUW AN 1
  VISIBLE SMOOSH NAUW AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
  VISIBLE SMOOSH NAUW AN " LITTERS OV KITTEHS" MKAY
  VISIBLE "WAN FALLS DOWN AN BREAKZ PAH"
  VISIBLE SMOOSH LEZZ AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
  VISIBLE ""
IM OUTTA YR LOOPZ

with...

I HAS A nauw ITZ A NUMBR
I HAS A lezz ITZ A NUMBR
IM IN YR LOOPZ NERFIN YR cowntr TIL BOTH SAEM cowntr AN DIFF OF 1 AN numah
  nauw R SUM OF numah AN cowntr
  lezz R DIFF OF nauw AN 1
  VISIBLE SMOOSH nauw AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
  VISIBLE SMOOSH nauw AN " LITTERS OV KITTEHS" MKAY
  VISIBLE "WAN FALLS DOWN AN BREAKZ PAH"
  VISIBLE SMOOSH lezz AN " LITTERS OV KITTEHS ON TEH NETZ" MKAY
  VISIBLE ""
IM OUTTA YR LOOPZ

Variable naming

Regarding NUMAH, have you considered using NUMBAH? Similar meaning, but uses a more common mispronunciation.

Working around the spec

IM IN YR LOOPZ NERFIN YR COWNTR TIL BOTH SAEM COWNTR AN DIFF OF 1 AN NUMAH
  NAUW R SUM OF NUMAH AN COWNTR

This construct is non-obvious. You had to work around the spec to do something that you wanted to do, and I think it warrants explanation. Add a comment via BTW:

IM IN YR LOOPZ NERFIN YR COWNTR TIL BOTH SAEM COWNTR AN DIFF OF 1 AN NUMAH
  NAUW R SUM OF NUMAH AN COWNTR BTW workaround loop counters starting at 0

Correctness in corner cases

Your function doesn't check if the value passed in is greater than 0. This means that it falsely forces a KITTEH to break their paw when it wasn't necessary.

Add a guard clause at the top of the function; you can do an early return via GTFO.

DIFFRINT numbah AN BIGGR OF numbah AN 0
O RLY? YA RLY
    GTFO
OIC

Program definition

OBTW
    PRINT TEH LOLCODE VERSHUN OV N BOTTLEZ OV BER ON TEH WALL.
TLDR

HAI 1.3

Aside from the weird phrasing (does this code print the lolcode version of/and bottles of beer on the wall?), there's something else wrong here: Your comment is before the HAI 1.3. So any interpreter loading your file might not know what version you are using. Put your version number at the top.

Possible alternative dialects

VISIBLE "NO MOAR LITTERs OV KITTEHS ON TEH NETZ"

Did you make a typo here, is this an alternative kitty dialect that uses lower case 's' for certain plurals? I'm not sure.

Lastly, I think this version of 99 LITTERS OV KITTEHS ON TEH NETZ is not authentic, as anyone knows that when KITTEHS fall, they'll be alright. This version is sad, as all the KITTEHS just break their paws. Proper LOLCODE uses cats, it doesn't abuse them.


Prime sieves are really not well suited for linked lists. While sorting or merging are clever way to handle the lists in a functional context, the easiest way to improve preformance is to simply use mutable arrays, so it's more similar to the C++ version.

Here I just replaced the sorting and removeComposites with an unboxed STArray and indexing. The benifit with using STArray is that you still get a pure function, even though the array is mutable while generating. The times are now comparable with the C++ version.

import Data.Array.ST
import Data.Array.Unboxed

bound :: Int -> Int
bound n = floor (n' * (log n' + log (log n')))
    where
        n' = fromIntegral n

marked :: Int -> [Int]
marked n =  [ i + j + 2*i*j | i <- [1..iMax], j <- [i..jMax i]]
    where
        iMax = floor (sqrt (fromIntegral n))
        jMax i = quot (n - i) (2*i + 1)

marked' :: Int -> UArray Int Bool
marked' n = runSTUArray $ do
    arr <- newArray (1,n) True
    mapM_ (\i -> writeArray arr i False) (marked n)
    return arr

sieveSundaram :: Int -> [Int]
sieveSundaram n = 2: [2*x+1 | x <- [1..n'], marked' n' ! x]
    where
        n' = quot (bound n) 2

pe_007 = last . take n $ sieveSundaram n
    where n = 100001

main :: IO ()
main = print pe_007

On my system, with n=200001, the times are:

Haskell, Original version: 5.930s
Haskell, Neil's version:   5.916s
Haskell, Data.IntSet:      2.853s
Haskell, Boxed STArray:    0.209s
Haskell, Unboxed STUArray: 0.055s
C++:                       0.019s

It is probably possible to improve the times even more, but this takes care of most of the difference.

Update

Continuing on the theme of using the right data structure for the job, I tried using IntSets for aditional comparison. It is about twice as fast as the list based solutions, but still a lot slower than using mutable arrays (see updated table). So if you want to stay with pure haskell98, this might be an alternative. Here is my (naive) translation. I just create the set of numbers [1,n] and the set of numbers to remove (from marked) and take the difference.

import qualified Data.IntSet as IS

bound :: Int -> Int
bound n = floor $ n' * (log n' + log (log n'))
    where
        n' = fromIntegral n

marked :: Int -> [Int]
marked n =  [ i + j + 2*i*j | i <- [1..iMax], j <- [i..jMax i]]
    where
        iMax = floor (sqrt (fromIntegral n))
        jMax i = quot (n - i) (2*i + 1)

marked' :: Int -> [Int]
marked' n = let
    l1 = IS.fromList [1..n]
    l2 = IS.fromList (marked n)
    in IS.toList $ l1 IS.\\ l2

sieveSundaram :: Int -> [Int]
sieveSundaram n = 2: [2*x+1 | x <- marked' n']
    where
        n' = quot (bound n) 2

pe_007 = last . take n $ sieveSundaram n
    where n = 200001

main :: IO ()
main = print pe_007

IntSets are a really good data structure if you need to repeatedly modify the sets in a pure context, but for this problem nothing can beat an unboxed mutable array.


PHP Going Multiple Directories Back Best Practice

Instead of nesting the dirname calls, according to the documentation for dirname you could call this as of PHP 7:

dirname(__FILE__, 5)

For supporting lower versions of PHP, you could write a parentDirectory function:

function parentDirectory($path, $levels) {
    for ($i = 0; $i < $levels; $i++) {
        $path = dirname($path);
    }
    return $path;
}

Or just embed it inside your current code, without a specific function:

$configPath = __FILE__;
for ($i = 0; $i < 5; $i++) {
    $configPath = dirname($configPath);
}
define('PATH_TO_CONFIG_DIR', $configPath . "/config/");


This is a great sample for review btw! I'm glad you posted this. Hopefully it will get some good google traffic.

I see a number of problems here however, and they're not all with the code:

Why are you generating a password in the first place? The user should be doing this! Are you going to hash and store this plain and destroy it? Or are you going to email it to them or show it on screen? In any case, you shouldn't be generating passwords for users if you can help it. If you need to represent state for a user account who has not yet set a password, use null, string.Empty or some other flag to model this state explicitly. Do not choose a password for them please.
If you absolutely must choose a random password, then make it secure. I contest this statement "this password should be more than adequate for most situations". Alphanumerics + special characters of at least 30-50 characters is more what you want. LastPass for example defaults to 30 chars and the full mix of symbols. Also, you're composing your randomly generated plain using RNGCryptoServiceProvider and Random! Do not do this! You want cryptographically secure random numbers which you will get with RNGCryptoServiceProvider but you won't with Random. So please never use Random for security related work.
Lastly, I don't believe Crypter.Blowfish.Crypt(PasswordBytes) is bcrypt. What is the package/reference for that call? I believe the package you want is BCrypt-Official which should look something like BCrypt.Net.BCrypt.HashPassword(passwordPlain, BcryptWorkfactor) when used. If what you have there is what I think it is, it's not an adaptive function which is possibly worse than MD5 or SHA1 (which for clarity are also not acceptable).

Here is an alternative to generating a simple plain securely:

    private static string GenerateSimpleKeySecurely(int keyLength)
    {
        // add whatever special characters in here you like
        var keyspace = @"0123456789abcdefghijklmnopqustuvwxyz()[]{}".ToCharArray();

        var data = new byte[1];
        using (var crypto = new RNGCryptoServiceProvider())
        {
            crypto.GetNonZeroBytes(data);
            data = new byte[keyLength];
            crypto.GetNonZeroBytes(data);
        }
        var result = new StringBuilder(keyLength);
        foreach (var b in data)
            result.Append(keyspace[b % (keyspace.Length)]);

        return result.ToString();
    }

Now go and read the OWASP: Password Storage Cheat Sheet.


Generating Calendar month information using JavaScript

This could use some breathing space.

this.endDay = date.getDay();
date.setDate(1);
this.startDay = date.getDay();
this.days = [];

Compare it to this.

this.endDay = date.getDay();

date.setDate(1);

this.startDay = date.getDay();
this.days = [];

See how the extra vertical space calls out the change in state?

Magic Number Alert

This needs an extra variable, a comment, or maybe even both.

for(var i = 0; i < 42; i++) {

I've read over this loop at least 20 times now. I still have no idea why the number 42 is important here. Why is 42 the upper bound? The logic isn't obvious. You should find a way to make it obvious.


Is it ok to have an async void method?

Referencing Async/Await - Best Practices in Asynchronous Programming

As already stated in the OP async void should be avoided as much as possible.

The one exception to that rule being for event handlers, which can be the loophole to achieving the desired behavior while still having the ability to catch and handle any thrown exceptions.

Create an event

event EventHandler QueryReportCallbackEvent = delegate { };

to be raised by the timer callback

private void QueryReportTimerCallback(object state) {
    QueryReportCallbackEvent(this, EventArgs.Empty);
}

The event handler allows async void, so now you can safely do

private async void QueryReportCallbackEventHandler(object sender, EventArgs e) {
    if (await semaphoreQueryReportSlim.WaitAsync(10))
        await queryReportsCore();
}

  Is it ok to have await inside Parallel.ForEach?

NO!!!!

The async lambda

async (configuration) => ...

will be converted to async void which takes us right back to what was said in the beginning. async void BAD!!!

Instead refactor that lambda out into its own method that returns a Task

private async Task HandleReport(MachineConfiguration configuration) {
    if (configuration.IsConnectionValid) {
        var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
        await QueryAReport(configuration, queryReport);
    }
}

and this will now allow for the use of Task.WhenAll with all the machine configurations retrieved from the query.

var tasks = machineConfigurations
                .Where(x => x.QueryReport)
                .Select(configuration => HandleReport(configuration));

await Task.WhenAll(tasks);

This actually removes the need for the Paralell.ForEach.

Here is the complete code for what was described above.

//CTOR
public MyClass() {
    QueryReportCallbackEvent += QueryReportCallbackEventHandler;
    var QueryReportTimer = new Timer(QueryReportTimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
}

event EventHandler QueryReportCallbackEvent = delegate { };

private void QueryReportTimerCallback(object state) {
    QueryReportCallbackEvent(this, EventArgs.Empty);
}

private async void QueryReportCallbackEventHandler(object sender, EventArgs e) {
    if (await semaphoreQueryReportSlim.WaitAsync(10))
        await queryReportsCore();
}

private async Task queryReportsCore() {
    try {
        if (machineConfigurations != null) {
            var tasks = machineConfigurations
                            .Where(x => x.QueryReport)
                            .Select(configuration => HandleReport(configuration));

            await Task.WhenAll(tasks);
        }
    } catch (Exception e) {
        logger.LogError(e, e.Message);
    } finally {
        semaphoreQueryReportSlim.Release();
    }
}

private async Task HandleReport(MachineConfiguration configuration) {
    if (configuration.IsConnectionValid) {
        var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
        await QueryAReport(configuration, queryReport);
    }
}

Lastly take note of how the functions were broken down into smaller chunks that allowed for cleaner, more easy to read code.


private readonly string _ReCaptchaSecret;
private readonly string _ReCaptchaSiteKey;

private fields are either lowerCamelCase or _lowerCamelCase, both conventions are common.

public ReCaptchaValidator(string reCaptchaSecret)
{
    _ReCaptchaSecret = reCaptchaSecret;
    this.ErrorCodes = new List<string>();
}
public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)
{
    _ReCaptchaSecret = reCaptchaSecret;
    _ReCaptchaSiteKey = reCaptchaSiteKey;
    this.ErrorCodes = new List<string>();
}

Don't repeat work in your constructors: use chaining instead.

public ReCaptchaValidator(string reCaptchaSecret)
{
    _ReCaptchaSecret = reCaptchaSecret;
    this.ErrorCodes = new List<string>();
}

public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)
    : this (reCaptchaSecret)
{
    _ReCaptchaSiteKey = reCaptchaSiteKey;
}

With C# 6, you can also use a property initializer to.. initialize.. your property.

public List<string> ErrorCodes { get; set; }

public ReCaptchaValidator(string reCaptchaSecret)
{
    _ReCaptchaSecret = reCaptchaSecret;
    this.ErrorCodes = new List<string>();
}

becomes

public List<string> ErrorCodes { get; set; } = new List<string>();

public ReCaptchaValidator(string reCaptchaSecret)
{
    _ReCaptchaSecret = reCaptchaSecret;
}

I would also advise to use a private setter for your ErrorCodes like this:

public List<string> ErrorCodes { get; private set; } = new List<string>();

Likewise, with C# 6, you might as well make it a readonly property:

public List<string> ErrorCodes { get; } = new List<string>();

StringBuilders see their most use when you're concatenating strings in a loop. In this scenario I would use a formatted string which turns this:

var sb = new StringBuilder();
sb.Append("https://www.google.com/recaptcha/api/siteverify?secret=");
sb.Append(_ReCaptchaSecret);
sb.Append("&response=");
sb.Append(request.Form["g-recaptcha-response"]);
sb.Append("&remoteip=");
sb.Append(GetUserIp(request));

into this:

var uri = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}",
    _ReCaptchaSecret,
    request.Form["g-recaptcha-response"],
    GetUserIp(request));

Or with C# 6:

var uri = $"https://www.google.com/recaptcha/api/siteverify?secret={_ReCaptchaSecret}&response={(request.Form["g-recaptcha-response"])}&remoteip={GetUserIp(request)}";

else if (!string.IsNullOrEmpty(request.UserHostAddress))

I prefer string.IsNullOrWhiteSpace because only rarely whitespace characters are considered good input.


Filtering objects according to required and preferred attributes

The most important piece of advice I can offer is get rid of any. By using any you are making Typescript ignore potential errors in your program. opportunity could be described with the following interfaces:

interface Opportunity {
  id: number
  title: string
  nationalities: Criteria[]
  skills: Criteria[]
  backgrounds: Criteria[]
  languages: Criteria[]
}

interface Criteria {
  option: 'preferred' | 'required'
  id: number
  name: string
}

Furthermore, the backgrounds, skills, languages, and nationalities properties should be correctly typed. In this case, I'd just add another interface, SeparatedCriteria isn't really the best name, but you can probably come up with a better one as you are more familiar with what each piece of data represents.

interface SeparatedCriteria {
  preferred: Criteria[]
  required: Criteria[]
}

filterByProperty has a lot of redundancy. At the very least, I would recommend defining isRequired and isPreferred local functions to help cut down on some of the noise.

However, this is still rather noisy especially as the logic is the same for each property - the only thing that changes is the key. With this in mind, we can define an array of keys, ['skills', 'backgrounds', 'languages', 'nationalities'] and assign this[key].preferred and this[key].required.

The trick to making this work correctly is to use both intersection types and index types. It is possible to do this without knowledge of these topics, but the solution will not be type safe as it would be possible to add keys which aren't present in both Opportunity and AppComponent without receiving a compiler error. Here's how I would implement this function. You could now get rid of isRequired and isPreferred as they are only used once, but I believe it makes the logic more clear to leave them as is.

filterByProperty() {
  const isPreferred = ({ option }: Criteria) => option == 'preferred';
  const isRequired = ({ option }: Criteria) => option == 'required';

  const propertyKeys: Array<keyof AppComponent & keyof Opportunity>
    = ['skills', 'backgrounds', 'languages', 'nationalities'];

  for (const key of propertyKeys) {
    this[key].preferred = this.opportunity[key].filter(isPreferred);
    this[key].required = this.opportunity[key].filter(isRequired);
  }
}


Hamburger menu with Javascript - clearing state

HTML

The formating could be a bit cleaner ( on its own line, superfluous spaces around =, content of
 not indented).
on... attributes shouldn't be used. Event handlers should be assigned in the script.
I don't believe &#9776; ("Trigram For Heaven") is a suitable character to use for a  menu icon.
The submenus aren't structured properly in my opinion:

The clickable header entries shouldn't be list items themselves, but separate elements before the ul.
Also they should be an interactive elements such as <button> or .
If you would also wrap all the submenus in a separate item with the hamburger button before it, then you could simplify the JavaScript so that it simply toggles that single element, which spares you the loop and the exception of the first element.
Alternatively you could even consider using the  element, which has the toggling built in, requiring no JavaScript at all.

JavaScript

Instead of passing the ID of the parent element into the function you could get the clicked element (and thus its parent) from the event object. Example:

// Assign event handler in JavaScript instead of using the HTML attribute
document.querySelector(".menuHamburger").addEventListener("click", hideAllButFirstChild);

function hideAllButFirstChild(event) {
   // TODO Add null checks.
   const children = event.target.parent.children;

   // ...
}

And as seen above use const or let instead of var for variables.
Start the loop at i = 1 to skip the first element instead of checking inside the loop.
Instead of manipulating style in JavaScript set/remove a class (or, better, in this case the hidden attribute)


Finding distance between vectors of matrices

This is an old enough question that shooting for the extra points is hopefully not going to step on anyone's toes. So let me be the broadcast guy, i.e. this is a loop-free version.
It is perhaps better to first read either the numpy documentation on broadcasting, or a related answer of mine.
We start with solving the one-column case.
In this case the matrices are of size n x 1 and k x 1. We need to turn these into a matrix of size k x n.
Well, to get there by broadcasting, we need to take the transpose of one of the vectors. The problem calls for the first one to be transposed. Thus we have the matrix a.T of size 1 x n and b of size k x 1.
Then the solution is just
    # shape is (k, n)
    (np.abs(a.T - b) ** p) ** (1/p).

The case with multiple columns
The matrices are of size n x m and k x m. To be able to reuse the previous idea, we have to turn these into arrays of shape 1 x n x m and k x 1 x m. This can be done using np.expand_dims:
    # shape is (k, n, m)
    np.expand_dims(a, 0) - np.expand_dims(b, 1)

Looks good. All that remains is to take the absolute value, then the pth power, then sum up along the last dimension, lastly take pth root.
    # shape is (k, n)
    (np.abs(np.expand_dims(a, 0) - np.expand_dims(b, 1))**p).sum(axis=-1)**(1/p)


Similar to Toto's answer, I recommend:

function clean($var) {
    return preg_replace("~[^\w -]+~", "", $var);
}

This will replace all occurrences of one or more consecutive forbidden characters.

Adding the "one or more" (+) quantifier means longer potential matches and fewer total replacements.  IOW, imagine a carton of a dozen eggs on yhe ground.  If the task was to pick up 12 eggs, you could squat 12 times picking them up one at a time, or just squat once and pickup the carton.

I have eliminated the unnecessary inclusion of "single-use variables" as there is no benefit in retaining them for readability.

Following this custom function call, the call of htmlspecialchars() is useless because there won't be any chars to convert.

On the other hand, if you wanted to call htmlspecialchars_decode() prior to clean() there is reasonable logic to that decision, but it depends on the input that you are expecting.


LeetCode: Validate Binary Search Tree C#

For the most part I agree with your code.  However there are a couple of things:

IsValidBST I think is redundant.  Anyone running this method already knows it applies to a BST.  I think just IsValid would be better.

Helper should have a better name, I think an IsValid overload would work and it should be private.

It doesn't make much sense to me to make an instance of this class.  The methods don't rely on anything internal to the class.  I would suggest making the methods static.

It could look something like this:

public class IsValidBSTclass
{
    public static bool IsValid(TreeNode root)
    {
        return IsValid(root, null, null);
    }
    private static bool IsValid(TreeNode root, TreeNode minNode, TreeNode maxNode)
    {
        if (root == null)
        {
            return true;
        }
        if (minNode != null && root.val <= minNode.val || maxNode != null && root.val >= maxNode.val)
        {
            return false;
        }

        return IsValid(root.left, minNode, root) && IsValid(root.right, root, maxNode);
    }
}