Well, it took time to figure out what your program is doing. So I did shorten it in two phases.
First phase: I removed all duplicate temporary files, and used a pipe when a temp file was used once.
STEP1: you just make a checksum of all files in $path1 and $path2
### Find all filename and convert to MD5 ###
find $path1 -type f | xargs md5sum > checksums.md5
find $path2 -type f | xargs md5sum > checksums2.md5

You don't need 2 temp files, as path is included in filename. So you can replace this with a single find. I use sort to be able to use uniq afterwards:
find "$path1" "$path2" -type f | xargs md5sum  | sort > cksum.md5

STEP2: you find unique checksums in both files, and get the corresponding filenames.
### Compare to find different folder ###
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums.md5 checksums2.md5 > hasil1.txt
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums2.md5 checksums.md5 > hasil2.txt

### Merge result of compare ###
awk '{print $0}' hasil1.txt hasil2.txt > perbedaan.txt

### Filter Just Filename Difference ###
cat perbedaan.txt | awk '{print $2}' > hasilperbedaan.txt

As we have a checksum-sorted file, we just filter with uniq, and get filenames.
Note: As we use a MD5 checksum (128 bits), length is 128bits / 8bits * 2hex=32
uniq -u -w32 cksum.md5 | awk '{print $2}' > "$cekhasil"

If you prefer awk to uniq, just compare previous record's $1 with current's.
STEP 3: you match found entries with a new search (find) in the two source paths.
if [ -s "$cekhasil" ]
then
    echo " file exists and is not empty "
    ### Find All filename and date, after that put as we want ###
    find $path1 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate1.txt
    find $path2 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate2.txt

    ### Compare to get the date of filename ###
    awk 'A[$1]++' hasilperbedaan.txt filedate1.txt > pre_hasil1.txt
    awk 'A[$1]++' hasilperbedaan.txt filedate2.txt > pre_hasil2.txt
    ### Merge result of compare with date ###
    awk '{print $0}' pre_hasil1.txt pre_hasil2.txt > lengkap.txt
else
    echo " file does not exist, or is empty "
fi

Here, it is better to avoid new full find, and just loop over filenames.
if [ -s "$cekhasil" ]
then
    echo " file exists and is not empty "
    while read -r fn ; do
        ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'
    done < "$cekhasil" > lengkap2.txt

else
    echo " file does not exist, or is empty "
fi

Alltogether, the script becomes:
#!/bin/bash

path1=/home/br/dev/tools/bash
path2=/home/br/dev/tools/bash2
outfile=hasilperbedaan.txt

find "$path1" "$path2" -type f | xargs md5sum  | sort > cksum.md5

uniq -u -w32 cksum.md5 | awk '{print $2}' > "$outfile"

if [ -s "$outfile" ]; then
    echo " file exists and is not empty "
    while read -r fn ; do
        ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'
    done < "$output" > lengkap2.txt

else
    echo " file does not exist, or is empty "
fi

At this point, we can notice the 2 remaining temp files are used only once. We just get rid of them, and just pipe all together to get the output file.
    #!/bin/bash

    path1=/home/br/dev/tools/bash
    path2=/home/br/dev/tools/bash2
    outputfile="lengkap-v2.txt"

    find "$path1" "$path2" -type f | xargs md5sum  | sort |
        uniq -u -w32 | awk '{print $2}' |
        while read -r fn ; do
            ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'
        done > "$outputfile"
    [[ -s "$outputfile" ]] && echo " file exists and is not empty " ||
            echo " file does not exist, or is empty "

Notes:

I don't understand your second question: "Put command in variable if
can", so I skip that one.
You should never use the output of find (except with -print0 options) or ls as input of any command. But it is out of scope for this answer.


Given your form fields use appropriate names (i.e. field names match state properties), and you don't mind using a single state object you can create a single change handler that merges in each field update (similar to how a class-based component's this.setState would handle it) using the field name as the key.
const FormInvite = (props) => {
  const [state, setState] = useState({
    firstName: '',
    lastName: '',
    country: '',
    email: '',
  });

  const changeHandler = e => {
    const { name, value} = e.target;
    setState(state => ({ ...state, [name]: value }));
  }
  ...

const rootElement = document.getElementById("root");

const FormInvite = props => {
  const [state, setState] = React.useState({
    firstName: "",
    lastName: "",
    country: "",
    email: ""
  });

  const changeHandler = e => {
    const { name, value } = e.target;
    setState(state => ({ ...state, [name]: value }));
  };

  React.useEffect(() => {
    console.log('firstname changed', state.firstName);
  }, [state.firstName]);
  React.useEffect(() => {
    console.log('lastname changed', state.lastName);
  }, [state.lastName]);
  React.useEffect(() => {
    console.log('country changed', state.country);
  }, [state.country]);
  React.useEffect(() => {
    console.log('email changed', state.email);
  }, [state.email]);

  return (
    <form>

        First
        <input
          type="text"
          value={state.firstName}
          name="firstName"
          onChange={changeHandler}
        />

        Last
        <input
          type="text"
          value={state.lastName}
          name="lastName"
          onChange={changeHandler}
        />

        Country
        <input
          type="text"
          value={state.country}
          name="country"
          onChange={changeHandler}
        />

        email
        <input
          type="email"
          value={state.email}
          name="email"
          onChange={changeHandler}
        />

    </form>
  );
};

ReactDOM.render(
  <React.StrictMode>
    <FormInvite />
  </React.StrictMode>,
  rootElement
);
input {
  width: 3rem;
}

NOTE: This uses a functional state update to ensure/preserve previous state values that aren't currently being updated.
Alternatively you can create a mapping of state => setState function and use a similar change handler as before, this time though you won't need to merge in updates manually.
const FormInvite = props => {
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const [country, setCountry] = React.useState("");
  const [email, setEmail] = React.useState("");

  const fieldSetStateMap = {
    firstName: setFirstName,
    lastName: setLastName,
    country: setCountry,
    email: setEmail
  };

  const changeHandler = e => {
    const { name, value } = e.target;
    fieldSetStateMap[name](value);
  };
  ...

const rootElement = document.getElementById("root");

const FormInvite = props => {
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const [country, setCountry] = React.useState("");
  const [email, setEmail] = React.useState("");

  const fieldSetStateMap = {
    firstName: setFirstName,
    lastName: setLastName,
    country: setCountry,
    email: setEmail
  };

  const changeHandler = e => {
    const { name, value } = e.target;
    fieldSetStateMap[name](value);
  };

  React.useEffect(() => {
    console.log("firstname changed", firstName);
  }, [firstName]);
  React.useEffect(() => {
    console.log("lastname changed", lastName);
  }, [lastName]);
  React.useEffect(() => {
    console.log("country changed", country);
  }, [country]);
  React.useEffect(() => {
    console.log("email changed", email);
  }, [email]);

  return (
    <form>

        First
        <input
          type="text"
          value={firstName}
          name="firstName"
          onChange={changeHandler}
        />

        Last
        <input
          type="text"
          value={lastName}
          name="lastName"
          onChange={changeHandler}
        />

        Country
        <input
          type="text"
          value={country}
          name="country"
          onChange={changeHandler}
        />

        email
        <input
          type="email"
          value={email}
          name="email"
          onChange={changeHandler}
        />

    </form>
  );
};

ReactDOM.render(
  <React.StrictMode>
    <FormInvite />
  </React.StrictMode>,
  rootElement
);
input {
  width: 3rem;
}

NOTE: This can use a plain state update as each "piece of state" is fully independent of other state and the value is replaced each onChange.


import math, sys, os

TOLERANCE = 0.00001

class SizeError(Exception):
    def __init__(self, *args):
        self.args = args
        print "Size Error between " + str(args)

You shouldn't print in an exception constructor. At most, you should define a __repr__ for printing purposes. But you can probably get away with not doing that and trusting the default.

class P(object):

The name doesn't give me much clue as to what this class is.

    def __init__(self, *args):
        if len(args) == 1:
            try:
                self.components = tuple(args[0])
                self.size = len(args[0])
            except TypeError:
                self.components = tuple(args)
                self.size = len(args)
        else:
            self.components = args
            self.size = len(args)

Instead of assigning size three times, use self.size = len(self.components) at the end. In fact, consider not storing the size at all and just looking at the size of the components. I'd also suggest not accepting three different ways of passing in the parameters. Pick one and make it be used everywhere.

    def __getitem__(self, key):
        return self.components[key]
    def __repr__(self):
        result = ""
        for i in range(0, self.size):
            result += str(self[i]) + ", "

Add strings is expensive. But python has a really nice join function. So you could do:

result = ",".join(map(str,self))

And it'll actually take care of everything else for you

        return "<Point (" + str(self.size) + ") : "  + result[:-2] + ">"
    def __eq__(self, other):
        if self.size != other.size:
            raise SizeError(self, other)
        for i in range(0, self.size):

You don't need the zero.

            result = self[i] - other[i]
            if math.fabs(result) > TOLERANCE:

I'd combine those two lines

                return False
        return True
    def __add__(self, other):
        if other.size != self.size:
            raise SizeError(self, other)
        result = []
        for i in range(0, self.size):
            result.append(self[i] + other[i])

Use zip, and it'll be a bit faster to use a list comprehension:

result = [x+y for x, y in zip(self, other)]

        return P(result)
    def __sub__(self, other):
        if other.size != self.size:
            raise SizeError(self, other)
        result = []
        for i in range(0, self.size):
            result.append(self[i] - other[i])
        return V(result)

class V(P):

I wouldn't have vector inherit from point. I'd have them both inherit from some other more generic class. A vector is not a point, coding like it is one could be confusing.

    def dotProduct(self, other):

Python convention is to have names which are lowercase_with_underscores for methods.

        result = 0
        if self.size != other.size:
            raise SizeError(self, other)
        for i in range(0, self.size):
            result += self[i] * other[i]
        return result

Here I'd use

return sum(x * y for x, y in zip(self, other))

    def normalize(self):
        result = []
        length = self.getLength()
        if math.fabs(length) < TOLERANCE: return self.getZero()
        for i in range(0, self.size):
            result.append(self[i] / length)
        return V(result)
    def getLength(self):
        result = 0
        for i in range(0, self.size):
            result += self[i]**2
        return math.sqrt(result)

    def getZero(self):
        return self * 0
    def isZero(self):
        zero = self.getZero()
        return self == zero

Both of these will be inefficent implementations. They should work, but they'll be relatively slow. The fact being any Point/Vector class implemented in python will be unforgivably slow. That's why we typically implement such things in extensions like numpy.


Find sum of all the subarrays of an array

First I would suggest to separate I/O from the computation,
and define a function to compute the subarray sum. That increases
the clarity of the program and allows to add test cases more easily:

def subarray_sum(a):
    """Compute sum of all subarrays of a, multiplied by its last element"""
    n = len(a)
    total = 0
    for i in range(1, n + 1):
        for j in range(n + 1 - i):
            temp = a[j:j + i]
            total += sum(temp) * temp[-1]
    return total

Using sum() with generator expressions this can be shortened to

def subarray_sum(a):
    n = len(a)
    total = sum(sum(sum(a[i:j + 1]) * a[j] for j in range(i, n))
                for i in range(n))
    return total

But the time complexity is still \$ O(n^3) \$ because of the three nested
loops.

In order to find a more efficient method, let's compute the sum for a 3-element
array \$ [a, b, c] \$ explicitly:

$$
 a \cdot a + b \cdot b + c \cdot c \\
 + (a+b)\cdot b + (b+c) \cdot c \\
 + (a+b+c) \cdot c
$$
Rearranging terms, this becomes
$$
 a \cdot a + (a + 2b) \cdot b + (a + 2b + 3c) \cdot c
$$
Can you spot the pattern? This can be computed with a single
traversal of the array, i.e.  in \$ O(n) \$ time.


Number to german decimal format converter function

For formatting currency, given that there are many desired formats, the easiest and most readable way is to just make a function called formatCurrency() that might look something like this:

function formatCurrency(amount, symbol, groupDigits, preFixed, exchangeCommas){
    var result = amount.toFixed(2);
    if(groupDigits){
        result = result.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    if(prefixed){
        result = symbol + result;
    }else{
        result = result + symbol;
    }
    if(exchangeCommas){
        var decimalIndex = result.lastIndexOf(".");
        result = result.replace(",", ".");
        result = result.substring(0, decimalIndex) + "," + result.substring(decimalIndex + 1);
    }
    return result;
}

https://stackoverflow.com/questions/14467433/currency-formatting-in-javascript

Edit: Note that the parameters groupDigits, preFixed and exchangeCommas are optional boolean values.

Then if you want to make it shorter or less readable for whatever reason there are online tools that make it easy to do so, such as yui compressor.


Manage input values from file according to number of elements per line

You can simplify your loops logic like this

while (getline(inFile, inLine)) {
    std::istringstream inStream(inLine);

    anObject inObj;
    if((inStream >> inObj.one) && (inStream >> inObj.two)) {
        objList.push_back(inObj);
    }
    else {
        myVar = inObj.one;
    }
}

relying on exactly that form of input you mentioned is given.

std::ios::in is redundant for std::ifstream:

inFile.open("myFile.txt", std::ios::in);
                     // ^^^^^^^^^^^^^^

also open() isn't explicitely needed. You can simply write:

std::ifstream inFile("myFile.txt");

class anObject
{
public:
    int one;
    int two;
};

can be simpler written as struct:

struct anObject
{
    int one;
    int two;
};


ArrayBlockingQueue: concurrent put and take

Typo

In your take() function, you wrote this:

            notFull.signal();

But I'm pretty sure you meant to write this:

            notEmpty.signal();

Unnecessary Signalling? Nope

Originally, I thought that the extra signalling in the add() and take() functions were unnecessary.  In fact, they are not required, but when they are added, it improves performance.  It is a concept called "cascading notifies".  The LinkedBlockingQueue sources  explain it like this:

  Also, to minimize need for puts to get takeLock and vice-versa, cascading notifies are used. When a put notices that it has enabled at least one take, it signals taker. That taker in turn signals others if more items have been entered since the signal. And symmetrically for takes signalling puts.

Race condition? Nope

Originally, I thought that the code had a race condition involving memory reordering when accessing the shared queue.  However, it was pointed out that AtomicInteger acts as a volatile variable and provides a memory barrier.  So therefore the accesses are safe.

Update

After reading @rolfl's answer with his multiple variants that attempt to improve upon the original function, I was inspired to come up with my own variant.  I came up with one that is simpler than any of the variants listed here so far.  It basically uses two semaphores, normal synchronization, and an array:

import java.util.concurrent.Semaphore;

public class ArrayBlockingSemQueue<T> implements BlockQueue<T>
{
    private final int capacity;
    private final Semaphore notEmpty;
    private final Semaphore notFull;
    private final Object [] items;
    int takeIndex;
    int putIndex;

    public ArrayBlockingSemQueue(int capacity) {
        this.capacity = capacity;
        notEmpty = new Semaphore(0);
        notFull  = new Semaphore(capacity);
        items = new Object[capacity];
    }

    public void add(T t) throws InterruptedException {
        notFull.acquire();

        synchronized(notFull) {
            items[putIndex++] = t;
            if (putIndex == capacity)
                putIndex = 0;
        }

        notEmpty.release();
    }

    @SuppressWarnings("unchecked")
    public T take() throws InterruptedException {
        T ret;

        notEmpty.acquire();

        synchronized(notEmpty) {
            ret = (T) items[takeIndex++];
            if (takeIndex == capacity)
                takeIndex = 0;
        }

        notFull.release();
        return ret;
    }
}

Benchmarks

I used the same code that @rolfl listed in his answer to test the timings of the various Queues.  Here are my results:

           1x1   2x2   3x3   4x4   6x6   12x12 1x12  2x6   3x4   4x3   6x2   12x1
Veritas    3.32  3.39  3.54  3.59  3.54  3.62  6.63  3.95  3.67  3.68  3.88  6.16
DoubleSync 3.72  4.97  4.87  4.94  5.07  4.78  5.43  5.01  4.96  4.93  5.01  5.41
CDLatch    2.89  2.56  4.62  5.02  5.83  8.01  8.25  5.95  5.24  3.60  2.58  2.65
JS1        3.05  3.00  3.18  3.08  3.04  3.09  3.47  3.13  3.26  3.07  3.00  3.15


A couple of minor things:

First of all the convention in the ruby world is to use 2 spaces for indentation, not 4. It doesn't really matter much, but it's generally easier to use the style conventions that everyone uses unless you have a reason not to.

range = (0..10)

You don't actually need the parentheses here. Parentheses are not part of range syntax - the reason you usually see ranges wrapped in parentheses is that you can't call methods on ranges without them (because 0..10.foo would be interpreter as 0..(10.foo)).

to_guess = range.min + rand(range.max - range.min)

You should use begin and end or first and last instead of min and max. In ruby 1.8.7 min and max are inherited from Enumerable and will iterate the entire range in order to find the minimum/maximum, making them O(n). Only in 1.9 (in 1.9.2 at least) they're overridden to work in O(1) time. begin and end work in O(1) time in all ruby versions.

I would also consider putting this into its own method as it seems like it might come in handy more than once.

while !guessed

I would write that as until guessed as that reads a bit nicer to me.


I'm not sure what this program is trying to do, but I can give a few suggestions for style and improvements.

Firstly, unless you're not using the python command to run this script on the command line, you don't need the #!/usr/bin/python.
Secondly, I'd separate the imports out on each separate line like so.

import cgi
import cgitb
import json

This is in case an error occurs with the imports, if thats the case, the error will be easier to find.
After that I'd separate certain things into functions and add docstrings. A few things I might want to separate into functions is opening the file, updating the like values, and writing to the JSON file. This gives your program a bit of re-usability.
My final bit of advice would be to remove or improve un-needed comments such as the following.

# Create instance of FieldStorage
# Open a file
# Import modules for CGI handling

I'd also recommend checking out Python's style guide, PEP8. Hope this helps!


Stripping formatting from text - Am I using an efficient jQuery selector?

I struggled with the same issue in the past, and decided to simply use a disposable DOM element to convert the HTML to plaintext:

var message = "..."; // Contains HTML markup
var tmp = document.createElement("DIV");
tmp.innerHTML = message;
var message = tmp.textContent||tmp.innerText;
// message now contains plaintext, and tmp can be disposed of

With this approach, we still needed to allow the user to enter a single tag. For this, we simply implemented a microformat where the user enters "placeholders" with bracket symbols:

  Hello [[person]], having a good day?

Since this is just plain text, it will not be removed by the above conversion process, and can simply be replaced with the appropriate HTML tags:

message.replace('/\[\[person\]\]/g', 'some name');


I wanted some of the time-saving functionality of jQuery without the bulk of the entire library.

If you don't look back at older browsers, use version 2.x of jQuery. It's smaller than the 1.x as it has less cross-browser compatibility code (See How 2.0 Changed section). You can also custom-build jQuery to your own spec to include what you need. An even smaller yet jQuery-compatible library is Zepto, just ~9k compressed.

  Element Retrieval

Pretty straightforward. However, there is querySelectorAll which pretty much acts like jQuery's $. A singular version of it is querySelector. It's native, and has been there for quite a while.

One neat thing about jQuery and jQuery-like libraries is that they encapsulate results, single or multiple, into a set. Methods operate by looping through and applying to each item in the set. No items, no loop, thus no throw.

$('#foo').children().eq().next().remove();

The following example will not throw an error even when there's no #foo in the page.

  Element Creation

var h = $make('a', {
    'class': 'myClass',
    'text': 'Google',
    '@id': 'googleLink',
    '@href': 'https://google.com',
    '@target': '_blank'
});

Not entirely sure what's the difference between class and the other attributes when it's also an attribute. What should be different is text since it doesn't actually describe the element. Also, text nodes can be created separately via createTextNode.

  Element Sibling Insertion

if (t.startsWith('#')) {
  $get(t).parentNode.insertBefore(e, $get(t));
} else {
  var arr = $get(t);
  for (var i in arr) {
    var f = e.cloneNode(true);
    arr[i].parentNode.insertBefore(f, arr[i]);
  }
}

This is one case where your code will start to become unmaintainable. This function is making a special case for singular results. If you go with the set-like behavior of jQuery, singular results are still a set. Your code will always assume a set and be more consistent in operation.

  Element Removal

function $remove(e) {
    if (typeof e === 'string' || e instanceof String) {
        $remove($get(e));
    } else if (e.nodeType === 1 || e.nodeType === 3) {
        e.parentNode.removeChild(e);
    } else {
        for (var i in e) {
            e[i].parentNode.removeChild(e[i]);
        }
    }
}

Again, your code is doing special cases for different things. This could have been easier if you operated with a set of things.

function $remove(input){

  // Building the set
  var set = inputIsAString ? lookForElements(input)
          : inputIsAnElement ? createASet(input)
          : inputIsAlreadyASet ? input
          : [];

  // The actual operation
  set.forEach(function(){
    // element removal code
  });
}


As this works for you and as there is no javascript interpreter in PHP unless you install it (there is a V8 PHP extension IIRC), I would say you did this right so far.

Which else criteria could there be than your own ones? You should probably write unit and acceptance tests for it. And remove the var_dump debug cruft out of it. But by the way you do this on it's own, it does not look too far off.


Your main questions

  The application is divided into four scripts that have a single task each. This is inspired by how Git is organized. Is this a good way to isolate independent code in bash?

If the scripts are short, it's simpler to have all the code in one script, with each main functionality in its own function.

If the scripts are longer, and you suspect that they will get longer and longer, then it makes sense to keep them as separate scripts in a dedicated directory. However, in this case, if the scripts need to call each other, then you need a way so that they can find each other. A simple way is to add the directory of the scripts to PATH. Another simple way is to require that users must cd into the directory of the scripts of they want to use them.

Since you launch another script using the ./ prefix, that will only work if the other script is in the current directory.

  How should I handle shared code between scripts? I've use two different approaches below: I created a standalone script that the others call for determining the database name, and I copy-pasted the die function. I've heard of script sourcing, but I've never seen that used for creating bash "libraries".

Yes, script sourcing is more common. Another benefit of that will be that you can define your common functions in one place, no need to copy-paste die into every script that needs it.

Something I often do is cd to the directory of the script, and then source the common configuration and function definitions, like this:

cd $(dirname "$0")
. ./config.sh
. ./functions.sh

Function definitions

The convention is to put parentheses in function definitions, and to omit the " function " keyword, like this:

die() {
    echo "$1" >&2
    exit 1
}

Benefit from program exit codes

You can benefit from the exit codes of programs more aggressively. For example instead of this:

if [ $(echo "$1" | grep ":" | wc -l) -gt 0 ]; then

It's better to write this way:

if echo $1 | grep -q :; then

There are several things going on here:

I omitted the quoting of $1, because for the purpose here, it doesn't matter
grep exits with success if a pattern is found
The -q flag makes grep output nothing, but that of course doesn't change the fact of success or not, it's just too avoid garbage output
The statement has been radically changed. Instead of comparing the output of the wc command, we are operating based on exit codes. There is no more [ ... ]

We can do even better. Instead of echo, we can use "here strings" to cut out one more process:

if grep -q : <<< "$1"; then

But the best is to use pattern matching with [[:

if [[ $1 = *:* ]]; then

Use the principle about exit codes to rewrite the rest of your code and the other scripts.

Exit with non zero on error

In many places you exit with code 1 to signal an error but not here:

if [ $(echo "$1" | grep ":" | wc -l) -gt 0 ]; then
   exit 0

It would be better to echo a friendly message, and then exit with 1.

Safety

This part is a bit scary:

if [ $# -eq 1 ]; then
    rm "$file"
fi

Within the same script, file is sometimes a temporary file, sometimes it's the actual database. This can be confusing. It's easy to make mistakes in shell scripting, and with one simple mistake, your database might go up in smoke. I suggest to reorganize your code: move this dangerous operation closer to the code that creates the temp file. In addition, refer to the temp file by a different name, and use that name in the rm command. In other words, make it really hard to mistakenly delete the wrong file.


Validate optional input parameters with if(!empty)

I am very concerned about all the mangling that you are doing with addslashes(trim(strip_tags(…))) and addslashes(htmlentities(…)).  It's almost certainly wrong, but I can't tell you what would be right without knowing exactly how those variables get used.


Implementing multiprocessing to compare large number of entries in a python dictionary

I just figured out that I could have simply used a dictionary nested inside a dictionary instead of a list nested inside a dictionary. Now the script finishes within minutes for each sample.


I'm not sure what Class1 is for, but you can weave 2 lists together using a list comprehension to build the first part of the list.  Then add on the rest of the longer list.  Like so:

def weave2(seq1, seq2):
    result = [item for pair in zip(seq1, seq2) for item in pair]

    if len(seq1) < len(seq2):
        result += seq2[len(seq1):]
    else:
        result += seq1[len(seq2):]

    return result

To weave more than two lists, weave the first two together, then weave in the third list, and so on.  Like so:

def weave(*args):
    args = iter(args)
    result = next(args)

    for arg in args:
        result = weave2(result, arg)

    return result


I would rather do smth. like that (I added CancellationToken in case you would want to be able to cancel email parsing while it's in progress):

private static TimeSpan timeToWait = TimeSpan.FromSeconds(30);

//somewhere in your code:
_cancellationTokenSource = new CancellationTokenSource();

private static void Main(string[] args)
{
    CancellationToken token = _cancellationTokenSource.Token;
    do
    {
        try
        {
            ProcessEmailsAndWaitAsync(token).Wait();
        }
        catch (Exception e)
        {
            Debug.WriteLine("
Error in Client

Exception

" + e.Message + "

" + e.StackTrace + "
 ");
        }
    } while (!token.IsCancellationRequested);
}

private static async Task ProcessEmailsAndWaitAsync(CancellationToken token)
{
    await ProcessMailMessages(token);
    await Task.Delay(timeToWait, token);
}

private static async Task ProcessMailMessages(CancellationToken token)
{
    //...............................................................................
}


Enums with different methods, useful or abuse?

My answer to your main question is you gotta do what you gotta do. Just so you feel more comfortable; this pattern has a name strategy enum. It is even in Effective Java.

But I have a criticism for this bit:

    public static final TextType[] useCase1 = {text1, text2};

Arrays are mutable. You should not implement class constants as final arrays. Use unmodifiable collections instead:

    public static final List<TextType> useCase1 = Collections.unmodifiableList(
         Arrays.asList(text1, text2));

Also each time you add another use case you should not need to modify this enum, that is by adding another useCase. Those should be moved to wherever they are used.


Class to represent a mutable date and time

I guess I am not really seeing what value this class adds above and beyond what DateTime and related classes give to you "out of the box".

If you need a method or two to perhaps format a date in some specific way to be compatible with Amazon, then perhaps you could extend the base DateTime class with these methods.

Even then, I still question the value of introducing a whole class to, in essence, do these sorts of trivial things:

$datetime = new DateTime();
$datetime->modify('-1 month');
$datetime->modify('-10 days');
$amazonFormat = $datetime->format('c');

It is odd how you are working with PHP's procedural date functions interchangeably with DateTime.

For example in your constructor you write this:

public function __construct()
{
    date_default_timezone_set('America/Chicago');
    $date = new DateTime(date('Y/m/d H:i:s'));
    $this->setDate($date);
}

Which if you truly wanted to use DateTime might look like this:

public function __construct()
{
    $datetime = new DateTime('now', new DateTimeZone('America/Chicago'));
    $this->setDate($date);
}

There is no reason to change your system's default timezone on the fly if you just need to apply a timezone to one specific DateTime object. Right now your code could actually severely break other code in your system that follows instantiation of one of these objects, in that you have munged with default setting for all code that follows in script execution.  If the default setting on the server were for a different time zone,  all code execution up to the point of instantiation would operate in that timezone, while all code after would operate in America/Chicago.

If you truly are trying to set this as your default timezone for your entire application, this function call should be made somewhere in your bootstrapping process.

If this truly is a class-level setting, should the America/Chicago (or similar) value be passed to the constructor, or be a class constant? Right now you are "hiding" this setting inside method logic, which is a bad idea.

Why even have your currentDate() method?  It exactly the same as the constructor logic.

Your method names seem odd and could potentially cause confusion.  get/setDate() are really getting/setting DateTime objects which is not clear from the method names.  Your setDate() has an additional problem in that it does not enforce that a DateTime object be passed via type hinting, so some confused developer could pass a string or some other value to this method and put your object in a bad state.

You have the general problem throughout your public methods in that you are not enforcing data types for parameters at all.  This is typically achieved either through type-hinting (if applicable) or through validation within the method if type-hinting is not available for a given data type (which will vary based on version of PHP you are designing against).


how to efficiently draw line numbers in edittext ondraw without causing lag in scrolling

// I use short variable names because i think
// they are executed
much faster.

You are wrong. Execution speed does not depend on the length of identifiers anyhow.

// i use an array here for efficient
// random access to store the
// positions where the line numbers
// will be according to the number
// of lines

As usual the use of (primitive) arrays leads to procedural solution involving al lot of looping. Unnecessary looping is the most common performance issue.

   // now i loop thru all the numbers
   // replacing the characters in the array
   // (with spaces) with numbers

Instead of looping you should calculate what you need.
Because of your poor naming I'm not analyzing in detail what your code really does, but it looks like in mainly calculates the indentation needed.
Given the number of the current line and the overall line count I would do it this way:
 // this could also be a member variable
 // so that it does not need to be
 // calculated each time the draw method runs
 int indentedNumberWith =
           String.valueOf(lineCount).length();

 String indentedLineNumber =
           String.format(
                         "% "+indentedNumberWith+"s",
              // note this ^ space
                         String.valueOf(lineNumber));

This should replace the loop with the if cascade...


Computing the distance and weight matrix of a graph

Here is how you would do it with no for loops. The dist() function computes the distance between every pair of rows of a matrix. So you have to apply it to two matrices:

the matrix C where each row contains the i and j coordinates of each vertex.
the matrix matrix(M, ncol = 1) where each row contains the value at a vertex.

M <- t(mat)
C <- cbind(c(row(M)), c(col(M)))
D <- as.matrix(dist(C, method = "euclidean"))
E <- as.numeric(D <= R)
G <- as.matrix(dist(matrix(M, ncol = 1), method = "manhattan"))
B <- E * ((a * G) ^ 2 + (b * D) ^ 2) ^ (1 / 2)

Note that in R, matrices are stored using "Column Major", i.e. column by column. So it would be more natural to pick that the second row/col in B corresponds to the item at row 2 and col 1 in mat. You chose the opposite (row 1 col 2) which forced me to start my code with M <- t(mat). If you want to pick the more natural approach as I suggest, just replace that first line with M <- mat.


Better method structure for insertion in doubly linked list

if(head == null)
    {
        head = newNode;
        tail = newNode;
    }
    else
    {
        currentNode.next = newNode;
        newNode.prev = currentNode;
        tail = newNode;
    }

hmmm

    if(head == null)
    {
        head = newNode;
    }
    else
    {
        currentNode.next = newNode;
        newNode.prev = currentNode;
    }
    tail = newNode;

Yep, that's shorter.

Okay, and now a more serious answer:

A LinkedList, no matter if it's doubly linked or not, always is gonna require two things for insertAt: The object to insert, and some means of specifying where it goes. There's no way to circumvent this. Best you can do is take a Node (or Link, in your case) and give it an insertAfter method.

Oh yeah, back to your code example:

LinkedList list = new LinkedList();
Link link1 = new Link("A");
list.insert(list.head,link1);
Link link2 = new Link("B");
Link link3 = new Link("C");
list.insert(link2, link3);
list.insert(link1, link2);
list.display_List_Start_From_Head();

You have some serious bugs in there.

This should work fine, of course, but try iterating it backwards; you won't get the correct elements back.

Here's another way your list blows up:

LinkedList list = new LinkedList();
Link link1 = new Link("A");
list.insert(list.head,link1);
Link link2 = new Link("B");
list.insert(link1, null);//NullPointerException
list.insert(link1, link2);//If it didn't crash just now, this will clear the list and leave link2 as head


Singly linked list abstraction in ES5 JavaScript

You don't need to track the end of the list. You can just check that you've reached it if an element's next is null.

makeNode doesn't do anything. Every time you use it you set data instantly after, so data should be a parameter. Setting next to null isn't that useful because if you don't change it you can simply check node.next === undefined and get the same thing, while using less memory.

Try

function MakeNode(data) {
  return { data: data };
}

In general it's not that useful to separate the node and list abstractions. If you want a list just pass around the first node of the list. It makes many algorithms much simpler to read and write.

I'd start with

function Node(data, next) {
  this.data = data;
  this.next = next;
}

This sets next to undefined if you just do new Node(5).


That is not really exception handling:

In your main() method:

You are branching on three different types of exceptions, but your action is the same: Print a message.
Doing so is fine, but the point for different catch blocks is not obvious to me.
Anyway:

Use std::cerr instead of std::cout for errors.
return 1 (or any value different from 0) if your program fails.

In runAlgorithm()

Generally you should only catch exceptions you want to handle.
And printing a message is not really handling an exception, that is more like cheap debugging.

You are catching the MyOtherException exception and ignoring it.
Why? Is it irrelevant to the algorithm? If so, why print a message? If not, why continue the algorithm? You might want to move the catch block out of the loop if it is fatal, or possibly remove it at all if you can't deal with it.

As a rule of thumb: Only catch an exception if

you can do something about it, this might be trying a different way to achieve the goal of your function
you want to wrap it inside a more appropriate exception, for example you could catch a low level io exception and wrap it in a parse exception explaining in more detail what went wrong
it is irrelevant to the calling function
it is the main method. C++ behaves ugly on uncaught exceptions.
But you should probably return 1 instead of 0.


notes:

Your coding style seems good. There is some inconsistent indentation,
but i am guessing that is a question formatting problem.
Having a static variable word means that palindrome is not
threadsafe, and is confusing to call. either pass word to the
palindrome constructor, or make checkPalindrome() a static method
that takes a string.
checkPalindrome() outputs it's result to standard output. What if
you wanted to make your palindrome checker graphical?. have
checkPalindrome() return a boolean indicating whether word is a
palindrome or not. This concept of seperating model and output code
is extremly important.
Instead of wasting time and memory copy over the string backwards then
checking for equality, you can compare pairs of characters starting at
both ends of the string.
When you reverse the string, you can write a for loop that goes
backwards:

for (int i = word.length() - 1; i >= 0; --i) {
    reversedChar = word.charAt(i);
    reversedWord.append(reversedChar);
}

example:

public boolean checkPalindrome(String word) {
    for (int i = 0; i < word.length() / 2; ++i) {
        if (Character.toLowerCase(word.charAt(i)) !=
                Character.toLowerCase(word.charAt(word.length()-i-1))) {
            return false;
        }
        return true;
}


Finding common elements, ignoring duplicates, in two given string arrays

There is one major flaw in your code: Testing strings for value
equality must be done with .equals() not with ==.
For example, for

commonTwo(new String[]{new String("a"),"b","c"},
          new String[]{"a","b","c"})

your code returns 2 instead of 3.
(Compare How do I compare strings in Java?.)

Your computation of the larger/shorter array can be simplified to

shortArray = a.length < b.length ? a : b;
longArray = a.length >= b.length ? a : b;

But actually your code does not take advantage of the fact that one array is shorter than the other, so you might as well loop over a
and b directly.

Your letterToAvoid idea works (almost) to skip duplicate elements, but I would call the variable differently, perhaps lastDuplicate.
And you could early-return from the inner loop if a duplicate is found.
Your idea does not work if the string arrays contain empty strings
as well which should also be counted.

Your solution is not efficient. It does not take advantage of the
fact that both arrays are sorted. Instead of a nested loop you
can perform a parallel single iteration over both arrays:

If current left element is smaller than current right element,
advance left position by one.
If current right element is smaller, advance right position.
If current left and right elements are equal, we have found
a duplicate. Skip following equal elements in both arrays.

Possible implementation:

public int commonTwo(String[] a, String[] b){

    int count = 0;

    int i = 0;  // Index into a
    int j = 0;  // Index into b

    while (i < a.length && j < b.length) {
        int cmp = a[i].compareTo(b[j]);
        if (cmp < 0) {
            // a[i] is smaller
            i++;
        } else if (cmp > 0) {
            // b[j] is smaller
            j++;
        } else {
            // a[i] == b[j]
            // Increment count and skip duplicates
            count++;
            String lastDuplicate = a[i];
            i++;
            j++;
            while (i < a.length && a[i].equals(lastDuplicate)) { i++; }
            while (j < b.length && b[j].equals(lastDuplicate)) { j++; }
        }
    }

    return count;
}


I don't see how this runs asynchronously. callback(_status); will still only be called after all processing is finished, parallel or not. In this case this makes the callback rather redundant, as it does the same as a simple return value.

If you want to make it asynchronous you'll need to store the callback as a member variable, but return immediately in CheckRange. Start the actual processing on a separate thread by e.g. using a BackgroundWorker. Once this execution completes, you can call the stored callback with the result.


Use properties of prime numbers

The only prime number that is even is 2, for the simple reason that if the number is even, it is evenly divisible by 2 and is thus not a prime.

So after checking if 2 is a factor and removing it, simply start with div = 3  and in the update do div = div + 2. And you're twice as fast!

But there is more, consider \$x=6k+l\$ where \$l\in\left[0,5\right]\in \mathcal{Z}\$ and \$k\ge 0\$. It's obvious \$x\$ can represent any positive integer.

Assume for a second that \$k>0\$ and lets look a bit closer:

\$x=6k+0\$  is always be divisible by 2 and 3.
\$x=6k+1\$ This might be a prime (7, 13 for example are primes).
\$x=6k+2=2\cdot (3k+1)\$ is always divisible by 2.
\$x=6k+3=3\cdot (2k+1)\$ is always divisible by 3.
\$x=6k+4=2\cdot(3k+2)\$  is always divisible by 2.
\$x=6k+5\$ This might be a prime (11, 19 for example are primes).

Now note that \$6k+5 = 6\left(k+1\right)-1\$ so after checking the divisors we would miss at the start (2 and 3) set div=6 and try division with div-1 and div+1 then increase div by six and repeat.

This means that you're skipping 2/3rds of all divisors, i.e. ~300% faster.

Your exit condition for the loop is useless

As the input is guaranteed larger than zero, number!=0 will always be true in your loop condition. In fact you can reduce branching even further like this:

while(number!=1){
    while(number % div == 0){
        number = number / div;
        maxFact = div;
    }
    div = div + 1;
}
printf("%lld\n",maxFact);
ans = 1;

that's one branch less per iteration.


map vs if

var map = fn => res => x => fn(x) ? res : null

I would rename this to something more like ifThen or when -- calling this function map is confusing, to me at least, given the normal usage of map. This is an if where the else is always null.

In a larger program you may find that providing the true/false results as functions instead of constants would be more powerful, but here that would just add noise.

const

Most of your vars could be consts. Doesn't make much difference here but since you're deliberately being functional const would help declare your intent.

without mapDividedBy

I don't think you need this specialized function. Just pass the predicate and true-result into your when/if:

const when = pred => trueRes => x => pred(x) ? trueRes : null
const isDividedBy = dividend => divisor => divisor % dividend === 0
const mappers = [
  when(isDividedBy(3))('Fizz'),
  when(isDividedBy(5))('Buzz'),
]

naming

I'm not sure mappers is the most descriptive name. I can't think of anything better at present, so that's not very helpful, but any (pure) function is just a "mapper" from inputs to output(s). Maybe tests? Hmm.

In any event, since this is a FizzBuzz I suggest providing a final function named as such, for convenience and readability:

const fizzbuzz = applyMappers(mappers)
const result = Array.from(range(1, 100)).map(fizzbuzz)

misc

I like your currying approach.

Clojure has a function juxt which does the same thing as mappers.map(fn => fn(x)) but looks a little cleaner, being a separate function:

const fizzbuzz = x => juxt(mappers)(x).join('') || x

But whether this is more readable or more obscure depends on whether you know Clojure, so I've left this point to the end.


Integer seconds to formated string mm:ss

Your code looks functional, and, if this was for early versions of Java, it would be quite typical and standard.

The String.format process can do so much more than what you are using it for, though.

Your function:

private String secondsToString(int pTime) {
    final int min = pTime/60;
    final int sec = pTime-(min*60);

    final String strMin = placeZeroIfNeede(min);
    final String strSec = placeZeroIfNeede(sec);
    return String.format("%s:%s",strMin,strSec);
}

can be simplified drastically by using more of the String.format functionality:

private String secondsToString(int pTime) {
    return String.format("%02d:%02d", pTime / 60, pTime % 60);
}

The %02d means: "Format as a decimal number using at least 2 digits, and pad with 0 if less than 2 digits"

Note, that using the modulo 60 pTime % 60 gets the remainder of seconds when dividing by 60. This is  short hand for pTime - (ptime / 60) * 60


Bank transaction implementation - side-effects of barriers

In moneyTransferCTX:

You are using pointers. As you never expect these to be NULL (and they can't be changed) you should be using references.

The constructor is casting objects to things that are not necessarily valid.

moneyTransferCTX(IsourceAccount *src, IdestAccount *dst):
  // Cast the objects (src,dst) to their roles (sourceAccount, destAccount).
  sourceAccount(static_cast<decltype(sourceAccount)>(src)),
  destAccount(static_cast<decltype(destAccount)>(dst))
{}

Just because a src is an IsourceAccount does not mean it is also sourceAccount so casting it may not be valid. But it looks like what you are trying was to create a wrapper class (like this):

class sourceAccount
{
  IsourceAccount&  account;
  public:
    sourceAccount(IsourceAccount &acc): account(acc) {}
    void transferTo(moneyTransferCTX& ctx, int amount)
    {
        if (account.availableBalance() < amount) throw -1;
        account.withdraw(amount);

        ctx.destAccount->receive(ctx, amount);
    }
}  sourceAccount;

Personally I think this is overkill and you should just put the work you were putting in these classes into the execute method.

I would do this:

// How the Model objects interact
class moneyTransferCTX
{
  IsourceAccount& sourceAccount;
  IdestAccount&   destAccount;

public:
  moneyTransferCTX(IsourceAccount& src, IdestAccount& dst)
    : sourceAccount(src)
    , destAccount(dst)
  {}

  void execute(int amount)
  {
    if (sourceAccount.availableBalance() < amount) throw -1;
    sourceAccount.withdraw(amount);
    destAccount.deposit(amount);
  }
};

Creating dynamic objects should not be done if not required.

Account2 *savings = new Account2();
Account *checking = new Account(); //Changing the class type shouldn't hurt the code.

It is easier to create normal objects (then you don't have to delete them). If you must create them then you should wrap their usage in a shared pointer.

Account2 savings;
Account  checking; //Changing the class type shouldn't hurt the code.

Learn to use the C++ streams (It provides type safety):

printf("Opening Status- Savings: %d, Checking: %d\n",
       savings->availableBalance(),
       checking->availableBalance());

//

std::cout << "Opening Status- Savings: " << savings->availableBalance()
          << ", Checking: " << checking->availableBalance()
          << "\n";

Your use of exceptions is on the edge of being acceptable. Some people will say it is OK others will say it is in-appropriate. Personally I could go either way depending on what the application is doing. What you should keep in mind that exceptions are used to transfer control when an error occurs but should not normally by used for control flow. Error codes/status can be good internally, but don't leak them outside your interface.

The other thing I would point out is that you should probably not use int (though I suspect you were just doing that as a demonstration) as an exception. Either pick one of the standard exceptions or build your own (derived from std::runtime_error).

  try {
    printf("Transfer Savings to Checking 50\n");
    ctx[0]->execute(50);
  } catch(int n) {
    printf("Error: not enough funds\n");
  }

More pointer comments. Normal (modern C++) contains very few pointers. And even less explicit calls to delete. Any dynamically allocated object should be wrapped inside a smart pointer (or container like object boost::ptr_container springs to mind here). This makes there usage exception safe.

std::auto_ptr<moneyTransferCTX> tr(new moneyTransferCTX(checking, savings));
// Note I am using auto_ptr as this is the only smart pointe in C++03
// But it is not considered a good one (as it is easy to misuse)
// Look up the boost::shared_ptr or if you have C++11 compiler it is part of the standard.

// Note there are several good smart pointers and you should learn when to use
// each one appropriately.


Django query to find all items without a FK relationship except for excluded list

One of the inefficiencies in your code is when you're  collecting the list of ids of excluded_books. If you have 25 BOOKS_WITH_NO_AUTHORS, you're hitting the database 25 times.

I would recommend using the Q objects.
https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

This should substantially speed it up:

from django.db.models import Q

BOOKS_WITH_NO_AUTHORS = [(1979, "ABC123"), (1928, "DEF456")]

def missing_author(request):

    # Turn list of BOOKS_WITH_NO_AUTHORS into list of Q objects
    queries = [Q(publish_year=publish_year, book_num=book_num) for publish_year, book_num in BOOKS_WITH_NO_AUTHORS]

    # Take one Q object from the list
    query = queries.pop()

    # Or the Q object with the ones remaining in the list
    for item in queries:
        query |= item

    books_missing_authors = Book.objects. \
        filter(authors=None). \
        exclude(query). \
        order_by('publish_year')

    return render(request,
                  'missing_author.html',
                  {"data": books_missing_authors})


Remove value from linked list if it is equal to a parameter

Thank you for your interest in improving your code! Please, don't be confused about amount of comments. Programming is all about mastering your skills!

What's wrong with the code?

You leak memory!

For each call of new there must be a call for delete. Otherwise objects are not removed. Think of these operators as a C++ wrappers around malloc and free calls.

What could be improved?

Use T type in your methods

You used int k as a function argument, but an actual type you want is T. So it goes:

ListNode<T> * removeKFromList(ListNode<T> * l, T k)

Same for print method.

Use auto

When you change your signature to ListNode<T> notice, that using auto for statements, like

ListNode<int> *L2 = new ListNode<int>(node->value);

would not require any additional changes in the return types:

auto *L2 = new ListNode<T>(node->value);

It is common to use lowercase letters for variable names, even though you create all the list objects in uppercase.

Moreover, it looks nicer. But, do not overload your code with auto.
Use it only when it is obvious, what the type of your variable is.
So iterators, lambdas and new operators are the common case.

Variable & method names

Naming method removeKFromList suggests "remove key from the list", so we expect ListNode to contain pairs of key-value. It is confusing to see only T value in the struct, treated as a key in your methods. So it is better to rename method removeAllFromList. All here would stand for all occurrences. Do not use terms "key" and "value" together, unless you mean dictionary. Now:

ListNode<T> * removeAllFromList(ListNode<T> * l, T value)

It is considered a good practice to name variables in the way it makes sense what they stand for. Anyone should understand their meaning without reading more then couple of lines of code ahead. Ideally, write your code like a book. It wouldn't require much efforts. Try not to use variable names shorter then 3 symbols (except some particular cases, like in for-loop iteration):

ListNode<T> * removeAllFromList(ListNode<T> * list, T value)

Now we see another issue. If you pass ListNode<T> * it is actually a node, that is being passed by, but not the list. Fix:

ListNode<T> * removeAllFromList(ListNode<T> * node, T value)

const &

If integer instantiation is used, it is only a 4 bytes that are copied, so performance changes are unnoticeable. But since we use more complex classes, that would be an issue.
Use const & to fix this:

ListNode<T> *removeAllFromList(const ListNode<T> *node, const T &value)

Also make sure that nodes are not modified by writing const ListNode<T> *node

Style

Usually, it is hard to manually track all your spaces and tabulation. Use code refactoring tools. You sometimes mix styles by writing ) { and ){ with or without a space. We love perfection:)

Nesting levels

When you write:

if(l == nullptr){
    return nullptr;
}else{
   // ...
}

It is better to omit else body. That makes code more readable:

if (l == nullptr) {
    return nullptr;
}
   // ...

Reducing the amount of nested levels is good. And yes, use spaces.

File separation

ListNode methods are better placed in Node.cpp file, because they are relevant to ListNode.

Explicit

You may want to use explicit keyword to avoid unintentional type conversions.

What else could be improved?

Create LinkedList class

It is good to encapsulate your ListNode implementation. Hide your nodes, so no one could modify the values from outside, causing memory leaks or any kind of unintended behavior. It would also allow you to control memory by calling delete on each ListNode element in destructor.

There are more issues I may cover. But, please, start with those, provided above.
The method removeAllFromList could now look like this:

template<typename T>
shared_ptr<ListNode<T>> removeAllFromList(shared_ptr<ListNode<T>> node, const T &value) {
    if (node == nullptr) {
        return nullptr;
    }

    // The beginning node
    shared_ptr<ListNode<T>> root = nullptr;

    // Node used for iteration
    shared_ptr<ListNode<T>> current = nullptr;

    while (node != nullptr) {
        if (node->value == value) {
            node = node->next;
            continue;
        }
        if (root == nullptr) {
            root = std::make_shared<ListNode<T>>(node->value);
            current = root;
        } else {
            current->next = std::make_shared<ListNode<T>>(node->value);
            current = current->next;
        }

        node = node->next;
    }

    return root;
}

In my answer, I assume that you need to create a copy of the linked list and delete all the nodes with the value provided.


Print a pattern of text based on a line from an Excel file

STYLING
According to PEP-8, there are a few improvements to be made to your code:

Imports: Your imports should go in alphabetical order
Variable/Function Names: You should use snake_case instead of camelCase
Parameter Names: This may just be how I view your code, but how your parameters are named look like your taking in objects. You should use lowercase variables for better readability.
Spacing: You should use 4 spaces for each indent. For variable declaration and assignment, the = should be separated by a space on each side for readability, like so: s=0 to s = 0.
Main Guard: You should wrap any regular code in a if 'name == 'main' guard, to make sure that the code is only being run when that file is the main file, and not being imported by anything.

STRING FORMATTING
All throughout your code, you put strings together using + and .format. Luckily there is an easier way, by putting an f before the string like so: f"content here". This erases the need to have verbose + in your strings, and you no longer have to cast int to str with this method, you can just write the code in the brackets {your code here}.
Example:
return "name " + '"{}"'.format(cell_content)
to
return f"name \"{cell_content}\""
Here is the updated code:
import re
import xlrd

loc = ("Dir\StackoverflowExample.xlsx")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)

# Extracting number of rows

def case_multi(cell_content, cell_name):
    #takes a cell and a string as parameters, prints a pattern like Cell.X ="string", X starts with 0 and ends at the number of line in the Cell
    case = str(cell_content)
    x = re.split ("\s", case)   #splits the cell contents in a list using regex where space is the separator for the list's elements
    if name == cell_content:  # deals with the cell with spaces between objects no clue how it work but it does
        return f"name \"{cell_content}\""
    else:
        s = 0
        string = ""
    if str(x[0]).lower() == "any":
        return " "
    else:
        if len(x) == 1: # case where the cell has one line (or a word with no spaces)
            string = f"{cell_name} \"{case}\""
        else: # case where multilines/mutli spaces
            while s < len(x):
                listelement = x[s]
                string += f"{cell_name}.{str(s + 1)} \"{listelement}\""
                s += 1

        return string

def main():

    for number_of_rows in range(5):

        print "Rule " + str(number_of_rows)
        name= sheet.cell_value(number_of_rows, 1)
        source = sheet.cell_value(number_of_rows, 2)
        destination = sheet.cell_value(number_of_rows, 3)
        protocole = sheet.cell_value(number_of_rows, 4)
        log = sheet.cell_value(number_of_rows, 5)
        action = sheet.cell_value(number_of_rows, 6)
        #firewall = sheet.cell_value(number_of_rows, 7)

        try:
            print ("mgmt_cli add access-rule layer \"network\" position bottom " + str(case_multi(name,"name")) +  str(case_multi(source, " source")) + str(case_multi(destination, " destination")) +  str(case_multi(protocole, " service")) +   ' track.type "Log" ' + str(case_multi(action, " action")) )
        except:
            number_of_rows += 1

if __name__ == '__main__':
    main()


Extracting an XML config file from ZIP file and parsing it

The repeated part of your code can be extracted into a sub-function.

string InnerTextOfFirst(XmlDocument doc, string tagName)
{
  return doc.GetElementsByTagName(tagName)[0].InnerText;
}

Then use it like this:

appTitle = InnerTextOfFirst(xmlDoc, "appTitle");
appCompany = InnerTextOfFirst(xmlDoc, "appCompany");
appIconPath = InnerTextOfFirst(xmlDoc, "appIconPath");
appLargeIconPath = InnerTextOfFirst(xmlDoc, "appLargeIconPath");

This removes about a third of the inner most block.

Things to look out for:

What happens if the xml file does not have one of the tags you are expecting? It's likely that this block of code won't know the correct thing to do in this case. You should write the code so that when this happens, it is clear to the caller what the real issue is.
The C# naming convention for local variables is camelCase. While most of the variables are named correctly, the XmlNodeList variables are not.
There is a comment that refers to global variables. Having global mutable variables will make it harder to reason about how the code go into a certain state. It would be better to create a simple data class and have the code that parses the file return a new instance of that class with the parsed values.


A good solution is in this Stack Overflow answer:

rc = [response for ab in zip(A_response, B_response) for response in ab]


Simple gas station calculator for Windows

Firstly, I want to commend you on the neatness of your code. Appropriate spacing and newlines used make it very readable, even if some lines are slightly long. Also, you used the std:: namespace tag over the using namespace std; line, which is again, better practice in C++.

Now to answer your question, this code is not that large. When you compare it to the simplest possible program for a gas calculator, you must realize that your code has error-handling capabilities, it adds decimal seperators according to the German style, and it adds the ability to output the Euro sign to the screen. As you add more features, your code is naturally expected to get bigger, and once again, there is nothing that I can see in your code that is unnecessary, redundant, or unrequired (I'm not an expert on GetConsoleCP(), GetConsoleOutputCP(), etc..., so I may be wrong here).

**This is my general viewpoint of the code, and any further input for discussion is welcomed.


Correct using of try/catch clause on database execution

Some quick remarks:

Avoid writing ADO.NET code by hand; instead use an ORM like Dapper.
Why not use MAX() -- which I think is supported by PostgreSQL -- instead of ORDER BY roundNumberId DESC LIMIT 1?

SELECT MAX(column_name)
FROM table_name
WHERE condition;

Don't put business logic in exceptions. Instead, make this method int?
TryGetRoundNumberId() and let the calling code solve the issue when a null is returned.

Or perhaps provide a default, e.g. int TryGetRoundNumberId(int defaultValue), so you'll get something along these lines:

using (var sqlConnection = new SqlConnection(_connectionString))
{
    sqlConnection.Open();

    using (var sqlCommand = new SqlCommand())
    {
        // snip parameters etc.

        var result = (int?)sqlCommand.ExecuteScalar();
        if (result.HasValue)
        {
            return result.Value;
        }
        else
        {
            return defaultValue;
        }
    }
}


Implementation

size - sorted_elements might not return what you expect if size == 0 (it returns std::numeric_limits<unsigned int>::max()). This makes the intended check fail for size == 0. This can be fixed by changing the while loops condition to sorted_elements < size && !sorted.
You could use std::swap(arr[index], arr[index + 1]); to swap the elements. This way, the preferred assignment operation (copy or move) for Element will be used (if Element provides its own specialization). Currently, you always copy, which might not always be preferred (e.g. with large std::strings).


Pattern matching or list element selection?

It's possible to reduce the size of ones, tens, teens and so on if we use !! on a list instead of pattern matching. That's a completely other style though:

ones :: (Integral a, Ord a) => a -> WordNum
ones n
  | n > 0 && n < 10 = onsies !! fromIntegral n
  | otherwise       = error $ "ones: not a one-digit value"
  where
    onsies = words "one two three four five six seven eight nine"

Note that I removed the Show a constraint, because it's not necessary if our value n is in our range. It's only necessary in the error case. Instead, we should add where the error happened. Newer variants of GHC/base include a call-stack, therefore we will know the malfunctioning line, but it's always nice to know at least the function name. It also follows the base-style error messages, e.g.

head (x:_) = x
head []    = error "Prelude.head: empty list"

Either way, back to the code. Several functions are partial. Usually, you want your exported functions to be total, e.g. they never return _|_ (an infinite loop, an error, undefined,...). So instead of the ones above, we could write

ones :: (Integral a, Ord a) => a -> Maybe WordNum
ones n
  | n > 0 && n < 10 = Just $ onsies !! fromIntegral n
  | otherwise       = Nothing
  where
    onsies = words "one two three four five six seven eight nine"

However you wouldn't export all your helper functions either way, so lets keep the error variant. By the way, I've used words "one..." since my keyboard is slightly broken, but it's the same as ["one","two","three",...].

divMod, map and other standard library functions

Sometimes re-inventing the wheel is fun, but usually we want to try to get the most out of our standard library functions.

divMod

There are several occasions where we use both d = a `div` b and m = a `mod` b. If we use both, we can use (d,m) = a `divMod` b. That prevents typos like

    | n < 100   = tens (n `div` 10) ++ ' ' : (groupToWord $ n `mod` 11)
                                                    -- whoops        ^

So let us use it in splitNum:

splitNum :: Integral a => a -> [a]
splitNum n
    | d == 0    = [n]
    | otherwise = m : splitNum d
  where
    (d,m) = n `divMod` 1000

Note that quotRem will return the same values as divMod on positive numbers and is slightly faster.

zipWith and map

You use zip in your list comprehension just to ++ the zipped elements together. We can achieve this in a single step with zipWith:

[w ++ g | (w,g) <- reverse (zip wordGroups groups)]
= [ w ++ g | (w,g) <- reverse (zipWith (,)  wordGroups groups)]
= [ x      | x     <- reverse (zipWith (++) wordGroups groups)]
= reverse $ zipWith (++) wordGroups groups

toWordGroups is map groupToWord. If we use both functions in numToWord, we end up with

numToWord :: (Integral a, Ord a) => a -> String
numToWord n
    | n == 0     = "zero"
    | n >= 10^15 = error "numToWord: Doesn't support numbers bigger than trillions"
    | otherwise  = concat $ intersperse ", " $ reverse $ zipWith (++) wordGroups groups
    where
        wordGroups = map groupToWord $ splitNum n


Hard coding 32 as the size of the destination array regardless of the size if the source array is not so good, as it might not be big enough. Better approaches would be:

Make the destination twice as big as the input: that way it will always be big enough to contain the escape zeros. The drawback is that most often it will be too big.
Count the number of zeros first, and the allocate the exact size that you need. The drawback is that the counting step is an extra \$O(N)\$ operation. On the other hand, if the counting step find no zeros, then you can skip the copying step. If most input will not contain zeros, then this approach should work pretty well.


Separating the even and odd numbers in an array in C

Efficiency
Your code is already more efficient than you think. It has time complexity \$\mathcal{O}(n)\$, and thanks to tail recursion, it also has space complexity \$\mathcal{O}(1)\$.
Avoid forward declarations
I recommend that you avoid the need to forward-declare arrange() and swap() by reversing the order in which the functions appear in your source file. This avoids repeating yourself.
Don't return a void
Unfortunately, the C standard explicitly forbids calling return with an expression in a function returning void, even if the result of that expression itself is also void. While both GCC and Clang allow it, they will produce a warning when the -pedantic option is used. Just separate the call to arrange() from calling the return statement.
Simplify the code
Without making any changes to the algorithm, you can simplify the code. For example, the while-statement is redundant, since its condition will always be true in the first iteration, and you always call return inside the body, so it won't ever repeat. Furthermore, you can avoid having to declare the variables istart and iend. Here is how it could look:
void arrange(int arr[], int n) {
    if (n <= 1)
       return;

    if (arr[0] % 2 == 0) {
        arrange(arr + 1, n - 1);
    } else if (arr[n - 1] % 2 != 0) {
        arrange(arr, n - 1);
    } else {
        swap(&arr[0], &arr[n - 1]);
        arrange(arr + 1, n - 2);
    }
}


Playframework (Scala) custom exception handling

You are right to not create classes for AuthFail and EmailTaken.
These really sense as instances, rather than classes,
as they are special cases of AppException.

For example if AppException was a class, then AuthFail and EmailTaken would be best as instances of that class:

class AppException(val errorCode: Int, val message: String) extends Exception {
  val success = false
}

val emailTaken = new AppException(1, "email already used")

val authFail = new AppException(2, "id/password dont match")

However,
if they are instances,
then you would need to pass them around in the code where they might be needed.
Another alternative is to make them objects,
so you can easily import them and use them where needed:

object EmailTaken extends AppException(1, "email already used")

object AuthFail extends AppException(2, "id/password dont match")

Your approach using a trait for AppException instead of a class seems fine too, but I'm fairly new to Scala myself.
Using a class like I did above seems shorter, so I would prefer it.

As for using case classes (or case objects),
in the posted code I don't see a need:
it seems that you don't need to differentiate the different cases.
If all of these cases can be handled as an AppException and result in an InternalServerError,
then there's no need to implement more.

Finally:

  I could have used isInstanceOf[AppException] to check for custom exceptions. But are there any problems with this approach?

Don't do that. It's recommended to avoid isInstanceOf as much as possible.
The alternative is using polymorphism or pattern matching.
In your case, you don't actually need any of this.
You have simple instances of AppException:
all your cases behave the same way,
their only difference is in parameters, not in behavior.


Hacker rank - Left rotation - PHP code feedback for Timeout

Efficiency

You do a lot of manual shifting and pushing with your array. This is ok for small inputs, but as soon, as the distance $d and the size of your array $n grow, this becomes inefficient.

The main overhead however is coming from calling rotateOnce. Parameters are passed by value by default. That means the array is copied every time the function is called. You could pass it by reference:

function rotateOnce(&$a) {}

or simply include the two lines in your original function:

function rotLeft($a, $d) {
    $n = count($a);

    for ($i = 0; $i < $d; $i++) {
        $left = array_shift($a);
        $a[] = $left;
    }

    return $a;
}

I would guess that constraints on HackerRank mean, that you can expect values in that range and don't need to test inputs yourself.

This is now significant faster, but still slow especially for large distances $d.

That being said, I would take a look at PHP's internal array functions and think of a way, how to use them in combination to increase performance.

My naive approach would be something like this

if d is 0 or the same as the array's size, return the original
else split the array into two chunks at index $d
combine both arrays and return the result

The function could look like this Don't hover if you don't want to get spoiled:

 function rotLeft($a, $d) {
     if (count($a) == $d || $d === 0) {
         return $a;
     }

     $chunk1 = array_slice($a, 0, $d);
     $chunk2 = array_slice($a, $d);

     return array_merge($chunk2, $chunk1);
 }

For this input:

$a = range(1, 100000);
$n = count($a);
$d = 500;

… I've measured these times on my local machine*:

original: 1.8130s
optimized: 0.4294
rewritten: 0.0054s

Exponential expression vs. bitwise Operators

Your program has a flaw. It won't calculate the result correctly for large array sizes, because of this:

$n <= 10 ^ 5

^ is bitwise Xor and not pow:

pow(10, 5);
10 ** 5;

Try to avoid globals

I can see, that n is an input parameter that is not part of the function's given signature. However, I would try to avoid globals and get the value manually, if needed:

$n = count($a);

You can read more about this here:

PHP global in functions

Are global variables in PHP considered bad practice? If so, why?

* macOS 10.13, I7 2.5 GHz, 16GB RAM, MAMP PHP 7.2.1


Correct usage of alignas in std::ostringstream wrapper

This seems overcomplicated to me. Lazy-loading something doesn't require placement-new trickery and mucking around with alignments. Why not simply store a pointer to the stream which is only initialised when the user performs some kind of operation? This is the general way to do lazy-loading:

struct error_stream
{
private:
    std::unique_ptr<std::ostringstream> stream;

    // This should use make_unique, which you can find
    // or write yourself without too much hassle.
    void construct()
    {
        stream = std::unique_ptr<std::ostringstream>(
            new std::ostringstream);
    }

public:

    template <typename T>
    std::ostream& operator<<(T&& arg)
    {
        if(!stream) {
            construct();
        }
        (*stream) << std::forward<T>(arg);
        return *stream;
    }

    bool empty() const
    {
        return stream ? false : true;
    }

    std::string str()
    {
        if(empty()) {
             construct();
        }
        return stream->str();
    }
};

This seems to have the semantics you want (including being non-copyable due to using a std::unique_ptr) with much less hassle. You don't have to worry about placement new or any alignment requirements, which is going to make the code a -lot- harder to maintain.

Edit: If you really what to avoid the heap, I suppose you can use placement new. You allocate the memory for the stream when you create an error_stream, so I'm curious as to what problem you're trying to solve exactly. That being said, what you want to align is the storage for the ostringstream.

char memory_[sizeof(std::stringstream)];

Hence I'd use:

struct holder
{
....
private:
    alignas(std::ostringstream) char memory_[sizeof(std::stringstream)];
    ...
};


Printing the contents of a string array using pointers

Given that the code is really simple, I see mostly coding style issues with it.

Instead of this:

char *names[] = {
    "John", "Mona",
    "Lisa", "Frank"
};

I would prefer either of these writing styles:

char *names[] = { "John", "Mona", "Lisa", "Frank" };

// or

char *names[] = {
    "John",
    "Mona",
    "Lisa",
    "Frank"
};

The pNames variable is pointless. You could just use names.

Instead of the while loop, a for loop would be more natural.

This maybe a matter of taste,
but I don't think the Hungarian notation like *pArr is great.
And in any case you are using this pointer to step over character by character,
so "Arr" is hardly a good name.
I'd for go for pos instead. Or even just p.

You should declare variables in the smallest scope where they are used.
For example *pos would be best declared inside the for loop.
In C99 and above, the loop variable can be declared directly in the for statement.

The last return statement is unnecessary.
The compiler will insert it automatically and make the main method return with 0 (= success).

Putting it together:

int main(int argc, char *argv[])
{
    char *names[] = { "John", "Mona", "Lisa", "Frank" };
    for (int i = 0; i < 4; ++i) {
        char *pos = names[i];
        while (*pos != '\0') {
            printf("%c\n", *(pos++));
        }
        printf("\n");
    }
}

Actually it would be more interesting to use argc and argv for something:

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; ++i) {
        char *pos = argv[i];
        while (*pos != '\0') {
            printf("%c\n", *(pos++));
        }
        printf("\n");
    }
}


Converting and enriching an array of data

Depending on the constant overhead of retrieving the request presentation string for a request ID (i.e. is it considerably more efficient to get all the strings for a bunch of IDs at once than for each ID separately?), a better design might be to iterate over the theatre list only once, getting the representation strings as you go and caching the results in a Map.

Map<String, String> cache = new HashMap<>();
for (int i = 0; i < theatreListData.length; i++) {
    TheatreListDataWrapper wrapper = wrapperList[i];
    TheatreListData listData = theatreListData[i];
    String requestId = listData.getCarePlan().requestId;
    if (validRequestId(requestId)) {
        String text = cache.get(requestId);
        if (text == null) {
            text = getRequestDelegator().getRequestPresentationStringsById(requestId);
            cache.put(requestId, text);
        }
        wrapper.requestText = text;
    }
}

This is probably not a good idea of getting the request text requires, say, a database query.

Other than that, I can think of no algorithmic improvements. You should store the result of requestMap.get(requestId) in a local variable so you don't do the call twice; that's inefficient. Perhaps you can modify getRequestPresentationStringsByIds to take a Collection instead of a List so that you don't have to wrap your set in an ArrayList. Can't think of more.


These constituent queries will never generate overlapping results, since their ACTION columns are all distinct.  Therefore, you should be using UNION ALL instead of UNION to avoid the deduplication effort.

Also, I suspect you should be using INNER JOIN instead of LEFT JOIN because I doubt that you are interested in historical events that didn't occur.

For portability, string literals should be written using single quotes, like 'Request', rather than "Request".  Allowing double quotes for string literals is a MySQLism — standard SQL uses double quotes for identifiers, the way MySQL uses backticks.

Take care to be consistent in your indentation and capitalization.  You wrote h.FromUserId instead of h.`fromUserId` in one case.  You also call the result column ACTION, which is capitalized differently from history.Action.  The result also had "Accepted", "Denied", and "Track Request" oddly capitalized in various places.

Anyway, to address your specific concern, I think that this formulation using CASE could work for you.

SELECT Action, dateTime
    FROM (
        SELECT CASE
               WHEN h.Action = 'Request' THEN CONCAT('You sent track request to ', u.username)
               WHEN h.Action = 'Accept'  THEN CONCAT('You accepted track request from ', u.username)
               WHEN h.Action = 'Deny'    THEN CONCAT('You denied track request  from ', u.username)
               END CASE AS Action
             , h.dateTime
             , h.fromUserId AS self
            FROM history h
                INNER JOIN login_user u
                    ON h.toUserId = u.id
            WHERE h.Action IN ('Request', 'Accept', 'Deny')    -- possibly superfluous
        UNION ALL
        SELECT CASE
               WHEN h.Action = 'Request' THEN CONCAT(u.username, ' sent you track request')
               WHEN h.Action = 'Accept'  THEN CONCAT(u.username, ' accepted your track request')
               WHEN h.Action = 'Deny'    THEN CONCAT(u.username, ' denied your track request')
               END CASE AS Action
             , h.dateTime
             , h.toUserId AS self
            FROM history h
                INNER JOIN login_user u
                    ON h.fromUserId = u.id
            WHERE h.Action IN ('Request', 'Accept', 'Deny')    -- possibly superfluous
    ) AS msg
    WHERE self = 28
    ORDER BY dateTime;


SHA256 is not a secure password hash because it is fast. See How to securely hash passwords? on security.se for details.
It's not obvious that random is good enough to generate salts. While the requirments for salts are lower than those for keys, you still need a decent RNG. I recommend using SystemRandom.


Shortening method based on an argument name

Without seeing the greater context in which this code appears such as how the components are constructed, and not having kept up with Spring since 1999, I can only address the immediate code. The above could be converted to use two maps: one for the text fields and another for the currentScale strings.

In the code that builds the components, create the two maps and store them in instance fields of the same class.

private final Map<Object, JTextField> textFieldsByRadioButton = new IdentityHashMap<>();
private final Map<Object, String> scalesByRadioButton = new IdentityHashMap<>();

private void buildComponents() {
    ...
    addRadioButtonSpinnerMapping(rRadioButton, rSpinner, "r");
    addRadioButtonSpinnerMapping(gRadioButton, gSpinner, "g");
    addRadioButtonSpinnerMapping(bRadioButton, bSpinner, "b");
}

private void addRadioButtonSpinnerMapping(JRadioButton button, JSpinner spinner, String scale) {
    textFieldsByRadioButton.put(button, ((DefaultEditor) spinner.getEditor()).getTextField());
    scalesByRadioButton.put(button, scale);
}

public void itemStateChanged(ItemEvent ie) {
    Object source = ie.getSource();
    JTextField textField = textFieldsByRadioButton.get(source);
    if (textField != null) {
        currentScale = scalesByRadioButton.get(source);
        textField.requestFocus();
    }
    ...
}

While it requires slightly more code, it only takes one line to add another spinner.


The way I see it, you have 2 options; either use Deferreds, or store your delay in a variable:

var delay = 0,
    $left_box = $(".balance_left_box");

$("#bgd_balance").animate({
    backgroundPositionY: "0px",
    backgroundPositionX: "0px",
    'background-size':'100%'
}, 800, "swing");

$left_box.delay(delay += 2000).slideDown(200, "easeInCirc");

$left_box.find("p.first-line").delay(delay += 2400).slideDown(600, "easeInCirc");

$left_box.delay(delay += 1000).animate({
    height:"270px",
    top:"64px"
}, 100, "easeInCirc");


Parsing and formatting var_export() string

Your script is like a var_export()-var_dump() hybrid with flare (I've not come across highlight_string() before -- pretty cool).

I ran some more tests with a few samples that I had laying around and noticed that your code is having some difficulties accessing the written "resource" branch.  I tested with fopen($filename, 'r'); the var_export() evaluation of a resource is NULL and var_dump() returns resource(5) of type (stream).  Because your script is founded on var_export(), it will fail to dignify the resource type data, I think you [sh/c]ould remove that from your battery of checks.
Miscellaneous gotchas include:

['a => key' => 'something']

and

['multiline' => 'line1
line2']

These will break your regex-based parsing -- of course, the former is going to be a much less common occurrence versus the latter.
You can safely remove some useless declarations:

$Test = []; and $textvar = '';

As a general rule, I prefer to never use OR or AND in my conditional statements as a matter of consistency and as a means to avoid fringe precedence issues.
preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $textvar); This pattern/function is over-performing.  It doesn't make any sense to pick up the second capture group, just to put it back down unaltered.  In fact, there is no need for capture groups or character classes for this task.  I will also recommend that you use a consistent pattern delimiter for all patterns in your script. A tilde is a good/popular choice because it shouldn't interfere with any of your patterns and will help to prevent any accidental typos and escaping problems elsewhere.  To double the leading whitespace on each line, just use this (there's no use doubling zero whitespaces, so match one-or-more with +):

preg_replace('~^ +~m', '$0$0', $textvar);

$textvarArr = preg_split("/\r\n|\n|\r/", $textvar) is more succinctly written as:

$textvarArr = preg_split("~\R~", $textvar)

Whenever I see preg_match() called inside of a loop so that replacement actions can be performed, this is a classic indicator that preg_replace_callback() should be called.

$textvarArr = preg_split("~\R~", $textvar);
foreach ($textvarArr as $key => $value) {
    preg_match('~=>\\s(.*?),~', $value, $newvalue);
    if (!empty($newvalue)) {
        $newvalue[1]      = str_replace("'", "", $newvalue[1]);
        $typeval          = myGetType($newvalue[1]);
        $value            = str_replace("=> ", "=> " . $typeval . ': ', $value);
        $textvarArr[$key] = $value;
    }
}

can become:

$textvar = preg_replace_callback(
    "~ => \K\V+(?=,)~",
    function ($m) {
        return myGetType(str_replace("'", "", $m[0])) . ": {$m[0]}";
    },
    $textvar
);
// then proceed with something like...
$textvarArr = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => array ['], preg_split("~\R~", $textvar));

I've got to say that this looks a little dangerous...

if (substr($textvar, -1) == '[') {
    $textvar = str_replace("[", "[]", $textvar);
}

I mean, you are checking the final character, then doing a full text scan and replace operation.  This deserves a bit of double-checking.  Don't you only mean to close the final square brace? Maybe...

if (substr($textvar, -1) == '[') {
    $textvar .= "]";
}

I didn't get a chance to properly review (but it could probably use a little polish/simplifying):

$textvarArr = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => array ['], preg_split("~\R~", $textvar));
$textvar    = join(PHP_EOL, array_filter(["array ["] + $textvarArr));

I ran our outputs on a diffchecker program to be sure that my script returns the exact same output as yours.

Overall, an interesting exercise, good job.


BMI calculator in python using if statements

This kind of programming exercice, despite its apparent simplicity, is a good opportunity to learn various things.

Style

Python has a Code Style guide called PEP 8. If you begin with Python, I highly recommend reading it every now and then and trying to apply it.

In your case, a few things could be improved regarding style:

blank lines between the different branches of if are more an inconvenience from my point of view
variables should follow the snake_case naming convention (instead of camelCase)

Builtin input

As you've noticed for the end of the function, the input builtin takes an optional prompt parameter. This could be used at the beginning of the function as well.

Duplicated code

A lot of code looks like the same line with minimal variations. Having duplicated code makes the code more tedious to read and harder to maintain (if you need to change something, you'll need to change it in many places). One of the principles of software programming is Don't Repeat Yourself (also written DRY).

In your case, we could store the body category in a variable and only print the ouput from a single place:

Chained comparison

This is very specific to Python but instead of body_mass_index > 30 and body_mass_index <= 35, we can write: 30 < body_mass_index <= 35 using chained comparisons.

Magic numbers

Magic Numbers are usually frowned upon. In our case, one needs a bit of thinking to understand where the 12 and 0.025 come from. A better way to handle this is to store them in a variable with a meaningful name.

I am not quite sure about the best naming convention for names related to conversion constant. I've followed the names suggested by Solomon Ucko in the comments.

At this stage, we have the following code:

INCHES_PER_FOOT = 12
METERS_PER_INCH = 0.0254

weight_in_kilo = float(input('Enter your weight in kilo:'))
height_in_feet = float(input('Enter your height in feet:'))

height_in_meter = height_in_feet * INCHES_PER_FOOT * METERS_PER_INCH
body_mass_index = weight_in_kilo / (height_in_meter ** 2)

if body_mass_index < 15:
    category = 'very severely underweight'
elif 15 <= body_mass_index <= 16 :
    category = 'severely underweight'
elif 16 < body_mass_index <= 18.5:
    category = 'underweight'
elif 18.5 < body_mass_index <= 25:
    category = 'Normal(healthy weight)'
elif 25 < body_mass_index <= 30:
    category = 'overweight'
elif 30 < body_mass_index <= 35:
    category = 'moderately obese'
elif 35 < body_mass_index <= 40:
    category = 'severely obese'
elif body_mass_index > 40:
    category = 'very severely obese'

print('Your BMI = ' + str(body_mass_index) + ' You are ' + category + '.')
input('Please press Enter to exit')

Which can still be improved.

Mutually exclusive conditions

Because of the way we check body_mass_index, if it is under 15, we get into the first case so there is no need to check elif 15 <= body_mass_index in the else part. This is guaranteed to be always true. Similarly, half the checks have no effect.

Code organisation

To make the code easier to understand (and easier to reuse, to test, etc), it is a good habit to split in into smaller reusable chunks. In our case, defining functions could be a nice touch.

Disclaimer: Next paragraph can be a bit overwhelming for a beginner, do not worry if you do not fully get it. It highlights how to solve problems you may not be interested in yet but it is a good chance to do things properly.

Also, if we want to be able to actually reuse your functions, we want to be able to import the file. Currently, if we do so, we get stuck into the parts asking for user inputs. Thus, the usual strategy is the following: split your code into 2 parts:

code defining functions/constants/classes/etc but without any side-effect or user interactions
code actually doing things (input/output, etc) behind an if __name__ == "__main__": guard. As pointed out by Solomon Ucko, it's generally a good idea to have this performed via a main() function and have the last two (non-blank) lines be if __name__ == '__main__': main(). This allows the interactivity to be triggered as needed.

At this stage, we have:

INCHES_PER_FOOT = 12
METERS_PER_INCH = 0.0254

def convert_feet_to_meter(height_in_feet):
    return height_in_feet * INCHES_PER_FOOT * METERS_PER_INCH

def get_body_mass_index(height_in_meter, weight_in_kilo):
    return weight_in_kilo / (height_in_meter ** 2)

def get_category(body_mass_index):
    if body_mass_index < 15:
        return 'very severely underweight'
    elif body_mass_index <= 16 :
        return 'severely underweight'
    elif body_mass_index <= 18.5:
        return 'underweight'
    elif body_mass_index <= 25:
        return 'Normal(healthy weight)'
    elif body_mass_index <= 30:
        return 'overweight'
    elif body_mass_index <= 35:
        return 'moderately obese'
    elif body_mass_index <= 40:
        return 'severely obese'
    else:
        return 'very severely obese'

def main():
    weight_in_kilo = float(input('Enter your weight in kilo:'))
    height_in_feet = float(input('Enter your height in feet:'))
    height_in_meter = convert_feet_to_meter(height_in_feet)
    body_mass_index = get_body_mass_index(height_in_meter, weight_in_kilo)
    category = get_category(body_mass_index)
    print('Your BMI = ' + str(body_mass_index) + ' You are ' + category + '.')
    input('Please press Enter to exit')

if __name__ == "__main__":
    main()

Going further, a few more details could be improved.

String formatting

Python offers many tools to format strings so that you do not need to use string concatenations. You can refer to PyFormat.info for documentations and examples.

You could write:

print('Your BMI = %f You are %s.' % (body_mass_index, category))

Or the newer technique:

print('Your BMI = {} You are {}.'.format(body_mass_index, category))

Also, in Python 3.6, yet another soution was added: F-strings.

Data over code

This may be a bit overkill here but sometimes a lot of code can be replaced by a small amount of code working on a properly filled data structure. In our case, the get_category function does the same thing for all categories: check the if we are under a given limit and if so, return the category name.

Disclaimer: Next part works under the assumption that body_mass_index < 15 should actually use <= like the other cases.

# List of pairs (higher-limit, name) sorted
CATEGORIES = [
    (15, 'very severely underweight'),
    (16, 'severely underweight'),
    (18.5, 'underweight'),
    (25, 'Normal(healthy weight)'),
    (30, 'overweight'),
    (35, 'moderately obese'),
    (40, 'severely obese'),
]

def get_category(body_mass_index):
    for limit, name in CATEGORIES:
        if body_mass_index <= limit:
            return name
    return 'very severely obese'


Resolving promises on resolver using ui-router

You shouldn't use $q.defer unless you have to.

Here you can just return the promise:

Basket.fromApi = function (id) {
    return boxesResource.get({
        id: id
    }, function (response) {
        // various manipulation here with the response...
        return new Basket(...));
    });
};

You could really clean up the resolve by creating a new service:

State

.state('catalogue', {
    resolve: {
        boxCreateData: function($stateParams, boxCreateService) {
             return boxCreateService.getBoxCreateData($stateParams.id);
        }
    }
})

Service

app.service('boxCreateService', function(Basket, Customer) {
    this.getBoxCreateData = function(id) {
        return Basket.fromApi(id)
                .then(function (basket) {
                    return Customer.fromApi(basket.getCustomer())
                        .then(function (customer) {
                            return {
                                basket: basket,
                                customer: customer
                            };
                    });
                });
    };
});

There's not much you can do to avoid two nested promises here. You need the customer ID before you can get the customer.

More on the deferred antipattern.


Your code seems legit to me, so I'll try to answer some of your questions.
preg_match() uses UTF-8 input based on code points, so you don't have to worry about that.
The difference between \xYY and \x{YYYY} is that the first one accepts either one or two characters after control \x (so, up to 256-th code point), and the latter one is universal and accepts range which covers all Unicode table.
The u flag for RegExp pattern indicates that engine should treat the pattern as Unicode, it doesn't do anything with the text under test. So you can omit this flag in simple patterns like /[0-9]/. The last two code snippets also correct.


Is there a better way to assign constructor parameter in Typescript?

This is typical example of service locator anti pattern that should be refactored to builder pattern.

export class Hexagone {
  constructor(
    private ctx: CanvasRenderingContext2D,
    private center: Vector2,
    private size: number,
    private color: string,
    private type: HexagoneType
  ) {}
}

export class HexagoneBuilder {
  public center?: Vector2;
  public size?: number;
  public color?: string;
  public type?: HexagoneType;

  constructor(private ctx: CanvasRenderingContext2D) {}

  create() {
    return new Hexagone(
      this.ctx,
      this.center ?: new Vector2(),
      this.size ?: 100,
      this.color ?: "red",
      this.type ?: HexagonType.POINTY
    )
  }
}

Sorry if i made some syntax errors, I dont work with ts on daily basis, but you should get the idea...