Performance notwithstanding, there's some other cleanup that's worth doing:

Capitalize NUM_WORKERS since it's a global constant
Do not shadow your global output with a local variable of the same name; and ideally don't have a global output at all
After your get() and before your call to .text, you need to check whether the request succeeded - either via .ok and a log entry showing the reason; or by .raise_for_status()
never try / except / pass. This is the broadest and most dangerous form of silent exception-swallowing. If runner is executing and the user attempts to terminate the application with a Ctrl+C, that will be ignored here, and all other error information has become invisible to you. Consider at least except Exception: and logging the exception using the standard logging framework.
Consider annotating runner as def runner(number_of_requests: int) -> str
Do not cast the result of .text to a string - it's already a string
Do not use time.time() here; instead use time.perf_counter() for a sufficiently short duration or time.monotonic() otherwise
The parens in (number_of_request*num_workers)/duration are redundant


Reuse the value of previous type instead of None

First, your code reformatted properly so it's more legible:

def get_info(alpha, alpha_type):

    print("checking value of item:", alpha_type)

    try:
        if not alpha_type:
            raise

        return alpha, alpha_type

    except Exception:
        alpha_type = "vowel"
        return get_info(alpha, alpha_type)

if __name__ == '__main__':
    main_type = None
    for elem in ["a", "e", "o"]:
        result = get_info(elem, alpha_type=main_type)
        main_type = result[1]
        print(result)

Take 20 minutes and read over PEP8. It's Python's style guide and dictates how code should look. Most notably, you should have spaces after commas, and you shouldn't try to shove things onto one line in most cases (like you're doing with raise).

Your code is abusing try and raise. It doesn't make any sense to raise in a try just to go to the except. You should just use make use of the if that you already have:

def get_info(alpha, alpha_type):

    print("checking value of item:", alpha_type)

    if not alpha_type:
        return get_info(alpha, "vowel")

    else:
        return alpha, alpha_type

Honestly, I don't understand what you're trying to do here, so that's really all I can comment on. I just wanted to point out the formatting and needless use of try.


TypeScript implicit 'any' type with computed property key

You very rarely need to use any in TypeScript because its type-system is so expressive.

The problem is that copyFormat is specified to be any string.

What would happen if you passed "blahblahblah" as copyFormat? Your types currently allow this!. Then, your code would attempt to do formats["blahblahblah"], but .blahblahblah is not a member of  the formats object.

You need a more precise type for copyFormat. You intended the caller to only pass one of "keyword", "hex", or "rgb". You can make a type that is just those three values like so:

interface Props {
  keyword: string;
  hex: string;
  rgb: string;
  copyFormat: "keyword" | "hex" | "rgb";
}

It looks like Props really holds two things; it holds the actual data, and then a separate argument controlling what you read from it. It might make sense to split it into two arguments:

export default ({ keyword, hex, rgb }: Props, copyFormat: "keyword" | "hex" | "rgb") => {
  const formats = {
    keyword,
    hex: hex.toUpperCase(),
    rgb: `rgb(${rgb})`,
  };

  return
{formats[copyFormat]}
;
}

If you don't like typing out all of the possible key options, you could instead use the keyof type operator to say that copyFormat is any valid key in the Props type. TypeScript will see that all of the properties are strings and correctly infer the resulting type of formats[copyFormat] is thus a string.

interface Props {
  keyword: string;
  hex: string;
  rgb: string;
}

export default ({ keyword, hex, rgb }: Props, copyFormat: keyof Props) => {
  const formats = {
    keyword,
    hex: hex.toUpperCase(),
    rgb: `rgb(${rgb})`,
  };

  return
{formats[copyFormat]}
;
};
```


This is good code, because it does what it says on the tin. I do have two remarks:

The this. in this.ensureCapacity(limit) isn't necessary. Some people swear by adding it anyway, so it's a matter of style.

The other remark is that you loop over twice as many elements as needed because you set size to limit before looping. You can hold off until after:

public void mirror() {
    if (size != 0) {
        int limit = size * 2;
        this.ensureCapacity(limit);
        //size = limit; // [!] moved to below >>>
        for (int i = 0; i < size; i++) {
           elementData[(limit - 1) - i] = elementData[i];
        }
        size = limit; // [!] <<< moved from above
    }
}

That's all. Good code.


Getting a valid datetime format from a string

import datetime
def _eventdatetime(self, string):
    base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M")

Why are you specifying the date as a string only to parse it? Just do: base_date = datetime.datetime(1980,1,6,0,0). You should also make it a global constant so as not to recreate it all the time.

    weeks = datetime.timedelta(weeks = int(string[5:9]))
    days = datetime.timedelta(days = int(string[9]))
    seconds = datetime.timedelta(seconds = int(string[10:15]))

There is no need to create several timedelta objects, you can do datetime.timedelta(weeks = ..., days = ..., seconds = ...)

    stamp = base_date + weeks + days + seconds

    adjustUTC = datetime.timedelta(hours = 3)
    stamp =  stamp - adjustUTC

I'd use stamp -= datetime.timedelta(hours = 3) # adjust for UTC

    return str(stamp)


I took your new code and cleaned it up a bit by

adjusting bracket location
removed unnecessary nesting of if statements
gave some operations some breathing room
fixed some odd indentations

I took your code

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
      Dictionary<char,int> firstString = new Dictionary<char,int>();
      Dictionary<char,int> secondString = new Dictionary<char,int>();

      foreach(char character in a)
      {
          if(firstString.ContainsKey(character))
          {
              firstString[character]+=1;
          }
          else{
              firstString[character]=1;
              }
      }

      foreach(char character2 in b)
      {
          if(secondString.ContainsKey(character2))
          {
              secondString[character2]+=1;
          }
          else{
              secondString[character2]=1;
              }
      }

      if(firstString.Count !=secondString.Count){
          return false;
      }
      else   {
              foreach(KeyValuePair<char,int> letterValue in secondString)
                  {
                      if(firstString.ContainsKey(letterValue.Key))
                      {
                          if(firstString[letterValue.Key] != secondString[letterValue.Key]){

                              return false;
                              }
                      }
                      else
                      {
                          return false;
                      }
                  }
              }
      return  true;
  }

  public static void Main(string[] args)
  {
      Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
  }
}

and refactored it to this (there is an issue with the if then statement inside last for loop, which I address later)

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

        foreach(char character in a)
        {
            if(firstString.ContainsKey(character))
            {
                firstString[character] += 1;
            }
            else
            {
                firstString[character] = 1;
            }
        }

        foreach(char character2 in b)
        {
            if(secondString.ContainsKey(character2))
            {
                secondString[character2] += 1;
            }
            else
            {
                secondString[character2] = 1;
            }
        }

        if(firstString.Count != secondString.Count)
        {
            return false;
        }
        else
        {
            foreach(KeyValuePair<char,int> letterValue in secondString)
            {
                if(firstString.ContainsKey(letterValue.Key)
                    && (firstString[letterValue.Key] != secondString[letterValue.Key]))
                {
                    return false;
                }
                else
                {
                    return false;
                }
            }
        }
        return  true;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
    }
}

I also decided to change this so that there are two separate if statements, this will reduce the O(n) in the optimistic case
(Your code cleaned up)

foreach(KeyValuePair<char,int> letterValue in secondString)
{
    if(firstString.ContainsKey(letterValue.Key))
    {
        if(firstString[letterValue.Key] != secondString[letterValue.Key]){
            return false;
        }
    }
    else
    {
        return false;
    }
}

New Code with less complexity

foreach(KeyValuePair<char,int> letterValue in secondString)
{
    if (!firstString.ContainsKey(letterValue.Key))
    {
        return false;
    }
    if (firstString[letterValue.Key] != secondString[letterValue.Key])
    {
        return false;
    }
}

You could merge these into a single if statement, but for the sake of reading I left them separate here.

If one doesn't contain the key of the other one, you want to return false, no need to check the other condition.

Another overall thing that you could do to reduce the O(n) is to evaluate if the strings are the same length, immediately and return false if they are not, because you already know they cannot be anagrams of each other.

like this

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        if (a.Length != b.Length) {
            return false;
        }

        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

       /// ...

then you can remove the check later in the code.

I did that, and also changed += 1 to ++ twice in your code.  I also made it case insensitive, but sentences will not work.

Here is the code that works, I tested with your example and with Joker and JReko

if (a.Length != b.Length)
{
    return false;
}

Dictionary<char, int> firstString = new Dictionary<char, int>();
Dictionary<char, int> secondString = new Dictionary<char, int>();

foreach (char character in a.ToLower())
{
    if (firstString.ContainsKey(character))
    {
        firstString[character]++;
    }
    else
    {
        firstString[character] = 1;
    }
}

foreach (char character2 in b.ToLower())
{
    if (secondString.ContainsKey(character2))
    {
        secondString[character2]++;
    }
    else
    {
        secondString[character2] = 1;
    }
}

foreach (KeyValuePair<char, int> letterValue in secondString)
{
    if (!firstString.ContainsKey(letterValue.Key)
        || (firstString[letterValue.Key] != secondString[letterValue.Key]))
    {
        return false;
    }
}

return true;


After I did a little playing around in a LinkedIn page's source code and I found out that LinkedIn already uses jQuery: that means you don't need to worry about checking if jQuery exists in the page because the page already has it.

Therefore, you can strip away all the jQuery injection nonsense, leaving your code looking like this;

var version = "2.1.4";

jQuery(document).on('scroll', function (event) {
    jQuery('li.card.guest').hide();
});

If you would like a review on how you did the on the vanilla JavaScript, leave a comment.


Passing an array created in function to other functions

First, the usual criticisms:

Don't use using namespace std;
Don't use raw new and delete
Include the headers your code uses (e.g. <iostream>)
Prefer prefix ++i over postfix i++ as a general habit
Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

Then, the point specific to your API design:

Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:

#include <iostream>
#include <utility>

std::pair<int *, int> create() {
    int n;
    std::cout << "How many elements? ";
    std::cin >> n;
    int *arr = new int[n];
    for (int i = 0; i < n; ++i) {
        int element;
        std::cout << std::endl << "Enter " << i << " array element: ";
        std::cin >> element;
        arr[i] = element;
    }
    return {arr, n};
}

void display(int *arr, int n) {
    for (int i = 0; i < n; ++i) {
        std::cout << std::endl << i << " element: " << arr[i];
    }
}

int main() {
    auto [arr, n] = create(n);
    display(arr, n);
    delete [] arr;
}

The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.

Applying "no raw new and delete" allows us to simplify much further:

#include <iostream>
#include <vector>

std::vector<int> create() {
    int n;
    std::cout << "How many elements? ";
    std::cin >> n;
    std::vector<int> result;
    for (int i = 0; i < n; ++i) {
        int element;
        std::cout << std::endl << "Enter " << i << " array element: ";
        std::cin >> element;
        result.push_back(element);
    }
    return result;
}

void display(const std::vector<int>& vec) {
    for (int i = 0; i < int(vec.size()); ++i) {
        std::cout << std::endl << i << " element: " << vec[i];
    }
}

int main() {
    auto vec = create(n);
    display(vec);
}

The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:

#include <iostream>
#include <vector>

template<class T>
T input(const char *prompt) {
    T result;
    // Print out everything in `prompt` (C++17 syntax)
    std::cout << prompt << " " << std::flush;
    std::cin >> result;  // Should we add some error-checking?
                 // What if the user types "hello world" here?
    return result;
}

std::vector<int> create() {
    std::vector<int> result;
    int n = input<int>("How many elements?");
    for (int i = 0; i < n; ++i) {
        result.push_back(input<int>("Enter the next array element:"));
    }
    return result;
}

void display(const std::vector<int>& vec) {
    for (int i = 0; i < int(vec.size()); ++i) {
        std::cout << std::endl << i << " element: " << vec[i];
    }
}

int main() {
    display(create(n));
}

Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.

Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.


POSIX shell compatible and POSIX conforming dirname implementation

I don't think there's a really compelling reason for this eval in stripslashes:

eval "$2=\$i"

It's a dirty hack to update the parameter variable in-place.
But this is not a common practice, I don't know other commands or built-ins that work that way, and I would find such usage unexpected.
I would find it more usable if stripslashes behaved more like other commands do:

print the result on stdout
set the result in a designated variable (like REPLY)

That would be more in-line with common UNIX practices, and unsurprising, familiar.

As a minor nitpick, I avoid quoting when it's unnecessary.
For example instead of [ "$p" != '//' ], I would write [ "$p" != // ]

Instead of this:

        [ -z "$p" ] && p=/

This form is shorter:

        [ "$p" ] || p=/

This might be subjective, but I would rewrite this part using regular if-else:

[ -n "$skip78" ] || {
    { [ "$p" != '//' ] || [ -z "$alt" ]; } && {
        stripslashes "$p" p
        [ -z "$p" ] && p=/
    }
}


Because you are interested in the time it took and not the stopwatch, you should return a TimeSpan. And since we no longer need stopwatch as a parameter, we can rename timer to stopwatch (as "timer" makes me think of the Timer class).

public static void Invoke(Action action, out TimeSpan timeSpan)
{
    var stopwatch = Stopwatch.StartNew();
    action.Invoke();
    stopwatch.Stop();
    timeSpan = stopwatch.Elapsed;
}


The compactness and efficiency of the code is quite impressive.  The downside is that it's rather convoluted and difficult to understand.

Types

Annotations

Haskell types are very helpful, both when writing and reading code.  Type declarations should not be limited to top-level functions.  They can, and should, be added to local variables as well.  Even though it's not very complicated, the purpose of endpoints becomes much clearer when its type is explicitly stated:

endpoints :: [(a, b)] -> [Either a b]
endpoints = foldr (\(a, b) m -> (Left a):(Right b):m) []

It converts tuples into eithers.  It's obvious from the type that it works almost like a map, which we can make more explicit by using concatMap:

endpoints = concatMap (\(a,b) -> [Left a, Right b])

Defining types

Another way in which types improve readability is that they hint at the semantics of a value.  Either is a very generic type, defining a newtype for interval endpoints might make things easier to understand.

Code organization

Related code should usually be grouped together.  The order, in which the local functions are defined, seems rather random.  Reorganizing those functions could benefit readability.

Variable naming

The variables (x:xs) a are shadowed in some functions.  That's confusing and will cause compiler warnings when compiled with -Wall.  I'd suggest renaming the outer (x:xs) to (y:ys).

This is just personal taste, but I'd also rename eitherValue to fromEither (in analogy to fromMaybe and fromJust).  This would make even more sense if a custom type was used (e.g. fromBorder).

Opinionated cleanup

Below is what I perceive as a cleaner version of this function.  It doesn't have the nice compactness of the original code, but uses the same basic algorithm.  The local functions are quite general and can easily be promoted to top level functions.  Reusable code is usually to be preferred.

import Data.Function (on)
import Data.List (group, sortBy)
type Border a = Either a a

disjoint' :: (Ord a) => [(a, a)] -> [(a, a)]
disjoint' = concatMap consecutiveBordersToIntervals
            . groupBalancedBorders
            . sortBy (compare `on` fromBorder)
            . intervalBorders
    where
      intervalBorders :: [(a, a)] -> [Border a]
      intervalBorders = concatMap $ \(x, y) -> [Left x, Right y]

      groupBalancedBorders :: [Border a] -> [[Border a]]
      groupBalancedBorders [] = []
      groupBalancedBorders xs = let (ys, zs) = spanBalancedBorders 0 xs
                                in ys : groupBalancedBorders zs

      spanBalancedBorders :: Int -> [Border a] -> ([Border a], [Border a])
      spanBalancedBorders _       []     = ([], [])
      spanBalancedBorders balance (x:xs) =
          let balance' = either (const $ balance + 1) (const $ balance - 1) x
          in case balance' of
               0 -> ([x],xs)
               _ -> let (ys,zs) = spanBalancedBorders balance' xs in (x:ys,zs)

      consecutiveBordersToIntervals :: (Eq a) => [Border a] -> [(a, a)]
      consecutiveBordersToIntervals =
          (\xs -> zip xs (tail xs)) . dedupSortedList . map fromBorder

      dedupSortedList :: (Eq a) => [a] -> [a]
      dedupSortedList = map head . group

      fromBorder :: Border a -> a
      fromBorder = either id id

This is as fast as the original, but arguably easier to read.  It also fixes a bug which caused empty intervals to be included.

>>> disjoint [(1,5), (5,10), (1,10)]
[(1,5),(5,5),(5,10)]
>>> disjoint' [(1,5), (5,10), (1,10)]
[(1,5),(5,10)]

As a final note, one should be aware that the algorithm makes some implicit assumptions on the topology of the intervals in a.  It would break down when intervals were allowed to have start points which are greater than their endpoint (think modular arithmetic).


Don't Repeat Yourself
Your main() function starts with 3 loops to initialize your table array. There are several problems here. First, it writes past the end of the array. If your array has n + 1 elements, then you can only write to 0 through n. Element n + 1 is out-of-bounds. So each of your loops is writing to one element of the next row, and then one extra row at the end, and one element past that, too. The loops should only go from 0 to n. This happens to work because you later read past the end of the array, too. If you're going to do that, you need to allocate n + 2 rows and columns.
Next, you're writing several elements 3 times. You can combine these 3 loops into 1 and do far less initialization. Further, you should use braces around all loop and conditional bodies because there's the potential to create errors in the future if you don't.
Also, you've switched i and j in the last loop which is highly confusing and could easily be missed by a reader.
Here's how I would write your initialization code:
table = new double [ n + 2 ][ n + 2 ]
for (int i = 0; i < n + 1; i++)
{
    for (int j = 0; j < k; j++)
    {
        if (i + j < k)
        {
            table [ i ][ j ] = 0.0;
        }
        else
        {
            table [ i ][ j ] = -1.0;
        }
    }

    for (int j = k; j < n + 1; j++)
    {
        table [ i ][ j ] = 1.0;
    }
}

Now no element should be touched more than once, no elements past the end of the array should be written to, and no array indexes are flipped.
You're also calculating (double)d / (double)s twice. You should calculate it once and re-use this value.
Naming
You should choose better names for your variables. i and j are fine for loop indexes as they are commonly used that way and nobody will be confused by them. However, I'd rename n, s, and k. I'd name n something descriptive like numThrows; k should be something like numNeeded, and s should be numSides.
Likewise, s, r, and d are not very helpful names for the arguments to game().
Speed
I haven't profiled your code, which is the real way to find out which parts are slow. I have seen many cases where casting variables from one type to another causes significant slowdowns. Since the bulk of your game() function is either calling itself or casting values, I recommend just making the arguments to the function be double to begin with. Of course, you can't use a double as an index into an array. So you could either pass the r and d values as both doubles and ints.


C++ implementation of Hackerrank's "Maximum Element in a Stack"

I believe to finish this within the time limit, you need to complete each of the three operations with \$O(1)\$ time complexity.

There are a number of variations in how you do that, but nearly all of them involve keeping track of the maximum value on the stack as you build the stack, rather than searching through all the existing stack items each time you receive a query. Given that this is an online challenge, I hesitate to go into a lot more detail on this point than that.

As far as the code style goes, the most obvious point would be that your compareValues isn't really necessary--std::less<T> will be used by default, and your comparison adds nothing it doesn't already do perfectly well. In fact, std::less<T> may be superior in one respect: it's defined as a function object--a class that overloads operator() to do the comparison. You'r defining an actual function, and passing a pointer to a function. Passing a function object tends to make it easier for a compiler to generate inline code, so letting std::less<T> do the job may well improve speed at least slightly.

One more (somewhat less obvious) point is that in the process of improving efficiency to the point that you can finish within the time limit, I'm (reasonably) confident that you'll eliminate the need to traverse the stack, so you should be able to use std::stack<int>.


Okay, I looked into the problem a bit deeper.

Currently, with your use case, you are doing a lot of multiplications which end up in zero anyway. Most of the image is namely black. You can easily skip all these multiplications by checking if the image block you are looping over is bigger than zero.
The two loops basically do a matrix multiplication. You are multiplying an image block with two vector values over which you loop. You can create a matrix which has all the possible combinations of Lo_D(p)*Lo_D(q) by taking the Kronecker product of Lo_D. Then you can simply do a matrix multiplication. and sum all elements over the matrix. However, it seems that this optimization is actually slower then the first one in this case. It might be the case that it is faster in other cases.
You are calculating each index of an array each time and afterwards you are summing it, this can be done in one line as well. The performance is however does not seem to increase or decrease.
Finally, you can do one minor optimization the for loop where you loop over Lo_D, you can also there check if an entire row is equal to zero. This is a small optimization but might give you something. Doing this another time in the next loop is useless.

Full code:

clear all;
close all;
clc

[Lo_D,Hi_D] = wfilters('coif1','d');

img = imread('tumor-1.jpg');
img = im2double(img);
figure;
imshow(img);
title('original image');

[nrows ncols] = size(img);
imgg = zeros(nrows+6,ncols+6);
imgg(1:nrows,1:ncols) = img(:,:);
figure;
imshow(imgg);

% Wavelet decomposition.
imgD_LL = zeros(size(img));
imgD_LH = zeros(size(img));
imgD_HL = zeros(size(img));
imgD_HH = zeros(size(img));

timgD_LL = zeros(size(img));
timgD_LH = zeros(size(img));
timgD_HL = zeros(size(img));
timgD_HH = zeros(size(img));

%% Optimization #1
tic
for i = 1:nrows
    for j = 1:ncols

        imgBlock = imgg((i+1):(i+numel(Lo_D)),(j+1):(j+numel(Hi_D)));

        if any(imgBlock(:) > 0)

            for p = 1:numel(Lo_D)
                for q = 1:numel(Hi_D)
                    tempqD_LL(q) = Lo_D(p)*Lo_D(q)*imgg(i+p,j+q);
                    tempqD_LH(q) = Lo_D(p)*Hi_D(q)*imgg(i+p,j+q);
                    tempqD_HL(q) = Hi_D(p)*Lo_D(q)*imgg(i+p,j+q);
                    tempqD_HH(q) = Hi_D(p)*Hi_D(q)*imgg(i+p,j+q);
                end
                if (length(tempqD_LL) == q)
                    tempQD_LL(p) = sum(tempqD_LL);
                    tempQD_LH(p) = sum(tempqD_LH);
                    tempQD_HL(p) = sum(tempqD_HL);
                    tempQD_HH(p) = sum(tempqD_HH);
                end

            end
            if (length(tempQD_LL) == p)
                timgD_LL(i,j) = sum(tempQD_LL);
                timgD_LH(i,j) = sum(tempQD_LH);
                timgD_HL(i,j) = sum(tempQD_HL);
                timgD_HH(i,j) = sum(tempQD_HH);
            end
        end
    end
end
toc

%% Optimization #2
% % Kronecker product
% LL = kron(Lo_D,Lo_D);
% LH = kron(Hi_D,Lo_D);
% HL = kron(Lo_D,Hi_D);
% HH = kron(Hi_D,Hi_D);
%
% % Reshape to matrix
% LL = reshape(LL,numel(Lo_D)*[1 1]);
% LH = reshape(LH,numel(Lo_D)*[1 1]);
% HL = reshape(HL,numel(Lo_D)*[1 1]);
% HH = reshape(HH,numel(Lo_D)*[1 1]);
%
% tic
% for i = 1:nrows
%     for j = 1:ncols
%
%         imgBlock = imgg((i+1):(i+numel(Lo_D)),(j+1):(j+numel(Hi_D)));
%
%         if any(imgBlock(:) > 0)
%             timgD_LL(i,j) = sum(sum(LL.*imgBlock));
%             timgD_LH(i,j) = sum(sum(LH.*imgBlock));
%             timgD_HL(i,j) = sum(sum(HL.*imgBlock));
%             timgD_HH(i,j) = sum(sum(HH.*imgBlock));
%         else
%             timgD_LL(i,j) = 0;
%             timgD_LH(i,j) = 0;
%             timgD_HL(i,j) = 0;
%             timgD_HH(i,j) = 0;
%         end
%     end
% end
% toc
%
%% Optimization #3
% tic
% for i = 1:nrows
%     for j = 1:ncols
%         tLL = 0;
%         tLH = 0;
%         tHL = 0;
%         tHH = 0;
%
%         imgBlock = imgg((i+1):(i+numel(Lo_D)),(j+1):(j+numel(Hi_D)));
%
%         if any(imgBlock(:) > 0)
%             for p = 1:numel(Lo_D)
%                 for q = 1:numel(Hi_D)
%                     tLL = Lo_D(p)*Lo_D(q)*imgg(i+p,j+q) + tLL;
%                     tLH = Lo_D(p)*Hi_D(q)*imgg(i+p,j+q) + tLH;
%                     tHL = Hi_D(p)*Lo_D(q)*imgg(i+p,j+q) + tHL;
%                     tHH = Hi_D(p)*Hi_D(q)*imgg(i+p,j+q) + tHH;
%                 end
%             end
%         end
%
%         timgD_LL(i,j) = tLL;
%         timgD_LH(i,j) = tLH;
%         timgD_HL(i,j) = tHL;
%         timgD_HH(i,j) = tHH;
%     end
% end
% toc
%
%% Original implementation
tic
for i = 1:nrows
    for j = 1:ncols
        for p = 1:numel(Lo_D)
            for q = 1:numel(Hi_D)
                tempqD_LL(q) = Lo_D(p)*Lo_D(q)*imgg(i+p,j+q);
                tempqD_LH(q) = Lo_D(p)*Hi_D(q)*imgg(i+p,j+q);
                tempqD_HL(q) = Hi_D(p)*Lo_D(q)*imgg(i+p,j+q);
                tempqD_HH(q) = Hi_D(p)*Hi_D(q)*imgg(i+p,j+q);
            end
            if (length(tempqD_LL) == q)
                tempQD_LL(p) = sum(tempqD_LL);
                tempQD_LH(p) = sum(tempqD_LH);
                tempQD_HL(p) = sum(tempqD_HL);
                tempQD_HH(p) = sum(tempqD_HH);
            end

        end
        if (length(tempQD_LL) == p)
            imgD_LL(i,j) = sum(tempQD_LL);
            imgD_LH(i,j) = sum(tempQD_LH);
            imgD_HL(i,j) = sum(tempQD_HL);
            imgD_HH(i,j) = sum(tempQD_HH);
        end
    end
end
toc

%%
% Check if they are the same, calculate difference and check if it is
% smaller then 5 machine epsilon because of numerical differences
all(all(timgD_LL - imgD_LL < 5*eps))
all(all(timgD_LH - imgD_LH < 5*eps))
all(all(timgD_HL - imgD_HL < 5*eps))
all(all(timgD_HH - imgD_HH < 5*eps))

% Plots Deconstruction..
figure;
subplot(2,2,1), imshow(timgD_LL, [min(min(timgD_LL)) max(max(timgD_LL))]), title('Img Deconstruction - LL filter');
subplot(2,2,2), imshow(timgD_LH, [min(min(timgD_LH)) max(max(timgD_LH))]); title('Img Deconstruction - LH filter');
subplot(2,2,3), imshow(timgD_HL, [min(min(timgD_HL)) max(max(timgD_HL))]); title('Img Deconstruction - HL filter');
subplot(2,2,4), imshow(timgD_HH, [min(min(timgD_HH)) max(max(timgD_HH))]); title('Img Deconstruction - HH filter');
figure;
subplot(2,2,1), imshow(imgD_LL, [min(min(imgD_LL)) max(max(imgD_LL))]), title('Img Deconstruction - LL filter');
subplot(2,2,2), imshow(imgD_LH, [min(min(imgD_LH)) max(max(imgD_LH))]); title('Img Deconstruction - LH filter');
subplot(2,2,3), imshow(imgD_HL, [min(min(imgD_HL)) max(max(imgD_HL))]); title('Img Deconstruction - HL filter');
subplot(2,2,4), imshow(imgD_HH, [min(min(imgD_HH)) max(max(imgD_HH))]); title('Img Deconstruction - HH filter');


Render elements from an array of objects

Two things right off the bat:

You're assuming that item.title and item.content are "safe" to insert. I.e. that they don't contain HTML, something that could be mistaken for HTML, or that if they contain HTML, it's meant to be there.

For instance, if title is "How to use the  tag", then the "" will be interpreted as HTML by the browser, and you won't get the right result.
Putting block elements (h1 and div) inside an inline element (a) is invalid HTML. (Edit: I was wrong - it's allowed, if you're using HTML5. Still invalid in earlier version, though. Tip 'o the hat to @dev-null for the correction). Anyway, your a elements hardly need to be a elements; you're handling all the interaction in JavaScript. They could just as well be div elements, or article elements or something else entirely.

Moving on. Janos already touched on how to improve makeElement, but I'd take it a step further.

I don't like the idea of defining a global function in an if/else to begin with, when said if/else could just as well be inside the function.

Using Janos' extracted createAnchor, you could simply define makeElement as:

function makeElement(item, top, left, includeContent) {
    var innerHTML = '
' + item.title + '
';
    if(includeContent) {
        innerHTML += '
' + item.content + '
';
    }
    return createAnchor(item, top, left, innerHTML);
}

The includeContent argument can probably be left out, since headlinesOnly seems to be a global (which is not a good thing, by the way). Here, I've made the argument "positive", as in "yes, do include content", since that's the part you're deciding on. Headlines are always present, so headlinesOnly is a bit of a double negation in the sense that true actually means "Yes, don't include content".

Overall, however, makeElement is poor name. Everything on the page is an element, so "make element" doesn't explain anything about the function's purpose. I don't know what your page is displaying, but I'm sure there's some more descriptive name for those elements; forget that they're HTML elements and consider instead what they're representing.

And while I used Janos' createAnchor, I'm not a huge fan of it. Using onevent-style attributes is not good practice. It's been outmoded for many years now.

Instead you should use addEventListener to attach event handling functions to your elements.

This would also mitigate the other big no-no you're committing: window['something'] = function ....

First of all, why not just say window.something = ... instead of the bracket/subscript? Using brackets is only useful if you want to access a property using a dynamic string. Here, the strings are hardcoded so it makes no difference.

But much more importantly, why are you declaring so many global functions? It's plain bad practice to pollute the global namespace like that.

Again, using addEventListener would avoid all that.

I'm also wondering why the behavior is different for touch vs mouse interaction. If I drag on a touch screen, the touchend event is ignored. But if I drag with a mouse, the mouseup event is not ignored. So why not use the click event instead?

Of course, click does have a delay on many touch screen clients, since the device is waiting to see if there's a 2nd tap, i.e. if it's a double-tap that's meant to zoom or some similar "meta-interaction". Whereas on with a mouse and keyboard there's no inherent meaning to a double-click, hence there's no delay.

So maybe keep the touchstart/move/end handlers for touch screens, but just use click for mouse events.

Lastly, as idle speculation, do you need to absolutely position your elements? You could make "column" elements instead, arranged side-by-side with CSS, and simply add your item elements to those. The browser would figure out how to do the layout. But I don't know the particulars of your page.

Here's one way to factor the code. Not saying it's perfect (far from it), but there's no duplication:

function createItemElement(item, includeContent) { // still not a great name
  var element = document.createElement('div'), // not an
      heading = document.createElement('h1'),
      content;

  heading.innerHTML = item.title; // NOTE: I'm *assuming* the title is "safe" to insert as HTML
  element.appendChild(heading);

  if(includeContent) {
    content = document.createElement('div');
    content.innerHTML = item.content; // NOTE: See the other note
    element.appendChild(content);
  }

  addItemClickListener(item, element);

  return element;
}

function addItemClickListener(item, element) {
  var touchmove;

  // define what should happen on click/tap
  function openItemUrl(event) {
    isTouch && cycript ? tryOpenUrl(item.url) : window.open(url, '_blank');
  }

  if(isTouch) {
    touchmove = function (event) {
      // remove move/end listeners in case of touchmove
      element.removeEventListener('touchend', openItemUrl);
      element.removeEventListener('touchmove', touchmove);
    };

    element.addEventListener('touchstart', function () {
      // only add the move/end listeners when a touchstart occurs
      element.addEventListener('touchmove', touchmove);
      element.addEventListener('touchend', openItemUrl);
    });
  } else {
    element.addEventListener('click', openItemUrl);
  }
}

// ....

// basic usage
var itemElement = createItemElement(item, !headlinesOnly);
itemElement.style.top = ...;
itemElement.style.left = ...;
container.appendChild(itemElement);

Here, createItemElement doesn't care about positioning; it just creates an element, and then it's up to you to do something with it. Likewise, it knows nothing about touch vs mouse; that's all contained in addItemClickListener. And the event handling doesn't use an explicit drag boolean; it just adds and removes the event listeners as needed.

Either function knows as little as possible, while the things that always change (positioning) is simply handled directly without being passed via arguments.

Optimally, the isTouch and cycript (whatever that is) variables wouldn't need to be global either, as they're what's creating the most coupling right now; addItemClickListener depends on both being present, while createItemElement is much better off just relying only on its arguments (and, well, on document, but that's a pretty safe thing to rely on in a browser).

I've also been a bit pedantic in building the elements, explicitly creating them with document.createElement. I'm just not a fan of defining chunks of HTML as strings. Besides, with this, you can more easily control how the title and content is added to the elements.


Instead of the loop, we can use std::all_of() (or std::any_of() with the opposite condition).  That can make the code clearer, because it signals intent at the beginning, and we don't need to unpick control flow as we do with for/return.  With C++20, we are able to pass a range object such as std::string as argument instead of an iterator pair (as we do in C++17).
And we have std::isalnum(), which is likely implemented as a lookup table like this (with the caveat that we need to be careful about signed char).  It's more portable (the code we have will be wrong if there are non-alphabetic characters between A and Z, as there are on EBCDIC systems, for example) and easier to get right (witness the typo - Z instead of z - that means on ASCII-like systems we allow no lower-case letters).
We could change the interface to just return the error string, with a null pointer indicating success, to avoid the "out" parameter.
#include <algorithm>
#include <cctype>
#include <string>

// return a null pointer if valid, else a pointer to the error message
const char *check_username_valid(const std::string& str)
{
    if (str.length() < MinUsernameLen) { return "Username Too Short"; }
    if (str.length() > MaxUsernameLen) { return "Username Too Long"; }
    auto const char_permitted
        = [](unsigned char c){ return c == '_' || std::isalnum(c); };

    if (std::all_of(str.begin(), str.end(), char_permitted)) {
        return nullptr;
    }

    return "Invalid Character in Username";
}

If we'll be adding more permitted username characters, we might want to use the lookup-table approach - but we don't need a new type, and this static const can be built at compilation time:
#include <array>
#include <climits>

bool legal_username_char(unsigned char c)
{
    static auto const table
        = []{
              std::array<bool,UCHAR_MAX+1> a;
              for (unsigned char i = 0;  i++ < UCHAR_MAX; ) {
                  a[i] = std::isalnum(i);
              }
              // additional non-alnum chars allowed
              a['_'] = true;
              return a;
          }();
    return table[c];
}

That idiom is an immediately-invoked lambda, and it's very handy for creating complex constants like this.  Note also the use of UCHAR_MAX rather than making assumptions about the size of the type.
Minor: no need for cast to int when indexing (a[int(((unsigned char)(x)))]).  An unsigned char is perfectly fine as array index.


Not all counting problems require enumerating the items being counted. If you were asked to count how many sheep there are in total if there are \$n\$ trucks with \$k\$ sheep each, you could write something like:

total_sheep = 0
for truck in range(n):
    for sheep in range(k):
        total_sheep += 1

Or you could cut to the chase and compute it as:

total_sheep = n * k

The problem you are trying to solve is more subtle, but can be attacked in a similar fashion. Modular arithmetic will be your friend in doing this. Rather than looking at the setting times as single numbers, convert them to tuples of (quotient, remainder) after dividing by \$X\$. This would e.g. convert the list of times for the second example into:

 5 --> (0, 5)
22 --> (3, 1)
17 --> (2, 3)
13 --> (1, 6)
 8 --> (1, 1)

We can use this information to prune the list of alarms: if any two alarms have the same remainder, they will ring at the same time, so we only need to keep the smaller one. This would convert the above list, after also sorting it, into:

 5 --> (0, 5)
 8 --> (1, 1)
13 --> (1, 6)
17 --> (2, 3)

Those two numbers tell us in which of the \$X\$ minute periods the alarm sounds for the first time, and at what offset into that period does it first go off. So we can process it sequentially and know that:

at the end of the first (0) period, 1 alarm has sounded for the first time, a total of 1 alarm will sound in every subsequent period, and the total number of alarms sounded is also 1.
at the end of the second (1) period, 2 alarms have sounded for the first time, 3 alarms will sound in every subsequent period, and the total number of alarms sounded is 4.
at the end of the third (2) period, 1 new alarm has sounded, 4 alarms will sound every period, and a total of 8 alarms will have sounded.

Since there are no more alarms to process, we have 8 alarms so far, 4 more sounding each period, and want to reach a total of 12, some simple math tells us that this will happen during the fourth (3) period, and that it will be the last of the alarms that will reach it.

To make the math more clear, lets imagine that we wanted to reach a total of 14 alarms instead. Since 8 have already sounded, we have 14 - 8 = 6 more to go. Since 4 alarms will sound in each period, and the quotient and remainder of 6 divided by 4 are 1 and 2, we know that we will reach our target after 1 full more period, plus 2 of the four alarms in the next period. This translates to 4 full periods, plus the time for the second alarm in that period to sound. The time of 4 full periods is 7 * 4 = 28. We need to add the offset of the second alarm when sorting them by offset, not by start time, so we need to add 3, not 1, and the end result would be 31.

This general outline omits many gruesome details, like what to do if we reach the target number of alarms before we finish processing the list. And the math described above is hard to get right in all corner cases, as there are many chances for off-by-one errors. I'm not going to spoil the fun for you by coding it up: give a try, and I'll be happy to review your next version.


1. Don't use using namespace std

That's generally considered bad practice.

Rather use

using std::cout;
using std::cin;
using std::string;

if you want to avoid typing these out.

2. Use interfaces properly and don't mix them up with abstract class implementations

Instead of simply declaring an abstract class, sort out specific interfaces in 1st place

struct IEmployee {
      virtual const& string name() const = 0; // see 3. regarding const please
      virtual const float& salary() const = 0;
      virtual bool managesOtherEmployees() const = 0; // equivalent to isLeaf() in the
                                                      // common composite pattern
                                                      // examples
      virtual void work() = 0;
};

Add functionality as needed:

struct IManager {
    void add(IEmployee&) = 0;
    void delete(IEmployee&) = 0; // if you have functions to extend the
                                 // composition, you probably want to have
                                 // the reverse operation if reasonable.
                                 // Here it seems to be so, since managers
                                 // sometimes need to fire team members.
};

Provide the abstract class for the common implementation

class Employee : public IEmployee {
private:
    string name_; // Don't use prefix '_' for symbols, these are reserved
                    // for the compiler and standard library implementations (see 4.)
    float salary_;
public:
    Employee(string name, float salary) : name_(name), salary_(salary) {}
    string name() const override {
        return name_;
    }
    float salary() const override {
        return salary_;
    }
    bool managesOtherEmployees() const override { return false; }
};

2. leads to an implementation of Developer and Manager classes as follows:

class Developer : public Employee {
public:
    Developer(string name,float salary) : Employee(name,salary) {}
    void work() {
         cout << "Developer " << name() << " Worked\n";
         // A developer works own.
    }
};

class Manager : public Employee, public IManager {
private:
    vector<std::reference_wrapper<IEmployee>> team_;
public:
    Manager(string name, float salary) : Employee(name,salary) {}
    bool managesOtherEmployees() const override { return true; }
    void add(IEmployee& emp) override {
        team_.push_back(std::reference_wrapper<IEmployee>(emp));
    }
    void delete(IEmployee& emp) override {
        std::remove(team_.begin(),team_.end(),std::reference_wrapper<IEmployee>(emp));
    }
    void work() {
        cout << "Manager " << name() << " Distributed Work\n";
        for(auto& emp : team_) { // Use range based loops and auto whenever possible (see 5.)
            emp.work();
        }
        // A manager distributes work in team members.
     }
     float salary() const override {
        float accumulatedSalary = 0.0;
        for(const auto& emp : team_) { // Note const and reference again
            accumulatedSalary += emp.salary() +15000;
        }
        return accumulatedSalary;
        // Salary of a manager is derived from team members.
     }
};

3. Use const qualifiers as much as possible

If you're declaring a class operation (class member function), decide if this should change the class state in first place.
Append a const qualifier, if you decide it shouldn't.

Same for parameters and return values. Usually you don't have to worry about which method by value or by const reference will be more efficient.
With any sophisticated, modern c++ compiler, you can assume the most efficient emitted assembly code will be chosen.

Passing/returning by value, still might be prone to generate copies if RVO isn't applicable. Thus I simply prefer to be explicit about that.

4. Don't use symbol names prefixed with _

Symbol names prefixed with a single or double underscore (_) are preserved by the c++ standard for compiler internals and standard library implementations.

It's easy to come over that just using underscores as a postfix for symbols as indication of class member variables:

template<typename TValue>
class MyClass {
private:
     TValue myValue_;
public:
     MyClass(const TValue& myValue) : myValue_(myValue) {}
     const TValue& myValue() { return myValue_; } // standard getter signature
     void myValue(const & TValue value) { myValue_ = value; } // standard setter signature
};

The above pattern will serve 98% of cases unambiguously quite well.

5. Use range based loop syntax beyond c++98

Since c++11 standard was established, the language supports range based for() loops of the form

for(<type spec> el : <container_ref>) { /* ... */ }

You should use the auto keyword for <type spec>, it can be garnished with const and & as usual, and automatically evaluates a dereferenced Iterator when enumerating the Containers values.


As someone who's been working with your project and your Console Gui here's my 2 cents:

protected final TextArea textArea = new TextArea();
protected final TextField textField = new TextField();

these could use a rename. The names do not contain any information and in all the unit tests you wrote, this was confusing me very much: Which is in, which is out?

I'd rather have something like:

protected final TextArea output = new TextArea();
protected final TextField input = new TextField();

textField.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
    //long block of code...

I like very much that you are using a comprehensively wired lambda. I don't like that you are mixing abstraction levels here. on the one hand, you have that "I configure my console" code like textArea.setEditable(false), and then you have that switch (keyEvent.getCode())

Personally I'd have instead extracted the handler code to a separate handler (which needs a better name than what I am about to propose):

private final EventHandler<KeyEvent> keyReleasedHandler = new EventHandler<>() {
        handle(final KeyEvent keyEvent){
            //your code here
        }
    }
textField.setOnKeyReleased(keyReleasedHandler);

This also makes it easier to understand, where your constructor ends, without seeing the method signature that follows. While we're at it:

    setCenter(textArea);

    //here comes the whole event handling

    setBottom(textField);

Why not put together what belongs together. Both of these are layouting commands, the other two are behavior commands. I'd go for:

setCenter(output);
setBottom(input);

output.setEditable(false);
input.setOnKeyReleased(keyReleasedHandler);

Other than that, your code is very concise and understandable. I like your defensive programming style ;)


Finding number of days until a certain date

const currentDay = moment().format('D');

You use .format() a lot, instead use Moment.js's getters like .date(). This way you also don't have to use parseInt() since the getters return number's.

What about this solution:

const getDaysTillSalary = (day) => {
  let date = moment();
  let days = 0;
  while(date.date() !== 8) {
    date = date.add(1, 'day');
    days++;
  }
  return days;
}

It creates a variable and stores the current Moment.js date in it. Then it repeatedly adds one day using .add() and counts up until date.date() (the day of the month) returns 8. The days variable is then returned.


Simple TicTacToe game, played by two simple A.I. players

Bugs

if(m==((s[1]&s[4]&s[7])
        |(s[0]&s[3]&s[6])
        |(s[2]&s[5]&s[8])
        |(s[6]&s[7]&s[8])
        |(s[3]&s[4]&s[5])
        |(s[0]&s[1]&s[2])
        |(s[2]&s[4]&s[6])
        |(s[0]&s[4]&s[8]))){

Does this even work? It seems to me that you are trying to test m to each of the above values, but what you are really doing is a binary math operation of & and |. Let me explain...

& "and"s each of the bits in the number, e.g.:

13&19

13:   0 1 1 0 1
17: & 1 0 0 0 1
      0 0 0 0 1

See what happened? 1 and 1 becomes 1, and every other combination becomes 0.

| "or"s the bits:

13:   0 1 1 0 1
17: | 1 0 0 0 1
      1 1 1 0 1

Similar to &, but 0 and 0 result in 0, and every other combination 1.

What is happening is that the char ASCII values are &'d and |'d. Is this really what you want? In this case, you have to do it the tedious way: test each of them to m:

    if (((m == board[1] && m == board[4] && m == board[7])
            || (m == board[0] && m == board[3] && m == board[6])
            || (m == board[2] && m == board[5] && m == board[8])
            || (m == board[6] && m == board[7] && m == board[8])
            || (m == board[3] && m == board[4] && m == board[5])
            || (m == board[0] && m == board[1] && m == board[2])
            || (m == board[2] && m == board[4] && m == board[6])
            || (m == board[0] && m == board[4] && m == board[8]))) {
        return m;
    }

Same here:

if((m==(b.s[a]&b.s[d]))&((b.s[c])==' ')){
    return c;
}
else if(((b.s[a]&b.s[c])==m)&&(b.s[d]==' '))
    return d;
else if(((b.s[d]&b.s[c])==m)&&(b.s[a]==' '))
    return a;
else
    return 9;
}

Becomes:

int checkArray(int a, int d, int c, Mark m, Board b) {
    if ((m == b.getBoard()[a] && m == b.getBoard()[d]) && ((b.getBoard()[c]) == Mark.NONE)) {
        return c;
    } else if ((m == b.getBoard()[a] && m == b.getBoard()[c]) && (b.getBoard()[d] == Mark.NONE)) {
        return d;
    } else if ((m == b.getBoard()[d] && m == b.getBoard()[c]) && (b.getBoard()[a] == Mark.NONE)) {
        return a;
    }
    return 9;
}

Formatting

I can't even read your code. Format it better; in an IDE, you can find a formatting option. In eclipse, it's Source->Format.

If you don't use an IDE, I suggest you install one. Eclipse is available here. Choose the installer, or the "Eclipse IDE for Java Developers" option.

Naming

public class tttmodimproved{

tttmodimproved is not only a bad name, it is also hard to read and understand. Cramming too much information in names is bad. Sure, names like class are bad, but so is thisclassdoesfooandbarwhilealsodoingotherstuff. That's what class-level javadoc comments are for.

As for readability, java class names are in PascalCase, and method and variable names in camelCase.

I suggest TicTacToe, and you can add a short comment about the class at the beginning, like so:

/**
 * ...
 */
public class TicTacToe {
    // ...

Other naming fixes:

cp -> changePlayer
p1 -> player1
p2 -> player2
b -> board
p -> currentPlayer
s -> board
tc: What does this even do?
...

I give up. Let's see what we have so far:

public class TicTacToe {

    static int turn = 0;

    public static void main(String[] args) {
        System.out.println("Let's play TicTacToe");
        char isWin = ' ';
        Board board = new Board();
        Player player1 = new Player('X');
        Player player2 = new Player('O');
        Player currentPlayer;
        for (board.tc = 0; board.tc < 9; board.tc++) {
            currentPlayer = changePlayer(player1, player2);
            board.updateBoard(currentPlayer, currentPlayer.getMove(board));
            isWin = board.checkWin(currentPlayer);
            board.showBoard();
            if (isWin != ' ')
                break;
        }
        if (isWin != ' ')
            System.out.println("congrats! " + isWin + " won the game.");
        else
            System.out.println("tie");

    }

    static Player changePlayer(Player p1, Player p2) {
        if (turn == 0) {
            turn = 1;
            return p1;
        } else if (turn == 1) {
            turn = 0;
            return p2;
        } else
            return p1;
    }

}

class Board {

    char[] board = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
    int tc = 0;

    char checkWin(Player p) {
        char m = p.mark;
        if (m == ((board[1] & board[4] & board[7]) | (board[0] & board[3] & board[6]) | (board[2] & board[5] & board[8])
                | (board[6] & board[7] & board[8]) | (board[3] & board[4] & board[5]) | (board[0] & board[1] & board[2])
                | (board[2] & board[4] & board[6]) | (board[0] & board[4] & board[8]))) {
            return m;
        }
        return (' ');
    }

    void showBoard() {
        System.out.println("");
        System.out.println(" " + board[6] + " | " + board[7] + " | " + board[8] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[3] + " | " + board[4] + " | " + board[5] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[0] + " | " + board[1] + " | " + board[2] + " ");
        System.out.println("");
    }

    void updateBoard(Player player, int move) {
        board[move] = player.mark;
    }

}

class Player {
    char mark = ' ', markOpo = ' ';

    Player(char mark) {
        this.mark = mark;
        System.out.println("player created with mark: " + this.mark);
        if (this.mark == 'X') {
            markOpo = 'O';
        } else
            markOpo = 'X';
    }

    int getMove(Board b) {
        int move = 9;
        if (b.tc > 2) {
            move = check(mark, b);
            if (move == 9) {
                move = check(markOpo, b);
            }
        }
        while ((move > 8) || (b.board[move] != ' ')) {
            move = (int) (Math.random() * 9);
        }
        return move;
    }

    int check(char m, Board b) {
        int mo;
        mo = checkArray(6, 7, 8, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(3, 4, 5, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 1, 2, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 3, 6, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(1, 4, 7, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(2, 5, 8, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 4, 8, m, b);

        if (mo != 9)
            return mo;
        mo = checkArray(2, 4, 6, m, b);

        if (mo != 9)
            return mo;
        else
            return mo;

    }

    int checkArray(int a, int d, int c, char m, Board b) {
        if ((m == (b.board[a] & b.board[d])) & ((b.board[c]) == ' ')) {
            return c;
        } else if (((b.board[a] & b.board[c]) == m) && (b.board[d] == ' '))
            return d;
        else if (((b.board[d] & b.board[c]) == m) && (b.board[a] == ' '))
            return a;
        else
            return 9;
    }

}

Now let's do some actual reviewing...

OOP

Java is an Object Oriented Programming (OOP) language, which means it's based on objects. You did a good job trying, but if you leave a default constructor and let the calling code do the work, it's not OOP at all. Let's do some serious redesigning:

public class TicTacToe {

    public static void main(String[] args) {
        System.out.println("Let's play TicTacToe");
        Mark win = Mark.NONE;
        Board board = new Board();
        Player player1 = new Player(Mark.X);
        Player player2 = new Player(Mark.O);
        Player currentPlayer = null;
        for (int tc = 0; tc < 9; tc++) {
            currentPlayer = switchPlayer(currentPlayer, player1, player2);
            board.updateBoard(currentPlayer, currentPlayer.getMove(board));
            win = board.checkWin(currentPlayer);
            board.showBoard();
            if (win != Mark.NONE) {
                break;
            }
        }
        if (win != Mark.NONE)
            System.out.println("congrats! " + win + " won the game.");
        else
            System.out.println("tie");

    }

    private static Player switchPlayer(Player currentPlayer, Player player1, Player player2) {
        if (currentPlayer == player1) {
            return player2;
        }
        return player1;
    }

}

class Board {

    private Mark[] board = { Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE };
    private int tc = 0;

    public Board() {

    }

    public Mark[] getBoard() {
        return board;
    }

    public int getTC() {
        return tc;
    }

    public void setTC(int tc) {
        this.tc = tc;
    }

    public Mark checkWin(Player p) {
        Mark m = p.getMark();
        if (((m == board[1] && m == board[4] && m == board[7]) || (m == board[0] && m == board[3] && m == board[6])
                || (m == board[2] && m == board[5] && m == board[8])
                || (m == board[6] && m == board[7] && m == board[8])
                || (m == board[3] && m == board[4] && m == board[5])
                || (m == board[0] && m == board[1] && m == board[2])
                || (m == board[2] && m == board[4] && m == board[6])
                || (m == board[0] && m == board[4] && m == board[8]))) {
            return m;
        }
        return Mark.NONE;
    }

    public void showBoard() {
        System.out.println("");
        System.out.println(" " + board[6] + " | " + board[7] + " | " + board[8] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[3] + " | " + board[4] + " | " + board[5] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[0] + " | " + board[1] + " | " + board[2] + " ");
        System.out.println("");
    }

    public void updateBoard(Player player, int move) {
        board[move] = player.getMark();
    }

}

class Player {

    private Mark mark = Mark.NONE;
    private Mark markOpo = Mark.NONE;

    public Player(Mark mark) {
        this.mark = mark;
        System.out.println("player created with mark: " + this.mark);
        if (this.mark == Mark.X) {
            markOpo = Mark.O;
        } else {
            markOpo = Mark.X;
        }
    }

    public Mark getMark() {
        return mark;
    }

    public int getMove(Board b) {
        int move = 9;
        if (b.getTC() > 2) {
            move = check(mark, b);
            if (move == 9) {
                move = check(markOpo, b);
            }
        }
        while (move > 8 || b.getBoard()[move] != Mark.NONE) {
            move = (int) (Math.random() * 9);
        }
        return move;
    }

    int check(Mark mark, Board board) {
        int mo;
        mo = checkArray(6, 7, 8, mark, board);
        if (mo != 9)
            return mo;
        mo = checkArray(3, 4, 5, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 1, 2, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 3, 6, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(1, 4, 7, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(2, 5, 8, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(0, 4, 8, mark, board);

        if (mo != 9)
            return mo;
        mo = checkArray(2, 4, 6, mark, board);

        if (mo != 9)
            return mo;
        else
            return mo;

    }

    private int checkArray(int a, int d, int c, Mark m, Board b) {
        if ((m == b.getBoard()[a] && m == b.getBoard()[d]) && ((b.getBoard()[c]) == Mark.NONE)) {
            return c;
        } else if ((m == b.getBoard()[a] && m == b.getBoard()[c]) && (b.getBoard()[d] == Mark.NONE)) {
            return d;
        } else if ((m == b.getBoard()[d] && m == b.getBoard()[c]) && (b.getBoard()[a] == Mark.NONE)) {
            return a;
        }
        return 9;
    }

}

enum Mark {
    NONE, X, O;

    @Override
    public String toString() {
        switch (this) {
        case NONE:
            return " ";
        case O:
            return "O";
        case X:
            return "X";
        default:
            return "";
        }
    }
}

A little explanation in the changes I made:

char is now Mark. It's more OOP that way, as char don't exactly represent a mark that a player makes.
default level methods are now either public or private. OOP people don't like default privacy methods.
turn variable in the Main class is now gone.

Now, moving to other changes:

The check method can be improved.

    if (mo != 9)
        return mo;
    else
        return mo;

This statement is redundant. It says, if mo is not 9, then return the value of mo. Otherwise, return the value of mo.

That can easily be:

    return mo;

    mo = checkArray(6, 7, 8, mark, board);
    if (mo != 9)
        return mo;
    mo = checkArray(3, 4, 5, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(0, 1, 2, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(0, 3, 6, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(1, 4, 7, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(2, 5, 8, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(0, 4, 8, mark, board);

    if (mo != 9)
        return mo;
    mo = checkArray(2, 4, 6, mark, board);

A lot of repetition here. Use loops:

int check(Mark mark, Board board) {
    int mo;
    // rows
    for (int i = 0; i < 9; i += 3) {
        mo = checkArray(i, i + 1, i + 2, mark, board);
        if (mo != 9) {
            return mo;
        }
    }
    // columns
    for (int i = 0; i < 3; i++) {
        mo = checkArray(i, i + 3, i + 6, mark, board);
        if (mo != 9) {
            return mo;
        }
    }
    // diagonals
    mo = checkArray(0, 4, 8, mark, board);
    if (mo != 9) {
        return mo;
    }

    mo = checkArray(2, 4, 6, mark, board);
    return mo;

}

Final Code:

public class TicTacToe {

    public static void main(String[] args) {
        System.out.println("Let's play TicTacToe");
        Mark win = Mark.NONE;
        Board board = new Board();
        Player player1 = new Player(Mark.X);
        Player player2 = new Player(Mark.O);
        Player currentPlayer = null;
        for (int tc = 0; tc < 9; tc++) {
            currentPlayer = switchPlayer(currentPlayer, player1, player2);
            board.updateBoard(currentPlayer, currentPlayer.getMove(board));
            win = board.checkWin(currentPlayer);
            board.showBoard();
            if (win != Mark.NONE) {
                break;
            }
        }
        if (win != Mark.NONE)
            System.out.println("congrats! " + win + " won the game.");
        else
            System.out.println("tie");

    }

    private static Player switchPlayer(Player currentPlayer, Player player1, Player player2) {
        if (currentPlayer == player1) {
            return player2;
        }
        return player1;
    }

}

class Board {

    private Mark[] board = { Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE, Mark.NONE };
    private int tc = 0;

    public Board() {

    }

    public Mark[] getBoard() {
        return board;
    }

    public int getTC() {
        return tc;
    }

    public void setTC(int tc) {
        this.tc = tc;
    }

    public Mark checkWin(Player p) {
        Mark m = p.getMark();
        if (((m == board[1] && m == board[4] && m == board[7]) || (m == board[0] && m == board[3] && m == board[6])
                || (m == board[2] && m == board[5] && m == board[8])
                || (m == board[6] && m == board[7] && m == board[8])
                || (m == board[3] && m == board[4] && m == board[5])
                || (m == board[0] && m == board[1] && m == board[2])
                || (m == board[2] && m == board[4] && m == board[6])
                || (m == board[0] && m == board[4] && m == board[8]))) {
            return m;
        }
        return Mark.NONE;
    }

    public void showBoard() {
        System.out.println("");
        System.out.println(" " + board[6] + " | " + board[7] + " | " + board[8] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[3] + " | " + board[4] + " | " + board[5] + " ");
        System.out.println("---|---|---");
        System.out.println(" " + board[0] + " | " + board[1] + " | " + board[2] + " ");
        System.out.println("");
    }

    public void updateBoard(Player player, int move) {
        board[move] = player.getMark();
    }

}

class Player {

    private Mark mark = Mark.NONE;
    private Mark markOpo = Mark.NONE;

    public Player(Mark mark) {
        this.mark = mark;
        System.out.println("player created with mark: " + this.mark);
        if (this.mark == Mark.X) {
            markOpo = Mark.O;
        } else {
            markOpo = Mark.X;
        }
    }

    public Mark getMark() {
        return mark;
    }

    public int getMove(Board board) {
        int move = 9;
        if (board.getTC() > 2) {
            move = check(mark, board);
            if (move == 9) {
                move = check(markOpo, board);
            }
        }
        while (move > 8 || board.getBoard()[move] != Mark.NONE) {
            move = (int) (Math.random() * 9);
        }
        return move;
    }

    int check(Mark mark, Board board) {
        int mo;
        // rows
        for (int i = 0; i < 9; i += 3) {
            mo = checkArray(i, i + 1, i + 2, mark, board);
            if (mo != 9) {
                return mo;
            }
        }
        // columns
        for (int i = 0; i < 3; i++) {
            mo = checkArray(i, i + 3, i + 6, mark, board);
            if (mo != 9) {
                return mo;
            }
        }
        // diagonals
        mo = checkArray(0, 4, 8, mark, board);
        if (mo != 9) {
            return mo;
        }

        mo = checkArray(2, 4, 6, mark, board);
        return mo;

    }

    private int checkArray(int a, int d, int c, Mark m, Board b) {
        if ((m == b.getBoard()[a] && m == b.getBoard()[d]) && ((b.getBoard()[c]) == Mark.NONE)) {
            return c;
        } else if ((m == b.getBoard()[a] && m == b.getBoard()[c]) && (b.getBoard()[d] == Mark.NONE)) {
            return d;
        } else if ((m == b.getBoard()[d] && m == b.getBoard()[c]) && (b.getBoard()[a] == Mark.NONE)) {
            return a;
        }
        return 9;
    }

}

enum Mark {
    NONE, X, O;

    @Override
    public String toString() {
        switch (this) {
        case NONE:
            return " ";
        case O:
            return "O";
        case X:
            return "X";
        default:
            return "";
        }
    }
}


Each function on its own

Let us have a look at each of your functions first in solitude. What does summation do?

summation :: (Integral a, Fractional b) => a -> a -> (a -> b) -> b
summation i n e = if (i < n)
                  then (e i + summation (i+1) n e)
                  else (e i)

Well, for all numbers from x in i to n, sum the e x. We can write this a lot more clear with a list comprehension:

summation :: (Enum n, Num a) => n -> n -> a
summation i n e = sum [e x | x <- [i..n]]

Note that this only holds if i is always lesser than n in the inital call.

Next, what does mean do?

mean :: (Real a, Fractional b) => [a] -> b
mean x = (1 / (genericLength x)) *
         (summation 1 (length x) (\i -> realToFrac (x !! (i-1))))

Uh, that looks complicated. First, let us rewrite it as proper fraction:

mean x = num / denom
  where
    num   = summation 1 (length x) (\i -> realToFrac (x !! (i-1)))
    denom = genericLength x

Much easier to read. So, what do you actually do in num? You calculate the sum of all numbers in x. However, this can be done with sum already. We end up with

mean :: Fractional a => [a] -> a
mean xs = sum xs / genericLength xs

Note that lists are usually named with a suffix s. One x, multiple xs.

We use the same approach on covariance. First, we rewrite it in simpler terms:

covariance x y = num / denom
  where
    num        = summation 1 (length x) elemwise
    denom      = genericLength x
    elemwise i = (realToFrac (x !! (i-1)) - mean x) * (realToFrac (y !! (i-1)) - mean x))

And now we immediately spot an error in elemwise. You wrote y !! (i-1) - mean x, but you meant y !! (i - 1) - mean y.

However, let us have a look at the mathematical definition again:

$$
cov(X,Y) = E\left[(X-E[X])*(Y-E[Y])\right]
$$

Allright. Let's write this exactly down as it stands there:

covariance x y = mean productXY
  where
   productXY = pairwiseProduct xSubMean ySubMean
   xSubMean  = subtractMean x
   ySubMean  = subtractMean y

This is obviously not ready yet. What are pairwiseProduct and subtractMean?

subtractMean :: Fractional a => [a] -> [a]
subtractMean xs = [x - mx | x <- xs]
  where
    mx = mean xs

pairwiseProduct :: Num a => [a] -> [a] -> [a]
pairwiseProduct xs ys = zipWith (*) xs ys

Now we're done. Note how the covariance almost looks like pseudo-code? It's clearly easy to read by a human. That's the most important point you should take from this review: make your code easy to read for yourself.

stddev xs is just sqrt (covariance xs xs), so you should probably use that:

-- sqrt needs Floating
stddev :: Floating a => [a] -> a
stddev xs = sqrt (covariance xs xs)

Everything at once

After we've finished our rewrite, it turns out you don't need summation at all. So what do we end up with?

mean :: Fractional a => [a] -> a
mean xs = sum xs / genericLength xs

covariance :: Fractional a => [a] -> [a] -> a
covariance xs ys = mean productXY
  where
   productXY = zipWith (*) [x - mx | x <- xs] [y - my | y <- ys]
   mx        = mean xs
   my        = mean ys

stddev :: Floating a => [a] -> a
stddev xs = sqrt (covariance xs xs)

pearson :: (Floating a) => [a] -> [a] -> a
pearson x y = covariance x y / (stddev x * stddev y)

Note that covariance got a lot easier to read due to bindings.

Please keep in mind that this implementation has some performance related issues. Especially the mean implementation is a poster child for a function that leaks memory, but for small lists you should be fine.

Working with lists

When you work with lists, avoid element-wise access. It's really slow. Instead, you want to transform the whole map into a single value (a fold, e.g. length or sum), or into another map (above with list comprehensions, e.g. [x - mx | x <- xs]).


Project Euler - #5 smallest multiple (Ruby using a hash table)

Theoretical Code Evaluation
Let's do some math to see how many operations you are doing.
I'm going to use m as my variable for whatever value you assigned to multiple
You have a loop that for every multiple of m, it does m modulus tests.
For m = 10, the correct answer is 2520, so we can calculate that you code did 2520/m*m = 2520 operations  For m = 13 the correct answer is 360360, which is also the same number of operations performed.  This doesn't seem too bad.
However you are also calling hash.has_value? every iteration.  If you look at the source code for this, it loops through every value in the hash.  This means that in the first iteration, the hash has one value and this is one operation. In the second iteration hash has two values (requiring  two operations) but now we've done a total of three operations between the first and second iteration.  In the third iteration there are three operations which makes for a combined total of 6 operations.  After the fourth iteration we've done a total of 10 operations.  This is a series of the sum of natural numbers and the formula for it is:

So when m = 10 you do 2520 + (252 * 253 / 2) = 34,398 operations.
When m = 13 you do 360360 + (27720 * 27721 / 2) = 384,573,420 operations.  This is not good.
Practical Code Evaluation
Now that we think we know what the code is doing, we can profile it to see what it is actually doing.  I generated these numbers on your code using the ruby-prof gem after setting multiple = 13.  (This is just a portion of the output)
Total: 165.979596

 %self      total      self      wait     child     calls  name
 56.63    165.679    93.988     0.000    71.690    27722   Hash#has_value?
 43.19     71.690    71.690     0.000     0.000 384240778   Fixnum#==
  0.13      0.215     0.215     0.000     0.000    27720   Range#each

We can see that it took 165 seconds to run on my computer.  Almost all of that time was spent calling Hash.has_value?.  Hash.has_value? was called 27722 times, which is 360360/13, the number of iterations in the loop (plus one or two more).  There is also another function, Fixnum#== that was called many times.  This is called from inside Hash.has_value? to compare each value in the hash to the value being searched for.  It is also called as part of the modulus check and probably a few other places as well.  The number is very close ot the number we predicted with the formula.
In summary, almost all of the processing time is taken by Hash.has_value? and its inner call to Fixnum#==.
Fixing The Code
Your bottleneck is in Hash.has_value? so we should get rid of it.  All you are doing is checking if the test number is divisible by every number less than or equal to m.  You store this in  a hash, but never reference anything other than the current iteration.  As such, you can get rid of the hash and use a simple counter instead.
multiple = 13
y = multiple

loop do
  counter = 0
  for x in 1..multiple do
    if y % x == 0
      counter += 1
    end
  end

  if counter == multiple || y == 0
    break
  end

  y += multiple
end

puts "Smallest number = #{y - multiple}"

When we profile this code we get the following:
Total: 0.137014

 %self      total      self      wait     child     calls  name
 75.91      0.104     0.104     0.000     0.000    27720   Range#each

We now run over 1000 times faster, yay!
Cleaning up the Code
One of the reasons this question took so long to answer is that your original code is very hard to read.  I'm going to keep your logic intact but clean it up some, just to make it look a little more rubyish.
def find_smallest_dividend(max_divisor)
  return 0 if max_divisor <= 0

  current_value = max_divisor
  loop do
    break if (1..max_divisor).all? { |n| (current_value % n).zero? }
    current_value += max_divisor
  end

  current_value
end

puts "Smallest number = #{find_smallest_dividend(13)}"


Implementing basic graph theory functions in APL with matrices

I believe the DoubleDegrees and ConnectedComponents functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?

Many APL implementations, especially Dyalog's, are heavily optimized around array operations using hardware SIMD instructions and parallel processing. Matrix multiplication is one of them.

Classical algorithms say that matrix multiplication is heavy, and a search algorithm will definitely do better. However, the uniqueness of APL gives very low constant factor to matrix multiplication (possibly even cutting down a dimension with enough parallelism), while it likely gives a high cost to a recursive search (interpreting a function over and over, and digging through a nested array).

In conclusion, I'd say matrix multiplication is the preferred way to solve such a task in APL. If in doubt, you can always implement both and compare the timings.

  I'm particularly interested in feedback on the AdjacencyMatrix and on the ConnectedComponents functions.

AdjacencyMatrix

AdjacencyMatrix ← {
    ⍝ Compute the adjacency matrix of a graph.
    ⍝ Monadic function expecting an 'EdgeList'.

    vertices ← ⊃1↑⍵          ⍝ can be simplified to `vertices ← ⊃⍵`
    edges ← (↓⌽⍪⊢) 1↓⍵       ⍝ consider putting atop `↓` outside of the train
                             ⍝ to clarify the intent:
                             ⍝ edges ← ↓ (⌽⍪⊢) 1↓⍵
    mat ← 0⍴⍨ 2⍴ vertices
    (1@edges) mat            ⍝ `1@edges⊢ mat` is more common way to split
                             ⍝ right operand from right arg
}

ConnectedComponents

ConnectedComponents ← {
    ⍝ Computes the number of connected components of a graph.
    ⍝ Monadic function expecting 'EdgeList' as argument.

    adj ← AdjacencyMatrix ⍵
    v ← ⊃⍴ adj                 ⍝ can be simplified to `v ← ≢adj`
    (1 1⍉adj) ← v⍴1            ⍝ can be simplified to `(1 1⍉adj) ← 1`
    accum ← (+.×)⍣(v-1)⍨ adj   ⍝ more on two last lines below
    ≢∪ (1@(≠∘0)) accum
}

Plain \$n\$th matrix power of an adjacency matrix \$M\$ gives the count of all length-\$n\$ paths between given two vertices. Adding the 1 to the diagonal of \$M\$ has the effect of adding loops to the graph, and its power gives the count of all length-\$≤n\$ paths. To describe the inner workings: For each pair of vertices \$(p, r)\$, +.× counts the paths \$p \rightarrow q \rightarrow r\$ for every intermediate vertex \$q\$ by multiplying × paths for \$p \rightarrow q\$ and \$q \rightarrow r\$, and collects all of them by sum +.

But right now we don't need the counts, we just need to know whether such a path exists. This gives rise to the Boolean matrix product ∨.∧. Analogously to +.×, ∨.∧ checks if any path \$p \rightarrow q \rightarrow r\$ exists by ∧-ing \$p \rightarrow q\$ and \$q \rightarrow r\$, and collects them by ∨ to indicate if some path exists. This has several benefits:

Boolean arrays and operations on them are more time- and space-efficient over integer arrays.
Finding all connected pairs is easier with the fixed point ⍣≡, while it can't be done with +.×.
You don't need an extra step (1@(≠∘0), though it can be simplified to 0≠or simply ×) to extract the exists from the counts.

Finally, if we change ∨.∧⍣≡⍨ to ∨.∧⍨⍣≡, we double the number of steps instead of advancing only one step every iteration (thus reducing the number of matmul operation from \$O(n)\$ to \$O(\log{n})\$). If we were calculating precisely the \$n\$th power, we would need repeated squaring that refers to \$n\$'s bit pattern. We don't need to care about it because we'll be iterating until it converges anyway.

Now the code looks like: (the variable v is removed since it is no longer used)

ConnectedComponents ← {
    adj ← AdjacencyMatrix ⍵
    (1 1⍉adj) ← 1
    accum ← ∨.∧⍨⍣≡ adj    ⍝ (f.g)⍣≡⍨ is same as f.g⍣≡⍨ due to parsing rule
    ≢∪ accum
}


Standard classes and derivation

If a class does not have a virtual destructor it is not supposed to be derived from. Before we got the finally key word this was the indicator you were supposed to use before deriving from a class.

But its safe unless you start taking pointers to your class. So to make sure it is not used incorrectly you should put it in a private context (so nobody else can use it apart from your library).

Inheriting functions.

You don't need to copy functions if they have the same name (that's the point of inheriting).

size_t size() const { return std::vector<T>::size(); }
void resize(size_t _size) { std::vector<T>::resize(_size); }

Don't need these. You automatically inherit them.

Inheriting Constructors.

You can use the using clause to inherit all the constructors.

vector() : std::vector<T>() {}
vector(const std::initializer_list<T> il) : std::vector<T>(il) {}
~vector() {}

Can be replaced with:

using std::vector::vector;

Identifiers with leading underscore.

Don't use them.

void resize(size_t _size)
                   ^^^^^

DO you know the rules about a leading underscore. I do (you got it correct). But can you assume that all the people reading your code know (you can't and most get it wrong). So prefer not to use a leading underscore on your identifiers.

Operator[] is supposed to be fast

The operator[] is an unchecked access into the data. You use this when you know that your index is guaranteed correct. We also have a checked access at() which is used when you can't guarantee that your index is in range.

T& operator [] (size_t index) {
    if (index + 1 - Base > size())
        resize(index + 1 - Base);
    return std::vector<T>::operator[](index - Base);
}
const T operator [] (size_t index) const {
    if (index + 1 - Base <= size())
        return std::vector<T>::operator[](index - Base);
    else
        return T();
}

Your operator[] is severely restricting the performance of your code for people that know that their access is good.

for(int loop=0;loop < v.size(); ++loop)
{
    doStuff(v[loop]);  // Why do I need to check loop is in bounds
                       // each time? It is guaranteed to be in bounds
                       // by the context.
}

When people use operator[] they have already checked (or by context guranteed) that the index is in bounds. You should not be checking. You should provide an alternative function that checks and resizes.

find does not return an iterator

It seems strange that find does not return an iterator.

signed find(const T& value) {
    auto i = std::find(cbegin(), cend(), value);
    if (i != cend())
        return i - cbegin() + Base;
    else
        return -1;
}

What's all this pointer maths.

        return i - cbegin() + Base;

Use the standard functions.

    return std::distance(cbegin(), i) + Base;

Constructing a string is easy

Your toString() function is bad as all that work can be done using the std::string constructors (also the standard library uses to_string() you should follow the same convention).

std::string to_string() const
{
    return std::string(cbegin(), cend());
}

Note: this does nothing.

    ss << std::endl;

You should probably never use std::endl. It is actually very rare that you want to flush a stream (they flush themselves at the best times anyway being a human you will just make the code in-efficient by trying to overcompensate).

Namespace

You should definitely put your code into its own namespace. The name vector is just too common.

Sure nonstd seems like a fine name.

Personally I use an initial uppercase letter for all user defined types and namespaces. This allows me to quickly spot an object from type.

namespace ThorsAnvil
{
    class BlaBla
    {
        public:
            BlaBla(int x);
    };
    int bla(int y);
}

int main()
{
    namespace TA = ThorsAnvil;
    int data1 = 15 + TA::BlaBla(15); // I constructed an object here.
    int data2 = 16 + TA::bla(15);    // I called a function here.
}

So I would call your stuff.

namespace NonStd
{
    template<typename T>
    class Vector { /* STUFF */};
};

template<typename T>
#if SomeNormalSituation
using Vec = NonStd::Vector<T>;
#else
using Vec = std::vector<T>;
#endif;

int main()
{
    Vec<char>   data;
}

Idea

Overall find.

  A vector class that allows extension via operator [] which also has a generic Base parameter allowing the vector to be based at 1 rather than zero for example.

Your crazy this is going to cause you so many issues. CS people are so used to their arrays being zero based that any other number is just going to cause errors.

Thoughts

  Basically I am working on a 'modern' C++ Lexical Analyser and Parser Generator duo to replace flex and GNU Bison

Hmm. I love flex/bison. Use them all the time. It will be hard to replace something that is already near perfection. There is a reason why nobody has tried to improve them in years (and all attempts to replace them have failed).


Some general guidelines regarding #includes:

only #include in the header when necessary (this reduces potentially unwanted dependencies)
whenever possible, forward declare in the header instead of using #include
whenever possible, #include in the implementation only (this does not affect dependency)
never #include a source file (having to do so indicates a hierarchy issue)
be sure to never allow files to #include each other (sort of in a "circular" manner)

You have a typo in your header guard:

#ifndef PARITY_H_
#define PATITY_H_ // should be PARITY_H_

The class isn't doing anything with <iostream> and <string>, so just remove them.
test() doesn't need the void parameter; that's only for C.
This:

if (numbers.size() % 2 == 0)
    return true;
else return false;

can be shortened to this:

return (numbers.size() % 2 == 0); // the statement's Boolean value is returned

You can use std::boolalpha to display a bool as "true" for 1 or "false" for 0:

std::cout << std::boolalpha << odd_number;

The while and if-else don't seem too intuitive.  The loop just runs until you break from it, and it's not directly tied to number.  One alternative is to do an initial input before the loop:

// initial input before loop-- number may be 0
std::cout << "Enter an integer: ";
int number; // move the declaration here
std::cin >> number;

// if not 0, proceed until it's 0
while (number != 0)
{
    parity_test.put(number);
    bool odd_number = parity_test.test(); // initialize here instead
    std::cout << "odd number? " << std::boolalpha << odd_number;

    // input again
    std::cout << "Enter an integer: ";
    std::cin >> number;
}


I haven't found any input which isn't handled well by your code. Here are some tests:

assertTrue(CanAdd(0, Integer.MAX_VALUE));
assertTrue(CanAdd(0, Integer.MIN_VALUE));
assertTrue(CanAdd(Integer.MIN_VALUE, 0));
assertTrue(CanAdd(-1, Integer.MAX_VALUE));
assertFalse(CanAdd(1, Integer.MAX_VALUE));
assertFalse(CanAdd(-1, Integer.MIN_VALUE));

So, it works but it isn't an easy task to read it. If this isn't a bottleneck in an application I would use a long:

public static boolean canAdd(int... values) {
    long sum = 0;
    for (final int value: values) {
        sum += value;
        if (sum > Integer.MAX_VALUE) {
            return false;
        }
        if (sum < Integer.MIN_VALUE) {
            return false;
        }
    }
    return true;
}

I think it's easier to read and maintain.

Finally, a note: according to Code Conventions for the Java Programming Language the name of your method should be canAdd (with lowercase first letter).

  Methods should be verbs, in mixed case with the first letter
  lowercase, with the first letter of each internal word capitalized.

Edit:

Apache Commons Math also uses long conversion:

public static int addAndCheck(int x, int y)
        throws MathArithmeticException {
    long s = (long)x + (long)y;
    if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
        throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y);
    }
    return (int)s;
}

As well as Guava:

public static int checkedAdd(int a, int b) {
    long result = (long) a + b;
    checkNoOverflow(result == (int) result);
    return (int) result;
}


A CRUD blog with a basic auth system made with the MERN stack

You can turn the action types to constants.
Have action creators

https://redux.js.org/recipes/reducing-boilerplate/

In deletePosts you're passing a cb that's never used
For readability I would always wrap args in ( ) in arrow function (params)
A trivial comment/preference... I would make sure I use data in args so I don't have to assign it to prop axios.put('/edit', { data: changes }) I would just doaxios.put('/edit', { data })`


R: Optimize algorithm speed that estimates hourly temperature and relative humidity

The first thing to improve about your code/procedure is readability.
Not "just" for others trying to understand your code, but for your latter self should you want to maintain it.
I don't know the first thing about R. The first style guide a superficial web search turned up is from Hadley Wickham's Advanced R, characterised as short and sweet.

Things I think to harm readability:

(lack of) structuring source code by formatting
(lack of) documentation in the source code: What is "everything" about?
What is the problem to solve, the sequence of well-defined steps perceived to solve it?
abbreviated names without an illuminating comment: is "hr" for hour or  humidity, relative or something entirely else?
hx seems to be four hours before sunset - what does the x signify, and why 4 hours?
in-line arithmetic with magical constants: while I can guess that lat*(3.141592653589793/180.0) is radian(latitude in degrees), I'd rather not.
What is the significance of 10 in dayIndex + 10,
0.39 in tMax - 0.39*(tMax - tMinNext), why isn't the latter just 0.39*tMinNext + 0.61*tMax?
computing things that don't get used
The only things I see used (pasted to hrResult - see below) are hr and tSum;
some code struggles with HumHr/HumTm and "their Accum counterparts".

Once the code is readable, one can start pondering performance impact:
Is there anything straining the memory hierarchy?
Do costly actions get repeated instead of results reused?
Then, there is general advice like Use Vectorisation,
and (resource demand) pitfalls - using paste() to accumulate the result may be one.


Disposable

You class manages a Timer, which you dispose of if Terminate is called.  It feels like your class should implement IDisposable and cleanup the timer if it hasn't already been done.

Is Started

Does this need to be exposed as a public property?  You're setting it in both your Start and Stop methods, but you never check its existing state.  Is calling Start twice in a row without calling Stop acceptable?  Perhaps Start should return IsStarted, rather than a value to indicate if it was able to acquire the lock.

Uncertain Usage

As I said in my response to your previous code it is unclear what your use case for this code is.  You are protecting the list, by creating a copy of it in GetLastUpdates, however if this is called by multiple threads each thread could end up with its own copy of the underlying list with the same items in it.  Each thread could then decide to perform some processing on the same item in the list.  Does this matter?  Is it prevented in someway outside of the code you've shown?  Some alternative options would be:

Calling threads simply pop the first item from the list, then perform processing on it.  If the underlying _updateList was a ConcurrentQueue and it was the the only way to fetch items, you could change GetUpdates to enqueue items and probably do away with the Monitor lock altogether.  Using your existing data structure you would have something like this.

public Update GetFirstItem()
{
    Update update = null;

    if (Monitor.TryEnter(_lock))
    {
        try
        {
            update = _updatesList.FirstOrDefault();
            if (null != update)
            {
                _updatesList.Remove(update);
            }
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }
    return update;
}

Calling threads pass in a selection delegate to select the item from the list they need to remove, then perform processing on it.

public Update GetFirstMatchingUpdate(Func<Update, bool> searchCriteria)
{
    Update update = null;

    if (Monitor.TryEnter(_lock))
    {
        try
        {
            update = _updatesList.Where(searchCriteria).FirstOrDefault();
            if(null != update)
            {
                _updatesList.Remove(update);
            }
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }
    return update;
}

Called like this:

var update = au.GetFirstMatchingUpdate(x => x.SomeField == "someText" && x.Id > 3);

Calling threads call existing GetLastUpdates, find the update they want to process, remove it from the list, then perform processing only if that removal works (i.e. they were the first to remove it).
Processing is only actually performed by a single thread (with the contention being between the update and the processor), in which case the problem I've described doesn't exist.


I would probably tackle it like this:

The database would have a few columns:

id
label
data (of some type, say, varchar for now)

The Wrapper class would be used to store/retrieve data from the database:

Responsible for conversion (serialization) from whatever type is necessary to the backend data store

The Wrapper class could have some sanity checks so that you couldn't ask for a int if it really was a string, etc etc.

This probably doesn't satisfy your "keeping things as small as possible" requirement, but disk is cheep.

You could create an object and basically serialize that and store the serialized version in the database.  You could then deserialize that when you needed to.


Here are some of your functions translated to be more pythonic:

Context managers mean never having to say your closed():

We can recast thse 2 functions (including fixing the bug of not closing the files):

def read(name):
    inFile = open(name, 'r')
    content = inFile.read()
    content = list(content.strip())
    return content

def write(name, nList):
    outFile = open(name, 'w')
    cList = convertToChar(nList)
    outFile.write(''.join(cList))

to:

def read(name):
    with open(name, 'r') as f:
        return f.read().strip()

def write(name, n_list):
    with open(name, 'w') as f:
        f.write(''.join(convertToChar(n_list)))

big key here is using context managers to automatically close the file, and not bothering to assign intermediate results to a variable.

List comprehensions can save a lot of looping boilerplate:

We will trim down:

def gen(keylen):
    i = 0
    key = []
    while i < keylen:
        k = random.SystemRandom()
        k = k.choice(string.printable)
        key.append(k)
        i += 1
    key = convertToNum(key)
    write("key.txt", key)
    return key

def convertToNum(charList):
    numList = []
    i = 0
    for i in charList:
        numList.append(ord(i))
    return numList

def convertToChar(numList):
    charList = []
    i = 0
    for i in numList:
        charList.append(chr(i))
    return charList

To:

def gen(keylen):
    key = convertToNum([random.SystemRandom().choice(string.printable)
                        for k in range(keylen)])
    write("key.txt", key)
    return key

def convertToNum(charList):
    return [ord(i) for i in charList]

def convertToChar(numList):
    return [chr(i) for i in numList]

All three of these functions now make use of list comprehensions to remove 75% of the lines of code.

NOTE

I did not test these changes they were just typed out in the editor.


Is there a better way to code this text adventure game?

A couple things. First of all, you should abstract the function that exits the game:

def exitGame():
    print 'That\'s a shame...'
    print 'Exiting program in 5 seconds:'
    for i in range(5):
        time.sleep(1)
        print(i+1)
    sys.exit('Exiting Game...')

Second, I would probably push Cabins, retries, etc. into arrays.

DECISIONS = []
CABINS = []
CONTINUES = []

Third, I would define the first level as a function so you can do the gracefully exit:

EXIT_MESSAGE = 'Exiting Game...'
#First level loop
while True:
    try: firstLevel()
    except SystemExit as e:
        print(str(e))
        break

One last thing. Use print as a function and not a statement. And maybe it's personal preference, but I find string formatting strongly preferable:

print('Nice to meet you, %s. Are you ready for your adventure?' % name)