Nested Deck class design and implementation

The way I understand your question, you want Card to be publicly available, yet only Deck should be able to construct a Card. One way to achieve this is to make the Card()  constructor private and a friend of Deck:

class Deck;

class Card {
    Card() {}
    friend class Deck;
public:
    // ...
};

class Deck {
    Card card;                     // ok
public:
    Card createCard() {            // ok
        return Card();
    }
};

int main()
{
    Deck deck;
    Card card = deck.createCard();

    Card doesntWork;               // error! Attempt to access private member
}

A somewhat cleaner solution would be to have only createCard() as friend of Card. In that case, however, you will have to dynamically allocate the Card (and return a pointer to it), because of mutual dependencies.

(The reason for this is that Card needs the definition, and not just declaration, of Deck to declare one of the Deck functions a friend. At the same time, Deck::createCard() needs the definition of Card to be able to return a Card by value. If you return a pointer, however, you only need the declaration.)

Other comments:

1: Consider giving ranks, suits and values distinct and unique types. For example using enum. Make use of the type system to enlist the compiler's aid -- by doing this you will be notified if you accidentally switch types somewhere.

2: I would change

for (unsigned iter = aDeck.size(); iter--> 0;)

to the more traditional

for (int i = aDeck.size() - 1; i > -1; --i)

The latter is more readable and clear about what is going on. The former is vulnerable to be incorrected, i.e. refactored to the (incorrect)

for (unsigned iter = aDeck.size(); iter > 0; --iter)

3: Don't call a variable iter when it's a counter and not an iterator.

4: Initializer list ordering should be the same as the variables are declared in the class. By doing this, you avoid ever risking dependency problems. (Variables are always initialized in the order they are declared in the class, not the order they appear in initializer lists.)

5: Reorder your #includes in the implementation file.

Update

6: Your card generation/constructor is error-prone. Apart from introducing type safety, I would recommend generating value based on rank, for example through a function and an std::map.


LinQ wrapper to get distinct items from a IEnumerable based on a function of item

That is a good definition for an IQueryable but I believe it is better to implement the operation directly for an IEnumerable (note: I don't use VB, so translated from C#):

<Extension()> Public Iterator Function DistinctBy(Of T, TKey)(src As IEnumerable(Of T), keyFun As Func(Of T, TKey)) As IEnumerable(Of T)
    Dim seenKeys As New HashSet(Of TKey)()
    For Each e As T In src
        If seenKeys.Add(keyFun(e)) Then
            Yield e
        End If
    Next
End Function


Replace part of the string with n size with string of m size

There's no definition in scope for size_t.  Since the description implies that you want std::size_t, you'll need

#include <cstddef>
using std::size_t

But I recommend just writing std::size_t in full where you use it - that's much clearer to readers.

size_t get_str_size(const char* temp){
            size_t s=0;
            while( temp[s] != '\0' )s++;
            return s;
        }

You've just re-implemented std::strlen() for no good reason.

    char* tempcopy = new char[original_size]; // holds the copy of the temp

    char *new_version = new char[ original_size + (new_size-old_size) ];

    delete tempcopy;
    delete new_version;

Memory allocated with new[] must be released using delete[] (not delete).  Valgrind will catch this error for you.

We have a memory leak if the first allocation succeeds and the second fails, because there is no delete[] tempcopy if an std::bad_alloc is thrown.

We reference deleted memory here:

    temp = (const char*)new_version;

    delete new_version;

    std::cout << &temp << "\t" << temp << std::endl;

That's Undefined Behaviour (and also caught by Valgrind - I really recommend you run your code under Memcheck, or any similar tool of your choice).

int main(int argc, char **argv){

Since we never use the arguments, there's no need to give them names; moreover, there's a signature of main() we can use with no arguments:

int main()

     for( int i =0 ; i <= original_size; i++ ){

Avoid comparing signed values (such as i) against unsigned ones (such as original_size).  We probably want the range of i to match, too, so just use the same type for both.

The code isn't very robust against a range of inputs.  In particular, if edelim is less than ldelim, we'll get (unsigned) integer overflow when we compute old_size, giving incorrect results.

Overall, the code looks very much like C code - and poor C code at that (e.g. copying 1 char at a time, rather than with memcpy()).  A C++ implementation (using std::string) is much shorter and more natural.


Method for validating properties based on passed conditions

The class encapsulating the two properties suggested by @eurotrash is definitely a good idea. I think name ValidationRule should be ok.

class ValidationRule
{
    public ValidationRule(Func<bool> predicate, string message)
    {
        Predicate = predicate;
        Message = message;
    }
    public Func<bool> Predicate { get; }
    public string Message { get; }
}

I'd go further and create a collection so that I can use the collection initializer to specify the rules. This means collection class must implement the IEnumerable<T> interface and some Add(..) method. Then we can use the syntax:

new SomeCollection
{
   Item1, Item2
}

or if the Add(..) requires more then one parameter:

new SomeCollection
{
   { Item1, Item1a },
   { Item2, Item2a },
}

so our new collection is

class ValidationRuleCollection : IEnumerable<ValidationRule>
{
    private readonly List<ValidationRule> _rules = new List<ValidationRule>();

    public ValidationRuleCollection Add(Func<bool> predicate, string message)
    {
        _rules.Add(new ValidationRule(predicate, message));
        return this;
    }

    public IEnumerator<ValidationRule> GetEnumerator() => _rules.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

Then you could use it like this

var result = Validate(nameof(FilePath), new ValidationRuleCollection
{
    { () => string.IsNullOrEmpty(FilePath), "Select a file to load" },
});

You don't need the Expression for it. You're not using it here. It adds overhead but does not have any advantage in this case.

The foreach loop can be replaced with LINQ. You stop at the first true result so use the FirstOrDefault to find it.

var rule = validationRules.FirstOrDefault(x => x.Predicate());
if (rule != null)
{
    ValidationProperties[propertyName] = false;
    ValidationChangedEvent?.Invoke(this, false);
    return rule.Message;
}


Typo

Error cused -> Error caused

Memory security

del password    # maybe it can help to make more secure?

It's not harmful, but it probably also won't help much. Your theory seems to be that if an outside attacker gains access to your program's memory (which is already instant doom), that calling del will have removed the plaintext password from memory thus reducing the impact of an attack. Have a read through an explanatory article like Python Garbage Collector, which says that

  you can use the del statement that removes a variable and its reference (not the object itself) [...] The del statement removes the references to our objects (i.e., decreases reference count by 1). After Python executes the del statement, our objects are no longer accessible from Python code. However, such objects are still sitting in the memory

del does not force garbage collection. To do that, you would in theory need to call gc.collect().

The most that del would immediately do is mitigate an attack on access to the locals dictionary. Again, if such an attack is possible, you have much bigger problems on your hands.

Boolean expressions

if key == asserted_key:
    return True
else:
    return False

can be

return key == asserted_key


C++ Calculator for complex numbers - follow-up

Use field initialization lists:

So your constructor

ComplexNumber(double real = 0.0, double imaginary = 0.0) {
    this->real = real;
    this->imaginary = imaginary;
}

Can become:

ComplexNumber(double real = 0.0, double imaginary = 0.0)
    : real(real), imaginary(imaginary) { }

Simplify your returns

I could see an argument for making an extra ComplexNumber to hold your return value if you need to further modify it or if the name of that variable is explanatory in showing what the return means, but as it stands, your c is neither of those.

Simplify

ComplexNumber c = ComplexNumber(real, imaginary);
return c;

To just

return ComplexNumber(real, imaginary);

Make your operator functions const

Since you (correctly) don't modify a when you do a + b, the operator function can (and should) be declared const. That way, even if you have a const object, you'll still be able to call it (and if you accidentally try to modify the member variable, you'll know immediately in the form of a compilation error).

That'd look like:

ComplexNumber operator+(const ComplexNumber &b) const {

Notice I've also declared b as const here since you shouldn't be modifying it either. I've also passed it by reference to save you some overhead.

Make your class printable with std::cout

Your printNumber is very specific. In fact, if you ever want to use this class for anything other than simply showing arithmetic results, that print may not be what you want. Instead, I'd make a generic str() that just returns a string version of the complex number. Something like:

std::string str() {
    std::ostringstream oss;
    oss << this->real << " + (" << this->imaginary << ") * i";
    return oss.str();
}

And then in the global scope, you can overload the << operator for std::cout:

std::ostream& operator<<(std::ostream &os, const ComplexNumber &cn) {
    return os << cn.str();
}

And now when you want to print it in main(), you can say:

std::cout << "a + b = " << a + b << std::endl;
std::cout << "a - b = " << a - b << std::endl;
std::cout << "a * b = " << a * b << std::endl;
std::cout << "a / b = " << a / b << std::endl;

Look at how easy that becomes to read and understand!


Find binary sequence in NumPy binary array

Before I get to your specific question, here are some general comments:

Since you are working with binary data, you should tell NumPy that your dtype is bool everywhere that you can.  That will lower memory requirements and speed up certain operations.  For example, data = np.zeros(1000) in getFixedTestData() should become data = np.zeros(1000, dtype=bool).  The default NumPy dtype is float which is not what you want.
The python convention for naming functions is snake_case i.e. all lowercase with underscores, not camelCase.  So findPulseSlow should be find_pulse_slow etc.
The right approach for optimizing your currently too-slow function is to use line profiling.  I really like the line_profiler module.  If you use IPython you can use it very easily as an inline magic function.
Doing #3 will mean unpacking that formidable iterator comprehension you wrote!  Instead of squeezing it all on one line, I'd define a generator function for the iterator, and try to be extremely explicit so that every line has only one function call, like this:

def yield_convolve(arr_1, arr_2):
    """Yields indices of arr_1 where arr_2 nearly matches."""
    MAX_ERR = 3
    len_1, len_2 = len(arr_1), len(arr_2)  # I assume arr_2 is always shorter than arr_1
    min_matches = len_2 - MAX_ERR
    num_windows = len_1 - len_2
    for idx in xrange(num_windows):
        arr_1_window = arr_1[idx:(idx+len_2)]
        summand = np.equal(arr_1_window, arr_2)
        sum_ = np.count_nonzero(summand)
        condition = sum_ >= min_matches
        if condition:
            yield idx

def find_pulse_slow_revised(arr_1, arr_2):
    return np.fromiter(yield_convolve(arr_1, arr_2), dtype=int)

I was probably overly expressive in the function I made -- it could be cleaned up by avoiding assigment to so many temporary variables but when doing line profiling this style really helps isolate the slow steps.

Watch out for places where you are inadvertently causing interconversion of NumPy data types and native Python data types.  For example, sum(np.logical_xor(...) should be np.sum(np.logical_xor(...)
I thought the np.logical_xor part you did was clever, but to my eyes at least it was a bit easier to grok using len(pulse) - maxerr as a criterion and using np.equal instead of np.logical_xor, so that is what I did in my example above.
I did a few timing tests with my revised function and it was at least ~20-30x faster than your findPulseSlow().  Using np.sum instead of sum was responsible for most of the speedup.  Using np.count_nonzero instead of np.sum gave an additional 2× or so.  Here's an example of some code from my IPython notebook, along with some output from the line profiler.

_, fixed_dat = getFixedTestData()

%timeit findPulseSlow(fixed_dat, NOAAsyncA)

%timeit find_pulse_slow_revised(fixed_dat, NOAAsyncA)

%lprun -f find_pulse_slow_revised -f yield_convolve find_pulse_slow_revised(fixed_dat, NOAAsyncA)

10 loops, best of 3: 54 ms per loop
1000 loops, best of 3: 1.43 ms per loop

Timer unit: 1e-06 s

Total time: 0.004039 s
File: <ipython-input-95-5e22e2fbabc9>
Function: yield_convolve at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def yield_convolve(arr_1, arr_2):
     2                                               """Yields indices of arr_1 where arr_2 nearly matches."""
     3         1            1      1.0      0.0      MAX_ERR = 3
     4         1            1      1.0      0.0      len_1, len_2 = len(arr_1), len(arr_2)  # I assume arr_2 is always shorter than arr_1
     5         1            0      0.0      0.0      min_matches = len_2 - MAX_ERR
     6         1            0      0.0      0.0      num_windows = len_1 - len_2
     7       961          407      0.4     10.1      for idx in xrange(num_windows):
     8       960          579      0.6     14.3          arr_1_window = arr_1[idx:(idx+len_2)]
     9       960         1511      1.6     37.4          summand = np.equal(arr_1_window, arr_2)
    10       960          642      0.7     15.9          sum_ = np.count_nonzero(summand)
    11       960          476      0.5     11.8          condition = sum_ >= min_matches
    12       960          422      0.4     10.4          if condition:
    13         3            0      0.0      0.0              yield idx

Total time: 0.006642 s
File: <ipython-input-95-5e22e2fbabc9>
Function: find_pulse_slow_revised at line 15

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    15                                           def find_pulse_slow_revised(arr_1, arr_2):
    16         1         6642   6642.0    100.0      return np.fromiter(yield_convolve(arr_1, arr_2), dtype=int)

Using the built-in np.convolve solution is definitely the way to go and is still way faster than even the improved "slow" method.


Unless you're using C89, I would define variables where they are used (I'm looking at curl).

0 is currently interpreted as CURLE_OK. This means that if cURL fails to initialize, you're returning a success code. That's probably not what you meant to do.

This is a great example of why you should never use plain constants to set the value of an enum. You throw away the entire purpose of the enum when you do that, and lost meaning gives you cases like this.

I would try to hide the cURL dependency. What if you later decide to change to using sockets again? The simplest way to do this would be a simple enum with 3 possibilities: CONNECTION_SUCCESS, CONNECTION_FAILURE, CONNECTION_EXCEPTION. The first two are obvious. The third would be if something other than simple pass/fail happened (cURL can't initialized for example).

This does unfortunately mean you need to do a bit more boiler plate for your error handling, but it means that you can change out the underlying implementation as you please.

Your comment is very vague with regards to return value ("Success value if connected to the internet."). What in the world is a 'success value'? Also, it might be nice to clarify what connecting to the internet means (in this context, it means DNS resolution, connecting and making an HTTP request -- that's a lot more than simple connection).

(Had to pick on you about documentation, of course :p).

I have a lot of reservations about this in general. What if google is down (yeah, yeah, but it can happen!). What if 5 years from now google doesn't exist? What if the user's DNS server enforces Bing (crazy, but you never know). It just seems a really fragile dependency. Unfortunately though, I have no better solution off the top of my head other than check more than 1 site and allow the user to override defaults.


Merge Sort Implementation in Java (that seems slow...)

General suggestion not related to the sorting implementation: You should be timing the time it takes to call and return from your mergeSort() method, not the time it takes to call System.out.println() and your toString() methods as well. Furthermore, a better microbenchmark calls for running a few iterations and then taking averages to smooth out outlying cases due to "warm-up".

Also, I will suggest using a StringBuilder instead of StringBuffer since your presumably do not require synchronization here, and append values one by one instead of concatenating them together:

stringBuilder.append(array[i]).append(", ");

Even if you feel like timing how long it takes for your toString() method, doing both of them is likely to shave a bit of time off too if used with enough repetition.


First of all there are two mistakes in the code:

ending = "ay" is a local variable only visible directly in the class body, not inside of the defs. For this reason translate_with_vowel will throw a NameError when it is called. You should make it a constant, so it'll be visible everywhere.
The reason that you did not notice the first mistake is that translate_with_vowel is never called because vowel_is_first will always return false. You should use if ... else ... end instead of the inline if. The reason that it doesn't work the way you wrote it is that since true if test_word[0] =~ /aeiou/ is not the last expression in the method, so its return value simply gets discarded and it doesn't have any side-effects.

From a design perspective, I'm a bit doubtful that having a PigLatin object for each string you want to translate is really a good idea. Each PigLatin object has one instance variable, which is set in initialize and used by exactly one method (translate). All other methods only depend on their arguments and not on the state of the object. So from a programmer's point of view, having the string encapsulated in an object buys you nothing over taking it as an argument to translate.

From the user's point of view it also makes the API more cumbersome than it needs to be. There's no reason to prefer PigLatin.new(string).translate over PigLatin.translate(string) if there's no reason why I'd ever call more than one method on an object, there really is no reason for the object to exist at all.

If the translation was parametrized by some configuration options, it would make sense to have a class which is instantiated with the options and a translate method which takes the string, like this:

pig_latin = Translator.new(:input => :english, :output => :pig_latin)
string1 = pig_latin.translate("Hello World")
string2 = pig_latin.translate("Goodbye World")

However since in this case there are no options, I'd recommend using a PigLatin module and defining all the methods as module_functions. This way the usage would be PigLatin.translate("Hello World") or include PigLatin; translate("Hello World").

Also since there's no reason why a user should ever call any of your methods except translate, the other methods should probably be private.

  def translate
    translated_phrase = String.new
    words = @phrase.split
    words.each do |word|
      puts word
      if vowel_is_first word
        translated_phrase +=  translate_with_vowel(word)
      else
        translated_phrase += translate_with_consonant(word)
      end
    end

    clean_up translated_phrase
  end

I assume the puts is just an old debug statement you forgot to remove. If it isn't, be advised that mixing IO with logic is usually bad design. If it is, a little tip: If you use p instead of puts for debug statements, you will get output which is more useful because you can see whether the object has the type you expect and, in case of strings, whether it contains any unprintable meta characters.

String.new is just a more verbose way to say "", so you should use that instead. However instead of appending to an empty string in an each loop, I'd rather use map and join. join will also take care of inserting spaces between the elements for you (if you tell it to, that is), so you don't need to add those spaces yourself in the translate_ methods and you don't have to remove the space at the end.

So I'd write translate like this:

 def translate(string)
    words = @phrase.split
    translated_words = words.map do |word|
      if vowel_is_first word
        translate_with_vowel(word)
      else
        translate_with_consonant(word)
      end
    end
    translated_phrase = translated_words.join(" ")
    translated_phrase.capitalize
  end

You can also define another helper method translate_word which contains the above if statement and then simplify the above to translated_words = words.map(&:translate_word).

  def translate_with_consonant word
    return word + "-way " if word.size <= 2
    split_location = word =~ /a|e|i|o|u/
    word_array_length = word.size - 1

    first_segment = word[split_location,word_array_length]
    second_segment = "-" + word[0,split_location-1] + word[split_location-1]  + "ay" + " "

    first_segment + second_segment
  end

The whole split_location is overly complicated. Just use String#split (which accepts an integer as a second argument, which you can use to tell it that you only want to split the string into two parts). You may also want to use string interpolation instead of concatenation. And as I said earlier, you can get rid of the + " " as that's now handled by join.

I'd write it like this:

  def translate_with_consonant word
    return word + "-way " if word.size <= 2
    second_segment, first_segement = word.split(/a|e|i|o|u/, 2)

    "#{ first_segment }-#{ second_segment }ay"
  end


Bash functions to run/manage MySQL, Redis, Sidekiq, Rails server

Pretty nicely written! In fact, if you want to DRY this up, I'm pretty sure you could do it yourself if you seriously tried... But here you go anyway ;-)

Non-standard features

The function keyword is non-standard:

function rpid {
    pgrep -f "$1" 2> /dev/null
}

Write it this way instead:

rpid() {
    pgrep -f "$1" 2> /dev/null
}

DRY-ing up

You could write running in terms of rpid:

running() {
    rpid "$1" > /dev/null
}

rpid() {
    pgrep -f "$1" 2> /dev/null
}

This way, the pgrep logic is only in one place. If you need to change something, you could do it in one place. Just remember that the caller (running) expects the correct exit code of success / failure, and no output on stderr.

The start / stop / status commands have the common elements of checking if the process is running or not. You could create helper functions to reduce the duplication:

start() {
    procname=$1; shift
    name=$1; shift
    if ! running "$procname"; then
        "$@"
    else
        echo "$name already running"
    fi
}

stop() {
    procname=$1; shift
    name=$1; shift
    if running "$procname"; then
        "$@"
    else
        echo "$name not running"
    fi
}

status() {
    procname=$1
    name=$2
    if running "$procname"; then
        echo "$name running"
    else
        echo "$name not running"
    fi
}

Then you can simplify the MySQL functions using these helpers:

msta() {
    start mysql MySQL mysql.server start
}

msto() {
    stop mysql MySQL mysql.server stop
}

mstat() {
    status mysql MySQL
}

Similarly for redis:

redis_start() {
    redis-server ~/.redis/redis.conf
    until running redis; do
      sleep 1
    done
}

redis_stop() {
    kill $(rpid redis)
    while running redis; do
      sleep 1
    done
}

resta() {
    start redis "Redis daemon" redis_start
}

resto() {
    stop redis "Redis daemon" redis_stop
}

restat() {
    status redis "Redis daemon"
}

And I left the rest for you as exercise:

rastat can be simplified using status
krs can be simplified similar to the way I did redis above
You can leave reportkill as it is, as it's a different pattern from the others

There remains still some duplication in the start, stop, status helpers, but trying to reduce that might hurt readability. I think the current form is the "sweet spot", trying to optimize further will have diminishing returns.

shellcheck.net

This site is really awesome for checking your shell scripts for common mistakes:

http://www.shellcheck.net/#


Load multiple text files with same name but in different folders

You are right to question your current approach.  With 9 sets of data with 5 repeats of each, you would need 45 variables with your current approach.  Using a list or dictionary for one dimension would reduce you to only 5 or 9 variables depending on which dimension became the list/dictionary.  Use a list/dictionary of lists/dictionaries could reduce the required variables to 1.

Using '/long/path/'+var1+'suffix/'+var2+'/filename.ext' is hard to read.  First, the PEP8 standard requires spaces around the + operators (as well as other places, such as after commas).  Using a .format() statement can make the string manipulation a bit clearer, and allow configuration to be move out of functions to a global scope, making changes easier.

Whether you want lists or dictionaries for the data, whether you want to store the individual msd[temperature][repeat] for later use or whether you just need to read the data in to compute the mean & standard deviation and can then discard the data, and so on is unclear.  Here (untested) is a rough reworking of your code to allow you to extend the temperatures and repeats as required; adapt as necessary.  The msd variable is a dictionary of lists, so the variable msd323_5 has become msd[323][4].

import numpy as np
import matplotlib.pyplot as plt

# Configuration

FILENAME = '/home/aperego/data/HexaPaper/nvt/{}K/{}/Average_MSD.txt'
REPEATS = ('1st', '2nd', '3rd', '4th', '5th')
TEMPERATURES = (303, 313, 323)

# Read data

def load(temp, pos):
    return np.loadtxt(FILENAME.format(temp, pos), usecols=[1])

steps = np.loadtxt(FILENAME.format(TEMPERATURES[0], REPEATS[0]), usecols=[0])

msd = {}
msd_mean = {}
msd_std = {}

for temperature in TEMPERATURES:

    repeats = []

    for repeat in REPEATS:

        sample = load(temperature, repeat)
        repeats.append(sample)

    data = np.vstack(repeats).T

    msd[temperature] = data
    msd_mean[temperature] = np.mean(data, axis=1)
    msd_std[temperature] = np.std(data, axis=1)

# Plot the data

plt.yscale("log")
plt.xscale("log")

for temperature in TEMPERATURES:
    plt.plot(steps, msd_mean[temperature], label="{}K".format(temperature))

plt.legend(loc="best")
plt.show()


Simple bash script creates apache2 virtualhost config for subdomain

Notes:

Quote your variables. Ref Security implications of forgetting to quote a variable in bash/POSIX shells
Don't use ALLCAPS varnames. It's too easy to overwrite important shell variables like PATH.
A2ENSITE=$A2A2ENSITE$HOST".conf" -- I don't see the A2A2ENSITE variable anywhere

this is a perhaps a corollary of the ALLCAPS vars problem: they can be hard to read.

For Command Substitution, don't use backticks, use $( ... ). That syntax is (IMO) easier to read, and there are other advantages, such as nestability.
if ((`which zenity|wc -w` == 0)) -- use the bash builtin type command to see if there is a zenity command available: type -p zenity will return an unsuccessful exit status if there's no zenity in your path:

if ! type -p zenity >/dev/null

Although I don't really see the need for zenity. It would be super frustrating for the user who doesn't have it, being prevented from using your script. And the technical user who would be comfortable installing it is the type of user who doesn't need the bells and whistles, IMO.
To check if a string is empty, you don't need to call out to wc.

Not this:

TEXT=`zenity --text-info --filename=$TMPHOST$HOST --editable`
words=$( wc -w <<<"$TEXT" )
if (($words == 0))

but this:

text=$(zenity --text-info --filename="$filename" --editable)
if [ -z "$text" ]       # cancel if empty

use mktemp for temp files

tmphost=$(mktemp)

And just use "$tmphost" instead of $TMPHOST$HOST
you can tell bash to automatically delete the temp file when it exits:

trap "rm $tmphost" EXIT

validate user input for host: a case statement might make sense here:

host=$(zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)')
case "$host" in
    "")            zenity --error --text="Bad input: empty";      exit 1 ;;
    *"*"*)         zenity --error --text="Bad input: wildcard";   exit 1 ;;
    *[[:space:]]*) zenity --error --text="Bad input: whitespace"; exit 1 ;;
esac

I applaud your use of here-documents
use if [ "$(id -un)" = "root" ] instead of the USER variable.
mkdir -p silently does nothing if the directory already exists, so you don't need to test -d

Perhaps you want this:

#!/bin/bash

webroot="/home/leonid/Web/" # root folder where subfolders for virtualhosts created
apachehost="/etc/apache2/sites-available/050-" # prefix for virtualhost config file
a2ensite="050-"             # short prefix for virtualhost config file
tmphost=$(mktemp)
trap "rm $tmphost" EXIT

if [ "$USER" == "root" ]
then
    echo "You should not run this script as root but as user going to edit web files." >&2
    exit 1
fi

read -p"Create virtualhost (= Folder name,case sensitive)" -r host
case "$host" in
    "")            echo "Bad input: empty" >&2;      exit 1 ;;
    *"*"*)         echo "Bad input: wildcard" >&2;   exit 1 ;;
    *[[:space:]]*) echo "Bad input: whitespace" >&2; exit 1 ;;
esac

# braces only for readability
hostfile="${apachehost}${host}.conf"    # apache virtualhost config file
dir="${webroot}${host}"                 # folder used as document root for virtualhost

# virtualhost template
cat >"$tmphost" <<EOF
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot $dir
    ServerName  $host.localhost
    ServerAlias $host.localhost
    <Directory "$dir">
        AllowOverride All
        Require local
    </Directory>
    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    LogLevel warn
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF

# edit virtualhost config
editor=${VISUAL:-$EDITOR}
if [ -z "$editor" ]
then
    echo "edit '$tmphost' to your liking, then hit Enter"
    read -p "I'll wait ... "
else
    "$editor" "$tmphost"
fi
# probably want some validating here that the user has not broken the config

echo "execute root tools with pkexec to create virtualhost"
mkdir -p "$dir"

pkexec /bin/bash <<EOF
chgrp www-data "$dir"
chmod u=rwX,g=rX,o= "$dir"
mv "$tmphost" "$hostfile"
chown root:root "$hostfile"
chmod u=rw,g=r,o=r "$hostfile"
a2ensite "${a2ensite}${host}.conf"
EOF

Responding to your questions:

"determine if running in a terminal?" Yes with this obscure test:

if [ -t 0 ]; then echo "in a terminal"; fi

That tests file descriptor 0, which is stdin. If you're launching your script as a GUI, that test should be false.
editor=${VISUAL:-$EDITOR} sets the editor variable to the user's $VISUAL variable, or if that's not set, to the $EDITOR variable. Many programs use this to determine the user's preferred "terminal" editor. vim and emacs are two common values there. If neither of those are set, then the user gets to go edit that however he chooses.
"is read terminal only?" Yes

If you're going to aim for GUI and text versions, I'd use one script, but make sure all the common code is put into functions so you don't have to duplicate your code. For example:

get_virtual_host() {
    if [ -t 0 ]; then
        read -p "Create virtualhost (= Folder name,case sensitive)" -r host
    else
        host=$(zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)')
    fi
    case "$host" in
        "")            echo "Bad input: empty" >&2;      exit 1 ;;
        *"*"*)         echo "Bad input: wildcard" >&2;   exit 1 ;;
        *[[:space:]]*) echo "Bad input: whitespace" >&2; exit 1 ;;
    esac
    echo "$host"
}

host=$(get_virtual_host)


Compare two lists to see if one is a rotation of the other

Naming

Your 2 arrays are used the same way, it is a bit weird to have 2 different names for them. Maybe int_arr1 and int_arr2 would be better names. Also the fact that they contain integers may be irrelevant for the naming: arr1 and arr2 would do the trick (or lst1 and lst2 because the corresponding Python primitive data structure is list).

Problem with the check for length equal to 0

Checking for identical lengths as the beginning of the function is a nice touch.

However, the or len(lst1) == 0 condition makes me uneasy. It only makes a different when the first part of the check was false and the second part is true which means: len(lst1) == len(lst2) == 0 which really means: lst1 == lst2 == [].

I'd expect the empty array to be a rotation of the empty array. The alternative would be to document the function to precise that only non-trivial rotations are considered (which is not the case at the moment). The easy fix is probably to remove this test or to return True in that case (or whenver lst1 == lst2).

Comments

Commenting your code is nice but adding obvious comments doesn't help anyone. There is a fine line between too many comments and not enough comments.

I'd get rid of #lengths of arrays are the same and not equal to zero? for instance.

On the other hand, #@cmp_arr, is the array being compared to see if it is a rotation could be kept somehow. This should be moved in the function docstring. Also, Python has a Docstring convention called PEP 257. You could write:

def is_rotated(lst1, lst2):
    """Test whether list lst1 is a rotation of list lst2."""

Same value computed multiple times

You compute set(lst1) multiple times which is not as efficient as it could be (which is sad for something meant to be an optimisation).

#does array contain same numbers?
s1 = set(lst1)
s2 = set(lst2)
if not s1 <= s2 and not s1 >= s2:
    return False

Optimisation does not work

I guess the point of the optimisation would be to detect situations like:

lst1, lst2 = [1,2,3,4,6,4,6], [6,4,7,1,2,3,4]
print(is_rotated(lst1, lst2))

lst1, lst2 = [1,2,3,4,6,4,7], [6,4,6,1,2,3,4]
print(is_rotated(lst1, lst2))

Unfortunately, this is not detected.

I guess instead of not s1 <= s2 and not s1 >= s2, you meant: not s1 <= s2 or not s1 >= s2 which is equivalent to not (s1 <= s2 and s1 >= s2) which is equivalent to the more straight-forward: s1 != s2.

In any case, as pointed out by Oscar Smith, this optimisation may not be worth doing.

Reusing existing functions

Looking for index can be done with the already existing function: index = lst2.index(lst1[0]).

Loop like a native

Your final loop is not really Pythonic. Most of the time in Python, you can avoid messing with indices. I hightly recommand Ned Batchelder's talk: "Loop like a native".

In your case, we can improve your code in multiple steps. (Some of the steps are pretty artificial in your case but I use them to show you the different functions you have in your Python toolbox).

Introducing enumerate to get rid of the code to track index:

#split list at index point, compare the lists
rot2 = lst2[index:] + lst2[:index]
for i, x in enumerate(lst1):
    if x != rot2[i]:
        return False
return True

Using zip to avoid accessing rot2 by index:

#split list at index point, compare the lists
rot2 = lst2[index:] + lst2[:index]
for x1, x2 in zip(lst1, rot2):
    if x1 != x2:
        return False
return True

Using all to make things more concise:

return all(x1 == x2 for x1, x2 in zip(lst1, rot2))

The final revelation: all this is not needed:

return lst1 == rot2

At this point, the code looks like:

def is_rotated(lst1, lst2):
    """Test whether list lst1 is a rotation of list lst2."""
    if len(lst1) != len(lst2):
        return False

    if lst1 == lst2:
        return True

    if set(lst1) != set(lst2):
        return False

    index = lst2.index(lst1[0])

    #split list at index point, compare the lists
    rot2 = lst2[index:] + lst2[:index]
    return lst1 == rot2

Broken code

As pointed out by Oscar Smith, your code does not work.

For that kind of programming task, it is very easy to write tests to help you catch issues. These can be written before, during and after writing the code. You could use a proper testing framework or just simple assertions like:

# rotation
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,7,1,2,3,4]
assert is_rotated(lst1, lst2)

# rotation with repeated numbers
lst1, lst2 = [1,2,3,4,6,4,7,1], [6,4,7,1,1,2,3,4]
assert is_rotated(lst1, lst2)

# different set
lst1, lst2 = [1,2,3,4,6,4,6], [6,4,7,1,2,3,4]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,6,1,2,3,4]
assert not is_rotated(lst1, lst2)

# equal
lst2 = lst1
assert is_rotated(lst1, lst2)

# empty
lst1, lst2 = [], []
assert is_rotated(lst1, lst2)

# 1 empty, 1 not empty
lst1, lst2 = [], [1]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1], []
assert not is_rotated(lst1, lst2)


Slow Flask-SQLAlchemy query using association tables

Saw your post on indiehackers. I don't know this orm, but generally speaking, I see you have two options.

Decide to preload/precache the data when your app starts and refresh it occasionally, if you insist on having all records available.

But some good advice I've read is : never do in real time what you can do in advance. So... Why not even build some "top posts" table and seed that?


A user will probably not be able to hurt your server. You do open your system up to SSRF which might cause a problem, depending on your system. There might also be a possibility to DOS your server as you keep connections open for 60 seconds, which is a rather long time (I'm not quite sure about this, but you should definitely test this).

You also provide your users the possibility to attack other systems using your server. They may exploit vulnerabilities in other systems that can be exploited via GET, and they may use your server to scan websites because you allow a keyword search. It may also aid in DOS attacks. You may or may not be liable for damages causes by this, I personally wouldn't risk it.

At a minimum, I would disable the keyword search, limit the amount of requests a user can do, and change the user agent to something more honest (eg MyAvailabilityChecker (more info: http://mywebsite.com/availabilitychecker), and provide an option to opt-out).

Regarding your code: It's generally good. A couple of points:

your comments don't add anything (except the comment about time in ms). And they are partly wrong (eg stop after 10 redirects). I would just remove them.
why proc? Shouldn't it be prot? Either way, don't shorten variable names, it makes code harder to read. Same goes for maxredirs. Also, use snake_case for all variables, so it might be max_redirects (max is commonly used, so shortening is ok).
else {$izkey = 0;} is not properly formatted.


Because the task within the Dispatcher is a long running task, you should use the option TaskCreationOptions.LongRunning. Otherwise the operation blocks a thread-pool thread that is usually used for short operations. Alternatively you could also use a Thread.
Instead of using the blocking collection for returning the result, you could use a TaskCompletionSource. That would change the return value of the method Invoke to Task<T>. Therfore the calling code could use the async/await-pattern.
Consider to throw an exception if the Dispatcher was stopped and Invoke is called. Otherwise the call blocks forever, right?


Bug

The - and / operators interpret their operands backwards from the typical RPN order.  That is, I expect "10 7 -" should produce 3, but it actually produces -3.

Recursion

Your code is awfully repetitive, because the handler for each operator has to fetch the operator ((first l)), perform the operation, then make the recursive call ((exec (rest l) … (inc opcount))).  It would be worthwhile to define a helper function that applies the operator to the stack.

(define (apply-op op stack)
  (cond
    [(number? (string->number op))
     (cons (string->number op) stack)]
    [(equal? op ".")
     (begin
       (display (first stack))
       (display " ")
       (rest stack))]
    [(equal? op "+")
     (cons (+ (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "-")
     (cons (- (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "*")
     (cons (* (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "/")
     (cons (/ (second stack) (first stack)) (rest (rest stack)))]
    [(equal? (string-downcase op) "dup")
     (cons (first stack) stack)]
    [else
     (~a "operation '" op "' invalid")]))

Then, the exec function just has to call it and drive the recursion.

(define (exec ops (stack empty) (opcount 1))
  "executes a stack based program."
  (cond
    [(empty? ops) (void)]
    [else
      (let ([next-stack (apply-op (first ops) stack)])
           (if (string? next-stack)
               (~a "Error at operator " opcount ": " next-stack)
               (exec (rest ops) next-stack (+ opcount 1))))]))


Note that you can use multiple return statements in a method, so instead of using goto, you can use a return statement. I.e:

if (s == null)
{
    return false;
}


While not answering your question, I would like to point out problems with your loop conditions.

First, the condition X != 99 - 1 looks strange. It is the same as X < 98 in this context. The same holds for Y. Since Y < 98, if you increment Y by one, Y is still Y < 99 and will never be Y > 98!

Arrays go from 0 to N-1. Let us assume that you have declared something like

const int N = 99;

Layer[,] layer = new Layer[N, N];

You would make two nested loops

for (int x = 0; x < N; x++) {
    for (int y = 0; y < N; y++) {
        layer[x,y].Update(x,y);
    }
}

In .NET 4.0 there is a parallel for statement, however if you are updating the UI, what your Update statement suggests, then a parallel processing is of little help. Only "pure" calculations will experience an increased calculation power when using parallel processing. Also, the single tasks must have a substantial amount of work to process; otherwise the overhead associated with parallel processing will outweigh the benefits.

See Parallel.For Method in .NET 4.0 vs the C# For Loop.


Computing the sum of all measures for a certain group type

If possible, I'd change the GroupColumns to be an array instead. That way, all you need to do is use .includes to see if an item is included in it. Other improvements can be:
Let TS automatically infer types when possible. You only need to denote the type of a variable or the type of a return value when TS can't do so on its own. TS can automatically determine that ComputeSpecificColumnMeasure returns a number. It can also determine that measure will be a number, so there's no need to denote the type of either of those.
Avoid String type The "String" type is something created via the String constructor, eg const str = new String('data');. This is almost never what you want - for a normal string, use the string (primitive) type instead. (TSLint rule: ban-types)
Avoid any You have data: Array<IDynamic<any>>. any should be avoided in TypeScript whenever possible, because it's so flexible - it loses type safety. If you don't know what the type will be, use unknown instead, which is type-safe.
For a small example of a problem with any:
const fn = (arg: any) => {
    console.log(arg.toFixed(2));
}

This will not throw a TS error, but it's likely to throw a runtime error unless the argument passed happens to be a number. Using unknown instead will throw a TS error - it'll force you to narrow the type first before calling a particular method on it.
const fn = (arg: unknown) => {
    if (typeof arg === 'number') {
        console.log(arg.toFixed(2));
    }
}

Even if the value that's any isn't being used in the function, it'd good practice to avoid any when possible anyway. (TSLint rule: no-unsafe-any)
Capitalization Conventionally, only a few things use PascalCase in JS:

Namespaces (eg React)
Classes
Enums, sometimes

A plain method should probably use the standard camelCase instead.
const groupColumns = [
    'Column Type X',
    'Column Type Y',
    'Column Type Z'
] as const; // Use "as const" to prevent automatic widening to `string[]`

private computeSpecificColumnMeasure(data: Array<IDynamic<unknown>>, groupType: string) {
    let measure = 0;
    data.forEach(el => {
        if (el.group2 === groupType && groupColumns.includes(el.group1)) {
            measure += el.measure;
        }
    });
    return measure;
}

Or, you could use .filter and reduce if you wished:
private computeSpecificColumnMeasure(data: Array<IDynamic<unknown>>, groupType: string) {
    return data
        .filter(el => el.group2 === groupType && groupColumns.includes(el.group1))
        .reduce((measureSoFar, el) => measureSoFar + el.measure, 0);
}


You might want to look into string interning:

  The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

While it has some memory-related side-effects, you could avoid having to build up a dictionary like this and throw away allocated strings to keep it updated.


Go Lang custom convert array into string with two separators

The Go standard library strings package has a Join function:
func Join(elems []string, sep string) string

Your function is a simple extension of strings.Join:
func JoinLast(elems []string, sep, lastSep string) string

However, for no obvious reason, you chose a different function parameter signature:
func JoinLast(sep string, lastSep string, words ...string) string

We need a comment to explain why this isn't an arbitrary or idiosyncratic decision.

Your testing is inadequate. Check boundary conditions. Your function fails on an empty words list.
words = []string{}

You have not provided any testing benchmarks. For example,
BenchmarkJoin-4   5534918  207.9 ns/op   104 B/op  5 allocs/op

func JoinStringsIntoArray(sep string, lastSep string, words ...string) string {
    lastElementIndex := len(words) - 1
    var joinedString string

    for index, word := range words[0:lastElementIndex] {
        if index == lastElementIndex-1 {
            sep = lastSep
        }
        joinedString += word + sep
    }

    joinedString += words[lastElementIndex]

    return joinedString
}

func BenchmarkJoin(b *testing.B) {
    words := []string{"one", "two", "three", "four", "five"}
    b.ReportAllocs()
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        JoinStringsIntoArray(", ", " and ", words...)
    }
}

You can do better. For example, minimize allocation,
BenchmarkJoin-4  16612879   70.95 ns/op   32 B/op  1 allocs/op

func JoinLast(elems []string, sep, lastSep string) string {
    var join strings.Builder
    joinCap := 0
    for i := 0; i < len(elems); i++ {
        joinCap += len(elems[i])
    }
    if len(elems) > 1 {
        joinCap += len(lastSep)
        if len(elems) > 2 {
            joinCap += (len(elems) - 2) * len(sep)
        }
    }
    join.Grow(joinCap)

    last := len(elems) - 1 - 1
    for i, elem := range elems {
        if i >= last {
            if i == last {
                sep = lastSep
            } else {
                sep = ""
            }
        }
        join.WriteString(elem)
        join.WriteString(sep)
    }

    return join.String()
}

func BenchmarkJoin(b *testing.B) {
    words := []string{"one", "two", "three", "four", "five"}
    b.ReportAllocs()
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        JoinLast(words, ", ", " and ")
    }
}


Is this Josephus problem solution bad or really bad?

You can simplify the code if you use (number + 1) % len(self.ppl). This is as it loops back around to the front of the list for you.
If you remove the prints then the code is easier to understand.
You can change creating_list to list(range(...)).
You don't need creating_list to be its own function.
You can combine run into kill removing the class. Leaving:

def game(n):
    ppl = list(range(1, n+1))
    has_gun = 1
    while True:
        number = ppl.index(has_gun) + 1 % len(ppl)
        del ppl[number]
        if len(ppl) > 1:
            number = ppl.index(has_gun) + 1 % len(ppl)
            has_gun = ppl[number]
        if len(ppl) == 1:
            return ppl[0]

You can move the if len(ppl) == 1: check into the statement of the while loop. This makes it easier to see that the function will always return.
You should rename your variables to make it easier to understand things. people over ppl.
Rather than using people.index store the index.

def game(people):
    people = list(range(1, people+1))
    index = 0
    while len(people) >= 1:
        index = (index + 1) % len(people)
        del people[index]
    return people[0]

Error if there is less than one person.
Allow taking a custom skip.

And you'd get to the function that I wrote to test your code:

def josephus_problem(people, amount):
    if people < 1:
        raise ValueError("There has to be at least one person")
    people = list(range(1, people+1))
    index = 0
    while len(people) > 1:
        index = (amount + index) % len(people)
        people.pop(index)
    return people[0]


Is there any way to make this CoffeScript code simpler / smaller

This is how I would write it.

lineEndings = (s, len) ->
  words = s.split ' '
  line = []
  result = []
  for word in words
    if line.length + 1 + word.length <= len
      line = [line..., word]
    else
      result.push line.join ' '
      line = [word]
  lastLine = line.join ' '
  result.push lastLine if lastLine
  result.join "\n"

There's nothing wrong with how you wrote it, though.


Replacing a For Each loop with something faster

This smells:

' opens a userform and collects the min value, assigned to UserSelectionMin (which is declared as an integer)
MinScore
' opens a userform and collects the max value, assigned to UserSelectionMax (which is declared as an integer)
MaxScore

You are using global variables - variables should have the tightest possible scope, and be passed to procedures as parameters; both MinScore and MaxScore should be Function procedures that return a value.

Sub MinScore()
With RandomScoreFormMin.ListBoxMin
.AddItem "0"
.AddItem "1"
End With
RandomScoreFormMin.Show vbModal
End Sub

Indentation is important for readability. It should look something like this:

Sub MinScore()
    With RandomScoreFormMin.ListBoxMin
        .AddItem "0"
        .AddItem "1"
    End With
    RandomScoreFormMin.Show vbModal
End Sub

However a more pressing issue is the fact that you are working against the form's default instance - which is a bad habit to take. Instead, you should create an object:

Dim view As RandomScoreFormMin
Set view = New RandomScoreFormMin

view.ListBoxMin.AddItem "0"
view.ListBoxMin.AddItem "1"

view.Show vbModal

and as I mentioned, that should be a function, which returns the user-selected min value:

Private Function GetMin() As Integer
    Dim view As RandomScoreFormMin
    Set view = New RandomScoreFormMin

    view.ListBoxMin.AddItem "0"
    view.ListBoxMin.AddItem "1"

    view.Show vbModal

    GetMin = view.ListBoxMin.Value
End Function

Now you no longer need to worry about loading/unloading the form, since a new instance is used every time this function is called. And then the calling code can use a local variable instead of a global:

Dim minValue As Integer
minValue = GetMin

Regarding the performance of the ForEach loop:

For Each c In Worksheets("matches").Range(addr).Cells
    If Abs(c.Value) = 0 Then
        c.Value = WorksheetFunction.RandBetween(UserSelectionMin, UserSelectionMax)
    End If
Next

Taking the absolute value of the cell's content looks like a little hack - that would deserve a little comment to explain why it's done, otherwise a maintainer might deem it redundant, and remove it.

My guts are telling me that it's a way of getting an Integer value from the cell, even if the cell is empty. In that case, CInt(c.Value) would do a better job.

Another thing is that you are updating a worksheet in a tight loop; Excel is redrawing itself and recalculating the affected cells every time a value is written!

You can turn off screen updating and automatic calculation, while you're updating the sheet's contents:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Just don't forget to set ScreenUpdating back to True and calculation back to automatic after the loop completes (ideally in an error handler, so that if a runtime error occurs, screen updating is turned back on), so that Excel doesn't appear to remain "frozen"!

You have a potential bug here:

Dim addr As String
addr = Selection.Address

You're using the currently selected range's address...

For Each c In Worksheets("matches").Range(addr).Cells

...and then you're assuming that this range is on the "matches" worksheet - and it may not be all the time. If you mean to work with Selection, know that it is a Range, so you could do this instead:

For Each c In Selection.Cells

Otherwise, you need to validate the Selection before you use it - is it on the worksheet you're expecting?

Using WorksheetFunction is inherently slow, and should be avoided as much as possible; if your goal is to return a random number between X and Y, you could use VBA's random number generator instead of a worksheet function - here's a little formula to get a random integer between lowerbound and upperbound:

Int ((upperbound - lowerbound + 1) * Rnd + lowerbound)

Rnd returns a number that's smaller than 1, and greater than or equal to 0. It should be used in conjunction with the Randomize keyword:

Randomize
For Each c In Selection.Cells
    c.Value = Int((UserSelectionMax - UserSelectionMin + 1) * Rnd + UserSelectionMin
Next


Don't write custom scripts for common sysadmin tasks. Using the proper tools will get the job done better, and the solution will be more maintainable — especially by any colleagues you might have.

Using monit, for example, this would just be a matter of writing a simple configuration file.

set logfile /root/process_monitor.log
check process myproc with pidfile /tmp/pidfile.pid
    restart program = "shutdown -r -t 10"  # draconian!
    every "15 4 * * *"
    if memory > 20 MB then restart myproc


Extract lines under the specified heading

Review

Your function skips until the heading is found and than takes element until the next heading. Perhaps we could split these methods up to make them reusable.
Try to avoid var (undesired scope), prefer let or const instead.
Prefer a Tree data structure over flat list for hierarchical data.

Refactored for Reusability

Skip items while a predicate is true.

  function skipWhile(items, predicate) {
    let ok = false;
    return items.filter((value, index, array) => {
      if (!ok && !predicate(value)){
        ok = true;
      }
      return ok;
    });
  };

Take items while a predicate is true.

  function takeWhile(items, predicate) {
    let ok = true;
    return items.filter((value, index, array) => {
      if (ok && !predicate(value)){
        ok = false;
      }
      return ok;
    });
  };

The OP method:

 function getLines (headingId) {
    let lines = skipWhile(data, v => v.id != headingId);
    lines.shift(); // we don't want the heading
    lines = takeWhile(lines, v => !v.isHeading);
    return lines;
  }

And verification:

  console.log(getLines(9).map(x => x.description))

Yielding:

  (3) [ "Blah 7" , "Blah 8" , "Blah 9" ]

You could also create these methods as prototype extensions on Array or refactor them to become generator functions (with yield syntax). I am sure these methods could get optimized for performance somehow.


Show one sheet for each field in pivot filter field

Sheets("pivot").Select
ActiveSheet.Unprotect
ActiveSheet.PivotTables("Pvt_Pck").ShowPages PageField:="Card"
Sheets("pivot").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
Sheets("pivot").EnableSelection = xlNoSelection

This is rather inefficient, and harder to follow than it needs to be. There's no need to Select anything and to work off the ActiveSheet.

Every sheet has a code name, an identifier that you can use in code to refer to it. Think of it as a free object instance living in global scope, waiting to be used. Select the worksheet in the VBE's Project Explorer (Ctrl+R if it's not displayed), and look at its properties (F4 if it's not displayed):

Notice there are two Name properties: one (Name) is the name of the tab in Excel; the other ((Name)) is the name of that "free object" I'm talking about.

If Sheets("pivot") is named Sheet1, then you can .Select it like this:

Sheet1.Select

But you don't need to do this.

You're accessing the Sheets collection (implicitly ActiveWorkbook.Sheets); that collection contains all sheets, and in Excel not all Sheet objects are a Worksheet - the Sheets collection also contains Chart sheets!

So instead of Sheets("name"), you should be accessing Worksheets("name") if you expect to be working with a worksheet. But you don't need to do that either.

And you should avoid implicit references to the ActiveWorkbook or the ActiveSheet: a fully-qualified ThisWorkbook.Worksheets("name") call is more reliable than Worksheets("name").

But I digress. I was saying you don't need to do this. Let's say you gave your "pivot" sheet a code name, and that you can access it in code with the  PivotSheet identifier.

You could then do this:

With PivotSheet
    .Unprotect
    .PivotTables("Pvt_Pck").ShowPages PageField:="Card"
    .Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
    .EnableSelection = xlNoSelection
End With

This does exactly the same thing as the snippet I quoted at the top of this post. Except if you look under the hood. Your code really did this:

In the Sheets collection of the ActiveWorkbook, look for the sheet named "pivot", and Select that sheet (so it becomes the ActiveSheet).
Unprotect the active sheet.
In the PivotTables collection of the ActiveSheet, look for the pivot table named "Pvt_Pck", and change the PageField to "Card".
In the Sheets collection of the ActiveWorkbook, look for the sheet named "pivot", and Protect that sheet.
In the Sheets collection of the ActiveWorkbook, look for the sheet named "pivot", and set EnableSelection on that sheet to xlNoSelection.

Notice everytime you access the Sheets collection, you're working much harder than you need to. Compare to mine:

Using the PivotSheet object reference...

Unprotect it.
In the PivotTables collection, look for the pivot table named "Pvt_Pck", and change the PageField to "Card".
Protect it.
Set EnableSelection to xlNoSelection.

Sub cmdg2b2(control As IRibbonControl)

You should always use names that you can pronounce. cmdg2b2 says nothing more than can be inferred from its IRibbonControl parameter, that it's some Ribbon callback procedure. What does it do? Wouldn't this be easier to work with?

Public Sub SetPivotPageField(ByRef control As IRibbonControl)

The procedure now...

has an explicit access modifier (Public)
is now explicit about how it's receiving its parameter (ByRef)
has a name that starts with a verb, conforms to the PascalCase naming convention of everything else in VBA, and gives us a clue about what's happening in its scope, without having to look at the actual code.

In the ShowSheets method, I can't help but notice these repeated lines:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

You had them in your Ribbon callback procedure too:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Every time you set Application.Calculation to xlCalculationAutomatic, you trigger a recalculation; in a large complicated workbook with lots of lookups and external dependencies, this single instruction alone can take several minutes to complete: don't toggle calculation mode without needing to.

Now, repeating code like this isn't something you want to have all over the place. Make a small procedure for that.

Private Sub ToggleWaitMode(Optional ByVal wait = True, Optional ByVal toggleCalculation = True, Optional ByVal toggleEvents = True)
    With Application
        .StatusBar = IIf(wait, "Please wait...", vbNullString)
        .ScreenUpdating = Not wait
        .EnableEvents = IIf(toggleEvents, Not wait, .EnableEvents)
        .Calculation = IIf(toggleCalcualtion, IIf(wait, xlCalculationManual, xlCalculationAutomatic), .Calculation)
    End With
End Sub

Now instead of copying the same code to toggle these things, you can simply do this before a long-running operation:

ToggleWaitMode

And then this when you're done:

ToggleWaitMode False

Now, seeing "Please wait..." in the status bar for 9 minutes isn't cool at all, and if I'm the user I totally think Excel is frozen. Consider updating progress in the status bar:

Public Sub UpdateStatus(Optional ByVal text As String = vbNullString)
    Dim appScreenUpdating As Boolean
    With Application
        appScreenUpdating = .ScreenUpdating
        If Not appScreenUpdating Then .ScreenUpdating = True
        .StatusBar = text
        .ScreenUpdating = appScreenUpdating
    End With
End Sub

You need this procedure to make sure ScreenUpdating is on before it updates the status bar text, otherwise the user won't see it changing because Excel isn't repainting itself.

These "helper procedures" can now be used to make your code much more focused on what it's supposed to do.

The ShowSheets function isn't returning anything. Function members should have a return value - if you don't need a return value, then make it a Sub (procedure) instead.

ActiveSheet.PivotTables("Pvt_Pck").PivotFields("Card").CurrentPage = "(All)"

You're not activating/selecting any sheet here - the procedure simply assumes that the active sheet has a pivot table named Pvt_Pck... and things could go horribly wrong if that's not the case: with screen updating turned off, and no error handling to turn it back on, things can get messy.

Handle runtime errors!

Public Sub ShowSheets(ByVal conta As String)

    On Error GoTo CleanFail
    ToggleWaitMode

    '...

CleanExit:
    ToggleWaitMode False
    Exit Sub

CleanFail:
    MsgBox Err.Description, vbExclamation
    Resume CleanExit
End Sub

Again, avoid working with the ActiveSheet, be it explicitly or implicitly.

Range("A4").Select

That Range call is an implicit reference to the active sheet - and if that sheet is not a Worksheet object, the Range method will fail, like this:

Not very graceful.

tsheet = Int(.PivotItems.Count / 2)

The Int function may not be working the way you intend it here: it doesn't round anything, it simply cuts the decimal part of the number - so this:

Int(1/2)

Returns 0. It could matter, or not. But it's good to know.

This is annoying:

Select Case conta
Case "A"
    ...
Case "B"
    ...
End Select

You need a comment to explain what the parameter is used for, and then when you call the method you need to know what magic values are being handled. Not cool. Using magic strings or magic numbers is the same thing: you're using magic values.

Make an enum instead:

Public Enum CardDisplayStyle
    ShowTopHalf
    ShowBottomHalf
End Enum

And now instead of passing a magic string "A" or "B", the call site looks like this:

ShowSheets ShowTopHalf

Or:

ShowSheets ShowBottomHalf

And the signature changes to this:

Public Sub ShowSheets(ByVal conta As CardDisplayStyle)

And the Select Case block no longer works off magic strings:

Case ShowTopHalf
    ...
Case ShowBottomHalf
    ...


Traversing from left or from right - Leetcode 140: Word Break II

The difference in runtime of 4ms is very small compared to normal system variance due to scheduling and whatever background tasks are running. I don't believe that indicates a performance benefit right vs left.

And the only difference between the two approaches (as far as I can see) is which order you iterate the string. Algorithmically speaking going right to left is equivalent to reversing the input strings and going left to right. There is no reason why that should be any faster as it's the exact same algorithm.

There maybe be a small difference due to branch prediction and cache hits in the CPU but this is because the input is slightly different and it exercises the CPU every do slightly differently but it will benefit either method randomly based on the input. The expected relative performance, however, is the same.

I'm sorry but I believe the is nothing to improve here.


CREATE TABLE Supplier
  (
  SupplierID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  SupplierName VARCHAR(30) NOT NULL DEFAULT '',
  SupplierTag  VARCHAR(30) NOT Null DEFAULT '',
  );

Why limit the name to thirty characters?  Consider names like "Specialty Products Company of Transylvania" -- that's forty-two characters.  Unless you have a reason to keep it short, it's better to pick a larger width than necessary rather than smaller.  A VARCHAR(255) with a thirty character string in it is the same length as if it were a VARCHAR(30).  You only use storage for what you use.

Also consider using NVARCHAR instead of VARCHAR.  Perhaps some of your suppliers will have names that require Unicode to represent.

CREATE TABLE Category
    (
    CategoryID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CategoryName VARCHAR(30) NOT NULL DEFAULT '',
    CreatedBy VARCHAR(30) NOT NULL DEFAULT '',
    CreatedOn DATETIME NOT NULL
    );

CREATE TABLE Sub_Category
    (
    SubCategoryID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    SubCategoryName VARCHAR(30) NOT NULL,
    CategoryID INT FOREIGN KEY REFERENCES CATEGORY(CategoryID),
    CreatedBy VARCHAR(30) NOT NULL,
    CreatedOn DATETIME NOT NULL
    );

You can only have two levels of category and you must have two levels of category.  If you want to add a third level, you'd have to add a new table (or refactor the existing tables).  It is more common to handle this with a single table that has a ParentID column.

CREATE TABLE Category
    (
    CategoryID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ParentID INT NOT NULL DEFAULT 0,
    CategoryName VARCHAR(30) NOT NULL DEFAULT '',
    CreatedBy VARCHAR(30) NOT NULL DEFAULT '',
    CreatedOn DATETIME NOT NULL
    );

Example showing how to use a table like this:  Getting all the children of a parent using MSSQL query.

CREATE TABLE Manufacturer
    (
    ManufacturerID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ManufacturerName VARCHAR(30) NOT NULL DEFAULT '',
    SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
    );

This says that a Manufacturer is associated with a SUB_CATEGORY.  This seems overly restrictive.  For example what if your subcategories are video and music?  A company may very well deal in both.

CREATE TABLE Products
  (
  ProductID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductName   VARCHAR(50) NOT NULL DEFAULT '',
  CategoryID INT FOREIGN KEY REFERENCES CATEGORY(CategoryID),
  SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
  ManufacturerID INT FOREIGN KEY REFERENCES Manufacturer(ManufacturerID)
  );

Given your original schema, you should be careful about having both a CategoryID and a SubCategoryID.  This is what is called a denormalized schema.  You can associate a CategoryID with a Product in two different ways.  In a normalized schema, you only want there to be one association.  Consider the case where CategoryID is not the parent of SubCategoryID.

Note that if you change to a single table with a ParentID, that it will also make sense to only associate the product with one level of category.

Consider the possibility that you might need products to be in more than one category at once.  For example, you might create a Specials category.  In that case, you might need to link Products and Category with a table rather than a column.

Note that you usually either want all the names to be singular (like Category and Manufacturer) or all to be plural (like Products).  Pick a convention and stick to it.

CREATE TABLE ProductSpecs
(
  RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductID INT FOREIGN KEY REFERENCES Products(ProductID),
  SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
  ProductSpec1 VARCHAR(30),
  ProductSpec2 VARCHAR(30),
  ProductSpec3 VARCHAR(30),
)

Given this description, you might be better off adding three columns to Products.  Although I would strong consider making a Specification table and a SpecificationToProduct table.  That way you can easily add more than three specifications to a product and multiple products can have the same specification.

Try to avoid names like RowID.  Go ahead and name this ProductSpecID or leave off that column altogether.

CREATE TABLE ProductAvailability
(
  RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductID INT FOREIGN KEY REFERENCES Products(ProductID),
  SupplierID INT FOREIGN KEY REFERENCES Supplier(SupplierID),
  SupplierWEB Varchar(30) NOT NULL,
  ProductPrice decimal(6,2) NOT NULL,
)

This seems a good place to use a composite primary key based on ProductID and SupplierID rather than RowID.

CREATE TABLE ProductAvailability
(
  ProductID INT FOREIGN KEY REFERENCES Products(ProductID),
  SupplierID INT FOREIGN KEY REFERENCES Supplier(SupplierID),
  SupplierWEB Varchar(30) NOT NULL,
  SupplierPrice decimal(6,2) NOT NULL,
  PRIMARY KEY (ProductID, SupplierID)
)

If ProductPrice is the supplier's price for the product, then SupplierPrice might be a better name.

It's not clear to me what a SupplierWEB is nor why it would be associated with the Supplier/Product link.  If it is the supplier's product page, then a name change might be clearer.  Also, it should probably be wider than thirty characters if it is meant to hold a link.

Your diagram does not match your table specifications.  I reviewed the table specifications.  If the diagram better reflects your actual design, you should post another question where the table specifications match the diagram.


x64 Assembly - checking for largest prime factor

One optimisation that would make your code run up to twice as fast, is to use the observation that a prime factor of n cannot be greater than n/2. So you can limit the number of times you iterate through your loop.

Additionally, you know that once you have tested for divisibility by 2, then subsequent trial divisions can skip all even numbers. If you continue down this road, you'll eventually implement a prime sieve using all the same tricks.

One thing I would suggest is to use jmp instead of jnz at the bottom of the loop. It might or might not make a performance difference, but you'll avoid the CPU (and your readers) from having to think about the condition.

It probably doesn't matter, but you could move the mov rdx, 0 up above the noinc label because whenever you jz noinc, you already know that rdx is zero. This sort of thing really needs to be clearly documented, of course.


Creating custom week start and week number

You really don't need to iterate, just do the (mod 7) math to get the correct date directly:

public static DateTime getFirstWorkDateOfYear(int year, int firstDay) {
    ReadWritableDateTime readWritableDateTime = new MutableDateTime(year, 1, 1, 0, 0, 0, 0);
    int doW = readWritableDateTime.getDayOfWeek();
    readWritableDateTime.addDays((7 + firstDay - doW) % 7);
    return readWritableDateTime.toDateTime();
}

public static DateTime getStartOfWorkWeek2(DateTime dateTime, int firstDay) {
    ReadWritableDateTime readWritableDateTime = dateTime.toMutableDateTime();
    readWritableDateTime.setMillisOfDay(0);
    int doW = readWritableDateTime.getDayOfWeek();
    readWritableDateTime.addDays(((firstDay - doW - 7) % 7));
    return readWritableDateTime.toDateTime();
}

The technique proposed is not particularly dependent on which date library you use; with minor variations it can be applied to normal Date or Calendar types.  While I like joda, in general, I have no opinion on its performance on Android.


Here's a solution using threads:

import sys
import os
import platform
import subprocess
import Queue
import threading

def worker_func(pingArgs, pending, done):
    try:
        while True:
            # Get the next address to ping.
            address = pending.get_nowait()

            ping = subprocess.Popen(ping_args + [address],
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE
            )
            out, error = ping.communicate()

            # Output the result to the 'done' queue.
            done.put((out, error))
    except Queue.Empty:
        # No more addresses.
        pass
    finally:
        # Tell the main thread that a worker is about to terminate.
        done.put(None)

# The number of workers.
NUM_WORKERS = 4

plat = platform.system()
scriptDir = sys.path[0]
hosts = os.path.join(scriptDir, 'hosts.txt')

# The arguments for the 'ping', excluding the address.
if plat == "Windows":
    pingArgs = ["ping", "-n", "1", "-l", "1", "-w", "100"]
elif plat == "Linux":
    pingArgs = ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1"]
else:
    raise ValueError("Unknown platform")

# The queue of addresses to ping.
pending = Queue.Queue()

# The queue of results.
done = Queue.Queue()

# Create all the workers.
workers = []
for _ in range(NUM_WORKERS):
    workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))

# Put all the addresses into the 'pending' queue.
with open(hosts, "r") as hostsFile:
    for line in hostsFile:
        pending.put(line.strip())

# Start all the workers.
for w in workers:
    w.daemon = True
    w.start()

# Print out the results as they arrive.
numTerminated = 0
while numTerminated < NUM_WORKERS:
    result = done.get()
    if result is None:
        # A worker is about to terminate.
        numTerminated += 1
    else:
        print result[0] # out
        print result[1] # error

# Wait for all the workers to terminate.
for w in workers:
    w.join()


Digital persona fingerprint verification takes a lot of time

Remove everything that is repeated in the loop and return/do the same thing. Put them outside the loop. Example, this draw the same image every time, you only need it once.

DrawPicture(ConvertSampleToBitmap(Sample))

And this seems to get the same feature every time.

Dim features As DPFP.FeatureSet = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification)


Suggestions for compose:

def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

if not arg: What's wrong with arg being falsey? Perhaps that's an acceptable input. Input validation should be designated to the functions being composed, which can raise their own errors.
if not all([callable(f) ...: This line should be before def inner(args). It should be a single-time input validation to ensure that all given inputs in fargs are callable. Currently, it checks needless amounts of times (each inner call) and does not check immediately.
if not all([callable(f) ...: You can use a generator expression instead of a list comprehension for this, slightly improving readability.

If both of these suggestions are implemented, your compose would look like:

def compose(*fargs):
    if not all(callable(f) for f in fargs):
        raise TypeError("Function is not callable")
    def inner(arg):
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

Please tell me if I have misunderstood your code.


TextRenderer class for rendering text with OpenGL

Most include files are written so that they are safe to be included multiple times. So, if your TextRenderer.h needs types from glew.h, you include it. Writing your own include files so that they include everything needed to use them (types, enums, ...) is usually a good thing.

You might write your TextRenderer.hpp something like this:

#ifndef TEXTRENDERER_HPP
#define TEXTRENDERER_HPP

#include <GL/glew.h> // For GLuint

class TextRenderer
{
    ...
}
#endif

The define TEXTRENDERER_HPP is there to make the header safe to be included multiple times. You may choose any unique identifier you like, but usually people use file names with some amounts of underscores at start and end.


Method to remove comments from a string line

I believe it's a good example of a problem that you can represent with a state-machine. What you do with the next character depends on the state you're in:

if you're outside of a comment, then you copy the character unless it's a / or a #
if the last character was a / outside a comment, then test if the new character is a * or a /
if you're inside a single line comment, you ignore it unless it's a newline
if you're inside a multi-line comment, you ignore it unless it's a star
if you've just read a * inside a multi-line comment then you need to check if the new char isn't a /

State-machines aren't always the most elegant way of coding, but they're robust, easy to read and blazingly fast. So how would you implement it in this case?

First, don't read the input line by line. It is probably a mistake since crucial information resides in the previous line, if there's one: you can't know, looking at a line, if a multi-line comment was opened in the previous one. Also, it will force you to perform memory management each time you read a line (you need to check if the output string is big enough and allocate more memory if it isn't), which will slow down your program, whereas looking character by character will allow you greater flexibility (any object exposing iterators on characters is acceptable) and prevent allocations if they aren't needed.

That brings us to the signature:

template <typename InputIt, typename OutputIt>
OutputIt copy_without_comments(InputIt first, InputIt last, OutputIt out)

The OutputIt can be many things: an iterator on an allocated buffer, an iterator constructing a string, an iterator on a stream...

The state machine itself is generally implemented with an enum specifying the possible states:

enum class State : char { SlashOutsideComment, StarInsideComment, SingleLineComment, MultiLineComment, NotAComment };

Then it's only a big switch to know how to handle the next character:

 switch (state) {
            case State::SlashOutsideComment:
                if (*first == '/') state = State::SingleLineComment;
                else if (*first == '*') state = State::MultiLineComment;
                else {
                    state = State::NotAComment;
                    *out++ = '/';
                    *out++ = *first;
                }
                break;
            case State::StarInsideComment:
                if (*first == '/') state = State::NotAComment;
                else state = State::MultiLineComment;
                break;
            case State::NotAComment:
                if (*first == '#') state = State::SingleLineComment;
                else if (*first == '/') state = State::SlashOutsidedComment;
                else *out++ = *first;
                break;
            case State::SingleLineComment:
                if (*first == '\n') {
                    state = State::NotAComment;
                    *out++ = '\n';
                }
                break;
            case State::MultiLineComment:
                if (*first == '*') state = State::StarInsideComment;
        }

Link to test and play with: https://wandbox.org/permlink/iXC7DWaU8Tk8jrf3


Reformatting a date from YYYY-MM-DD to MM/DD/YYYY

Simpler approach

Another option is to construct a Date object (this can be achieved by appending a time at midnight to the date) and pass that to Intl.DateTimeFormat.prototype.format(). Then there is no need to parse it and reconstruct it yourself.

function formatCourseDate(date) {
  const dateObj = new Date(date + 'T00:00:00');
  return new Intl.DateTimeFormat('en-US').format(dateObj);
}
console.log(formatCourseDate('1995-12-17'));

Reviewing your current code

Because this is Code Review and we don't just give alternate approaches, I wanted to also give feedback on the current code.

Given your current approach of splitting the parts of the date:

const _date = date.split('-');
const dateObj = {month: _date[1], day: _date[2], year: _date[0]};

because ecmascript-6 features like const are used, object destructuring and the shorthand property definition notation could also be used to simplify this code:

const date = '2017-11-05';
const [year, month, day] = date.split('-');
const dateObj = {month, day, year};
console.log('dateObj:', dateObj);


PHP script for getting post data from Tampermonkey script

A somewhat better solution would be to take advantage of the fact that PHP auto-generates arrays from REQUEST data, if the fields are named correctly. Thus I propose changing the code posted by you to the following:

var date = new Date();
var data = "date=" + date +
           "&accountsnumber=" + accountsCount +
    accounts.reduce(function (prev, account, n) {
        // Note the use of square brackets here, they tell PHP to create an array.
        return prev + "&d[" + n + "][accountname]=" + account.name +
            "&d[" + n + "][credits]=" + account.credits;
    }, '');

As for the PHP code, it'll look like this:

<?php
// Renamed this to save_contents () as that is what we're actually doing.
function save_contents()
{
    // Use intval () here to ensure that we do indeed have an integer, and not some random injection code.
    $accountnumber = intval ($_POST['accountsnumber']);

    // Validate with DateTime to verify that this is indeed a valid date.
    $date = new DateTime ($_POST['date'], new DateTimeZone (DEFAULT_TIMEZONE));

    // Format the date, and use htmlspecialchars to ensure HTML-conformity of the output.
    $str = 'Updated last: %s

';
    $output = sprintf ($str, htmlspecialchars ($date->format ("Y-m-d")))

    // Create a string template to use with sprintf (), to make the code easier to read.
    $str = 'Account %1$d
(%2$s)
CREDITS
%3$s
-<br /';

    for ($id = 1; $id <= $accountnumber; $id++) {
        // Use htmlspecialchars to protect against XSS.
        $accName = htmlspecialchars ($_POST['d'][$id]['accountname']);
        $credits = htmlspecialchars ($_POST['d'][$id]['credits']);

        $output .= sprintf ($str, $id, $accName, $credits);
    }

    file_put_contents("content.html", rtrim ($output, '
-
'));
}

As you can see I've added some basic protection against attackers as well, as the code posted by you is woefully insecure. Basically allowing whomever wants full access to your web-server, to do whatever they like!
Check out OWASP for more information.


Add an extra local variable before the first loop:

int maxItems = iconConfiguration.getMax_positions();
if (maxItems == -1) {
    maxItems = gwInputBaseDataList.size();
}

This way if you didn't specify a max in the configuration you just use "all" input items.

You can go a little bit further as well and use this as the condition on the outer for loop:

for (int i = 0; i < maxItems; i++) {
    if (getItemsMap().get(i) != null && getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)) != null) {
        gwBaseDataList.add(i, getBaseDataInListById(gwInputBaseDataList, getItemsMap().get(i)));
    } else {
        for (int j = 0; j < gwInputBaseDataList.size(); j++) {
            if (!gwBaseDataList.contains(gwInputBaseDataList.get(j))) {
                gwBaseDataList.add(gwInputBaseDataList.get(j));
                break;
            }
        }
    }
}
return gwBaseDataList;

I couldn't actually test this code, so make sure it's not off by 1 on the index when you try it yourself. And just to be safe test if this still actually does what you want it to do for all edge cases.

EDIT bugfix:

In case the max from the configuration is larger than the actual size you'll get an index out of bounds. Fixed by changing the if condition to the folowing:

if(maxItems == -1 || maxItems > gwInputBaseDataList.size()){


Testing whether an abstract object is an instance of one of the several concrete classes

Assuming that you have a good reason for not having an overriden GetValue() method on each sub-class, an extension method for each class, say, GetValue() should solve it.

public static class ObserverExtensions
{
  private static readonly IDictionary<Type, Func<ObserverDto, string>> _lookup = new Dictionary<Type, Func<ObserverDto, string>>
  {
     {typeof(BooleanObserverDto), dto => ((BooleanObserverDto)dto).GetValue() },
     {typeof(IntObserverDto), dto => ((IntObserverDto)dto).GetValue() },
     {typeof(DecimalObserverDto), dto => ((DecimalObserverDto)dto).GetValue() },
     {typeof(StringObserverDto), dto => ((StringObserverDto)dto).GetValue() },
  };

  public static string GetValue(this ObserverDto observerDto)
  {
       return _lookup[observerDto.GetType()](observerDto);
  }

  public static string GetValue(this BooleanObserverDto booleanObserverDto)
  {
     return booleanObserverDto.CurrentValue == true ? booleanObserverDto.TrueText :
            booleanObserverDto.CurrentValue == false ? booleanObserverDto.FalseText : booleanObserverDto.CurrentValue.ToString();
  }

  public static string GetValue(this IntObserverDto intObserverDto)
  {
     return intObserverDto.CurrentValue.ToString();
  }

  public static string GetValue(this DecimalObserverDto decimalObserverDto)
  {
     return Convert.ToSingle(decimalObserverDto.CurrentValue).ToString(CultureInfo.CurrentCulture);
  }

  public static string GetValue(this StringObserverDto stringObserverDto)
  {
     return stringObserverDto.CurrentValue;
  }
}

//...
Value = ObserverDto.GetValue();

One nice thing about this solution  is that we can add more classes (say, DateTimeObserverDto) without having to open up the set/update code. We simply add another extension method.

Edit: Correction

The extension methods only work if the references to the objects are of the concrete type. It doesn't work when passing in ObserverDto objects

// Passed
[TestMethod]
public void CheckConversions()
{
     var a = new IntObserverDto { CurrentValue = 17 };
     var b = new DecimalObserverDto { CurrentValue = 19.1m };
     var c = new BooleanObserverDto { CurrentValue = false };
     var d = new StringObserverDto { CurrentValue = "Hello World" };

     Assert.AreEqual("Hello World", d.GetValue());
     Assert.AreEqual("False", c.GetValue());
     Assert.AreEqual("19.1", b.GetValue());
     Assert.AreEqual("17", a.GetValue());
}

// Fails (doesn't compile) - no GetValue() for ObserverDto
[TestMethod]
public void CheckConversions()
{
     ObserverDto a = new IntObserverDto { CurrentValue = 17 };

     Assert.AreEqual("17", a.GetValue());
}

Best I can think of (sans adding a virtual method to ObserverDto) is use a lookup in the extension method (see above)


More efficient jQuery scripting when manipulating multiple elements with multiple CSS attributes

I would say two things could improve this considerably:

Use CSS classes elements that share the same animations. This way you can just fetch all the elements that need to be animated with a single $(). e.g. $('.animate')
Instead of using jQuery's animation methods, use CSS transitions. This will make your code simpler, and you know you're using the browser's native animation rendering.

Here's an example:

Logo 1

Logo 2

Some text

You could simplify this even further by using a single CSS class for all elements that need animating. e.g. $('.needs-animation').addClass('animate');

Also, if there are any animations that are triggered by mousehover, you could do all the animation in CSS with the :hover pseudo-selector.

Finally, make sure the CSS transitions you use are compatible with all the browsers you're supporting.


General Notes

First - In addition to replacing the magic numbers, I'd put your file path into a constant at the top of the module for easier maintenance:

Private Const WORD_DOCUMENT_LOCATION As String = "C:\Users\<user>\Desktop\CyberAwareness.docx"

Second - Get a reference to the Worksheet object at the start of the function instead of relying on calls to ActiveSheet.  Nothing will make the wheels come off of a long function faster than the user doing something that changes the active Workbook or Worksheet in the middle of your execution.

Dim sheet As Worksheet
Set sheet = ActiveSheet

Third - Using Range addressing C2 or L3 is not only harder to read, it is less efficient as well. Not only do you have to concatenate strings in order to build the addresses, Excel just has to convert them back into numeric indexes. Unless you have a really good reason not to do so, using .Cell(row, column) is almost always better and is much easier to use in loops.

'Instead of this...
sheet.Range("A" & i).Value = foobar
'...do this:
sheet.Cells(i, 1).Value = foobar

Fourth - Get into the habit of declaring the scope of your Subs and Functions to make sure that you are only exposing the ones that you intend to. If you leave these off, they will default to public and start showing up in your function list in the Workbook and be available for auto-complete. If it isn't something you would want to show up in a cell, i.e. =SearchWordDoc("this raises","an error"), declare it as Private.

Finally - Declare your function return types. It isn't clear what the code below returns, and the comment makes it worse - it doesn't return a Date at all, it returns a String.

'Searches word file for name, finds the associated paragraph, and returns the date'
Function SearchWordDoc(strPath, strName)

Taken in conjunction with the item above, the function declaration should really be something like this:

Private Function SearchWordDoc(filepath, name) As String

Performance

As @RubberDuck noted, the biggest performance boost you're going to get is from not repeatedly opening and closing the Word document. Most of the other suggestions are spot on, so I'll limit this answer to the performance aspect of the code.

Based on your existing code, it is apparent that there is only one line per person in your Word document and all of the lines have (or should have) the same structure.  What you are essentially doing is performing a lookup on a Word file based on a key.  VBA has an object that is designed to perform key lookups that are orders of magnitude faster than Word's .Find method - Scripting.Dictionary. All you need to do is parse the document first as text to build your object.  For example (with a reference to Microsoft Scripting Runtime):

Private Function LoadWordRecords(filepath As String) As Scripting.Dictionary

    Dim host As New Word.Application
    Dim doc As Word.Document
    Dim lines() As String

    Set doc = host.Documents.Open(filepath)
    'Take the whole document in one shot, and read to an array of paragraphs...
    lines = Split(doc.Content.text, vbCr)
    '...and dispense with Word.
    doc.Close
    host.Quit

    'Then do whatever you need to do to parse the text into a useful structure:
    Dim output As New Scripting.Dictionary
    Dim items() As String
    Dim i As Integer

    'Parse each line in the Word document to extract a key for the line.
    For i = 0 To UBound(lines)
        'Add whatever you need to validate the paragraph you're parsing.
        'Test the input line to see if it contains a comma.
        If (InStr(1, lines(i), ",") > 0) Then
            'Split into an array from the comma delimited string.
            items = Split(lines(i), ",")
            'Add the resulting item to the Dictionary with the key defined
            'as the first 2 elements and the value as the remainder of the line.
            Call output.Add(Trim$(items(0)) & ", " & Trim$(items(1)), items(2))
        End If
        'Or whatever is convenient.
    Next i

    Set LoadWordRecords = output

End Function

Then, all you have to do in the calling code is grab the Dictionary from your parsing function and grab the lines as needed based on the keys:

Public Sub SearchTextFile()

    Dim sheet As Worksheet
    Set sheet = ActiveSheet

    Dim i As Integer
    Dim currentCellNumberLname As String
    Dim currentCellNumberFname As String
    Dim currentCellData As String
    Dim firstPlusLastName As String

    'Load your lookup object:
    Dim entries As Scripting.Dictionary
    Set entries = LoadWordRecords(WORD_DOCUMENT_LOCATION)

    For i = 2 To 4
        currentCellNumberLname = "C" & i
        currentCellNumberFname = "D" & i
        currentCellToAdd = "L" & i
        ActiveSheet.Range(currentCellToAdd).Activate
        ActiveWindow.ScrollRow = ActiveCell.row
        firstPlusLastName = sheet.Range(currentCellNumberLname).Value & ", " & sheet.Range(currentCellNumberFname).Value

        'Retrieve lines by keys for parsing:
        sheet.Range(currentCellToAdd) = Left(Right(entries(firstPlusLastName), 22), 11)
    Next

End Sub

My rule of thumb is that Windows COM calls are generally expensive, and are best avoided if alternatives exist. This should be finishing on the order of seconds not minutes, and the majority of the processing time should be coming from simply opening the Word document.


Executor tasks for parallelizing a method

First of all, regarding your questions:

Yes. The 4 Futures will be mapped to 4 executor threads for all practical considerations. There might be edge-cases, where the first future is finished before the last is submitted and a thread gets reused, but this does not lead to any practical implications.
No, the i is a local variable. There is a different instance in each thread.
As you go index-based, you might as well use start- and end-indexes for your Future executions instead of sublists. On the other hand, if the list is an ArrayList this is exactly what happens under the hood of the sublist call.
Yes, I cannot see the question there.

However, your code has some other points worth addressing:

as AJNeufeld already mentioned, deleteObject() gets called twice per object
if a single object deletion fails, the following objects in that sublist will not even be attempted - is that the expected behaviour?
Callable is a functional interface, so instead of creating an anonymous subclass for each callable, simply use a lambda expression: () -> parallelDeleteOperation(listDir1)
index-based list traversal only makes sense if you actually need the index variable. In this case, you should use for(int x : listDir)

Regarding the general principle: you try to do many things manually and via a design decision, which the system already can do for you. Especially the idea to use exactly 4 CPUs is odd: if the target machine only has 2 CPUs you will wast time through unnecessary thread-switches, on an 8-core half of the machine is idle.

Additionally, as I already mentioned above, you don't attempt to delete every object, but only up to the first failure.

To rectify this, I suggest that you simply use a parallelStream which will be split to a number of cores suited for the given machine automatically, and collect the total success value via a reducer:

boolean allDeletionsSuccessful
= listDir.parallelStream()             // split to number of cores
    .map(x -> deleteObject(x))         // attempt each deletion, record success value
    .reduce(true, (x, y) -> x & y);    // merge with logical AND