Formatting phone number without knowing locale

Some improvements...

Variable re-assignment and null-check

You are re-assigning phoneNumber twice, and unfortunately I think you don't even need it at all.

First, it's generally not a nice idea to re-assign the method argument because careless mistakes may result in you inadvertently changing the instance referenced by it somewhere inside the method, when you're expecting the original input. Even if you don't explicitly final method parameters, it's simpler to always treat method arguments as an invariant so that you know what the method is processing on/with. Therefore, you should simply assign the output of stripNonDigits() to a new variable, and you can inline the new variable in the subsequent calls:

public static String formatPhoneNumber(String phoneNumber) throws NumberParseException {
    String strippedNumber = stripNonDigits(phoneNumber);
    return strippedNumber.length() != 7 && strippedNumber.length() != 10 ?
                strippedNumber : formatAsUSPhoneNumber(strippedNumber);
}

Now, you don't need a null-check (it's not in the right place anyways - it should be done at the start), and I renamed the main method as formatAsUSPhoneNumber(). I feel that formatUSPhoneNumber() is suggesting that it is formatting a US phone number into another representation.

stripNonDigits()

If stripNonDigits() should be used only by formatAsPhoneNumber(), consider making them private static. Ok, so even if you prefer not to use regex (fair point), how about Character.isDigit()? I feel that it's easier to read than the condition you have, short of the one-liner regex:

// replace all non-digits with an empty String
return input.toString().replaceAll("\\D+", "");


Get application credentials from linked array obtained from Cloud Foundry API

Consider breaking this into more, reusable methods.  E.g.

public Map<String, Object> getCredentials(String url, String org, String space, String app)
        throws MalformedURLException {

    GetApplicationEnvironmentsRequest request = GetApplicationEnvironmentsRequest.builder()
            .name(app)
            .build();

    Map<String, Object> mapSystemProvided = sm
            .getCurrentUserCfClient(new URL(url), org, space)
            .applications()
            .getEnvironments(request)
            .block()
            .getSystemProvided();

    Map<String, Object> SERVICES = (LinkedHashMap<String, Object>) mapSystemProvided.get("SERVICES");
    List<Object> apps = (ArrayList<Object>) SERVICES.get("apps");
    Map<String, Object> appsList = (LinkedHashMap<String, Object>) apps.get(0);

    return (LinkedHashMap<String, Object>) appsList.get("credentials");
}

public Map<String, String> getUserData(String url, String org, String space, String app)
        throws MalformedURLException {

    Map<String, Object> credentials = getCredentials(url, org, space, app);

    Map<String, String> parameters = new HashMap<>();
    parameters.put(ID, credentials.get(ID).toString());
    parameters.put(DEFAULTS, credentials.get(DEFAULTS).toString());

    return parameters;
}

Your original method was mostly getting the credentials.  If we move that into another method, it actually leaves this method rather simple and straightforward.

I moved what had been ops into the mapSystemProvided chain, as it wasn't used for anything else.

As a general rule, it is easier to have interfaces as types rather than implementations.  In this case, it makes the lines fit in the code window without scrolling on my screen.  That may not matter in your IDE though.  Mostly I just find it a good habit.  Most all of the time, you're just using the interface methods anyway.  Using the interface as the type helps enforce that and allows you to switch implementations easily.  Even if it doesn't actually work that way here.

I think that you could change the casts to the interface as well.  I didn't try that here, as I don't work with casting enough to be sure.  And of course there isn't enough context here to actually test this code.  But if I was working on this code, I'd try that to decouple it even more from the implementations.

I'd probably change SERVICES to services as I changed Url to url.  That way they fit the standard Java naming scheme.

I would consider changing the entity model.  For example, why is credentials hidden multiple levels deep inside of the getSystemProvided() result?  Maybe there's a reason for that, but it's hard to see with just this code.  It seems overly abstracted, at least when viewed in isolation like this.

Your indentation is funky.  I fixed it to be consistent in the alternative versions.  Perhaps that was just a copy & paste error.  There was also a missing } that I added.


It's hard to comment really well on this as your problem specification is more than a little vague.
Do you really want to do this based only on the first letter - is "AbominableSnowman" to be mapped to "Acc"?
Or do you know that the input sensor types are drawn from a specific set of values?
You could make your method (Java doesn't have functions) more succint, for example like this
private String findShortSensorName(String sensorType) {
  for (String sensorName : sensorNames) {
      if (sensorName.startsWith(sensorType.substring(0,1))) {
          return sensorName;
      }
  }
  return "";
}

However, the idiomatic approach for lookup in Java is usually to use a Map, and I'd have thought that if the value isn't found, throwing an Exception may be more appropriate than returning an empty string, though that will depend on your application. As your method doesn't look tied to a particular Java object, it can probably be "static", as well.
My version isn't shorter (it's considerably longer), but it's idiomatic (in my view) and easier to safely extend.
class BadSensorTypeException extends Exception {
// Thrown when a sensor type isn't found in the lookup table

  public BadSensorTypeException(String detailMessage) {
    super(detailMessage);
  }
 }

/**
 * lookup table mapping sensor types to short movesense names
 */
private static final Map<String, String> sensorNames = new HashMap<>();
static {
// static block to initialise the lookup table
  sensorNames.put("Accelerometr", "Acc");
  sensorNames.put("Gyroscope", "Gyro");
  // etc
}

/**
 * Converts human representation of sensor names to movesense names.
 * @param sensorType Human representation of sensor name.
 * @return Short name of the sensor.
 * @throws BadSensorTypeException if the sensor type isn't found
 */
private static String findShortSensorName(String sensorType) throws BadSensorTypeException {
  String shortName = sensorNames.get(sensorType);
  if (shortName != null) {
    return shortName;
  }
  throw new BadSensorTypeException(String.format("%s is not a valid sensor type", sensorType));
}


That is great as a first tkinter application. I like the fact you wrote two specific functions update_default_printer_label() and set_default_printer(). Most programmers will just do all what you did in one function and they believe as long as it does not exceed 25 lines length they are near perfection. With your approach, you have fine grain control on your program as unit testing is simplified (because you have small functions doing one clear task).

I do not have much to say about your program. There are very few imperfections but some may argue it is Ok. Nevertheless, I do not see the reason you let the function get_available_printers() orphan (I mean it can be integrated into the class PrinterManager, it is its right place and you will add only self. to call it where you did)

I would like to add one or two extra notes: given the description of the problematic, I think it would be reasonable to create a stand alone executable for your application using pyinstaller since you are trying to avoid navigating the printer menu and, why not, schedule your program (using python-crontab) to switch to the default printer (you need to add some code to check before switching) at a specific time (for example everyday at 08:10 AM)


Comparing two cars via their lifetime price

The first thing I would try is so factor out the input-prompting routines:

 private static Scanner input = new Scanner(System.in);

 private static int askInt(String prompt) {
     System.out.println(prompt);
     return input.nextInt();
 }

 private static double askDouble(String prompt) {
     System.out.println(prompt);
     return input.nextDouble();
 }

In my opinion, there's no particular reason why the car price, fuel efficiency, or distance numbers should be integral.  Why not just do all of the work in doubles?

public class CarComparison {
     private static Scanner input = new Scanner(System.in);

     private static double ask(String prompt) {
         System.out.println(prompt);
         return input.nextDouble();
     }

     public static void main(String[] args) {
         double carOnePrice = ask("Enter the price of car one: ");
         double carTwoPrice = ask("Enter the price of car two: ");
         double gasPrice = ask("Enter the price of gas in your area: ");
         double carOneMpg = ask("What is the average mpg of car one? ");
         double carTwoMpg = ask("What is the average mpg of car two? ");
         double milesDriven = ask("Give me an amount of miles total you think you will drive in this car: ");

         double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;
         double totalCostCarOne = gasCostCarOne + carOnePrice;

         double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;
         double totalCostCarTwo = gasCostCarTwo + carTwoPrice;

         if (totalCostCarOne == totalCostCarTwo) {
             System.out.println("The two cars cost the same.");
         } else if (totalCostCarOne < totalCostCarTwo) {
             System.out.println("Car One will, in total, cost less than car two. Buy it.");
         } else {
             System.out.println("Car two will, in total, cost less than car one. Buy it.");
         }
      }
}

For completeness, I've added handling for the unlikely case of a tie.

A next step might be to define a totalCost() function or to define a Car object, but I think that for this problem, the benefits of further changes would be marginal, and I would just leave it at that.


Project Euler #14 (Longest Collatz sequence)

First, put everything in a main function. This makes the variables local, which makes lookups a little faster. It's also neater.

It's worth formatting the comments with line wrapping and putting them in front of the commented line to keep lines short.

collatz_array[1] is never used except to iterate over, so just iterate over range(2, p) instead and ditch collatz_array[1]. In fact, at point of use it's simpler to just call enumerate:

max_value, max_count = 0, 0
for i, val in enumerate(collatz_array[2], 2):
    if max_count < val:
        max_count = val
        max_value = i

Then you should split collatz_array into two arrays, which I'm tentatively calling progression_mask and progression_length. They can be initialized as

progression_mask = np.arange(2, p, dtype='int64')
collatz_array = np.zeros(p-2, dtype='int64')

count is just len(sequence), so generate it at the end with len. When looping over sequence you can do:

count = len(sequence)
for q in sequence:
    ...
    count -= 1

if q in progression_mask is \$O(n)\$ but you can do the check in \$O(1)\$ with

if q < p and progression_mask[q-2]:

The same goes for if w in progression_mask.

This gets you much, much faster... but we can go faster still.

I would remove the -2 from the indexes by changing the arrays to:

progression_mask = np.arange(p, dtype='int64')
progression_length = np.zeros(p, dtype='int64')

Using pure lists is faster than Numpy arrays, so switch to them:

progression_mask = list(range(p))
progression_length = [0] * p

The final loop can be simplified with a max and index:

max_count = max(progression_length)
max_value = progression_length.index(max_count)

The main loop would be better with an early exit on the if i != 0 check, and it should be spelt if i (or if not i when inverted).

for i in progression_mask:
    if not i:
        continue

Generating the collatz numbers should be done with a function:

def collatz_progression(n):
    while n > 1:
        yield n

        if n % 2 == 0:
            n = n//2
        else:
            n = int((3*n)+1)

Note that this doesn't yield 1, as I don't think it's needed. It's called as

sequence = list(collatz_progression(i))

This isn't needed once we've moved to plain lists:

q = int(q)

If progression_mask is 0, we don't need to continue so can break from the loop:

if q < p:
    if not progression_mask[q]:
        break

    ...

count -= 1

I would ditch progression_mask and just check if progression_length is set.

Your loop

w = q
# Loop is run for about the number of even multiples of q
# the next even multiple
for e in range(1, p//q):
    w *= 2
    if w < p and progression_mask[w]:

would be better as

w = q
count_ = count
while w < p:
    progression_length[w] = count_

    count_ += 1
    w *= 2

in part so it can replace the other assignment. I would move it into a new function and rename the variables:

def assign_ascending_collatz(start, count, progression_length):
    while start < len(progression_length):
        progression_length[start] = count

        start *= 2
        count += 1

n = int((3*n)+1) can just be n = 3*n + 1.

if not n % 2 is more idiomatic than if n % 2 == 0, but even better is to flip the conditional and do

if n % 2:
    n = 3*n + 1
else:
    n = n//2

or maybe even

n = (3*n + 1) if n % 2 else (n // 2)

This gives:

def collatz_progression(n):
    while n > 1:
        yield n

        n = (3*n + 1) if n % 2 else (n // 2)

def assign_ascending_collatz(start, count, progression_length):
    while start < len(progression_length):
        progression_length[start] = count

        start *= 2
        count += 1

def main():
    up_to = 1000000

    progression_length = [-1] * up_to

    for i in range(up_to):
        if progression_length[i] != -1:
            continue

        sequence = list(collatz_progression(i))

        for i, val in enumerate(sequence):
            if val < up_to and progression_length[val] != -1:
                    break

            # Cache the count
            assign_ascending_collatz(val, len(sequence)-i, progression_length)

    max_count = max(progression_length)
    max_value = progression_length.index(max_count)

    print("Number with longest collatz sequence: ", max_value)

main()

With PyPy3 this takes me ~1.5s to run.

Most of the time seems to be in collatz_progression, so we can speed that up by letting it short-circuit against progression_length. This gives:

def collatz_progression(n, progression_length):
    while True:
        yield n

        if n < len(progression_length) and progression_length[n] != -1:
            return

        n = (3*n + 1) if n % 2 else (n // 2)

def assign_ascending_collatz(start, count, progression_length):
    while start < len(progression_length):
        progression_length[start] = count

        start *= 2
        count += 1

def main():
    up_to = 1000000

    progression_length = [-1] * up_to

    # Skip 0 and set 1
    progression_length[0] = 0
    progression_length[1] = 0

    for i in range(up_to):
        if progression_length[i] != -1:
            continue

        sequence = list(collatz_progression(i, progression_length))
        count = len(sequence) + progression_length[sequence.pop()]

        for val in sequence:
            # Cache the count
            assign_ascending_collatz(val, count, progression_length)
            count -= 1

    max_count = max(progression_length[1:])
    max_value = progression_length.index(max_count)

    print("Number with longest collatz sequence: ", max_value)

main()

Note that I had to fix progression_length[1] to avoid the -1 adding to the other values.

With PyPy3 this takes ~0.3 seconds to run. Hopefully that's fast enough.

Note that now your clever optimization of going forward as well with assign_ascending_collatz doesn't actually help. Getting rid of it even gives a tiny speed improvement:

def collatz_progression(n, progression_length):
    while True:
        yield n

        if n < len(progression_length) and progression_length[n] != -1:
            return

        n = (3*n + 1) if n % 2 else (n // 2)

def main():
    up_to = 1000000

    progression_length = [-1] * up_to

    # Skip 0 and set 1
    progression_length[0] = 0
    progression_length[1] = 0

    for i in range(up_to):
        if progression_length[i] != -1:
            continue

        sequence = list(collatz_progression(i, progression_length))
        count = len(sequence) + progression_length[sequence.pop()]

        for val in sequence:
            if val < len(progression_length):
                progression_length[val] = count

            count -= 1

    max_count = max(progression_length[1:])
    max_value = progression_length.index(max_count)

    print("Number with longest collatz sequence: ", max_value)

main()

Some good questions from the comments:

  Before turning the lists into arrays, for some p, the execution time was 305s and after the change, it became 448s. Does it not count against lists?

Numpy arrays are faster than lists for some things and slower for others. In particular, arrays tend to be slower when indexing single items (eg. my_array[12]). They tend to be faster on operations that affect the whole array, such as q in progression_mask, which searches the whole array.

Before removing if q in progression_mask and if w in progression_mask, most of the time was spent in those two operations. This meant arrays were significantly faster.

After removing them, all operations on the array were just indexes. This means that lists became faster.

So lists are only faster after making certain changes to the code.

  Why did you populate the progression_length with -1? It didn't seem to affect the result, either with 0 or -1.

I (arbitrarily) set progression_length[1] = 0 (instead of 1). This meant that 0 was a valid value, so it didn't make sense in my opinion to use it as a sentinel.

I would have chosen None instead of -1 if PyPy didn't have a special optimization for lists of only integers, meaning it's faster if I use an integer. If you don't want to use PyPy or don't mind PyPy being a little slower, I suggest using None.

  And you lost me completely after you 'short-circuited collatz_progression against progression_length'.

Let's say you have these lengths:

  0 1 2 3 4 5 6 7
[ 0 0 1 6 1 4 ? ? ]

where the ? is represented with -1.

We want to find the collatz number for 6. The original method would find this list:

[6, 3, 10, 5, 16, 8, 4, 2]

find its length and then loop over it, setting the values in progression_lengths.

However, once you have gotten

[6, 3, ...]

you know that every number afterwards is already set in the array since progression_length[3] != -1. This means you don't need to set them in the array.

You still need to know the number of skipped items, so you look it up from

# The last value before we stopped
progression_length[3]

which gives 6. You add that to the number of values in front (1) and get 7. This means you only have to generate 2 values from collatz_progression instead of 7 in order to get the appropriate length.

  And why didn't even multiples elimination not work?

It did work but the above optimization does the same thing in a better way.


Always prefer const when declaring variables - only use let when you have to reassign a variable. const requires less cognitive overhead, when you know at a glance that something's never going to be reassigned.
Style toggling You're currently toggling the style with styleSheet.insertRule(rule, 0) and styleSheet.deleteRule(0). I think it would be a little bit better to take a different approach.

Who knows what insertRule(rule, 0) and deleteRule(0) do at a glance? Probably not a whole lot of people; it's not a very common API that's used.
What if you need to expand the extension to add additional rules? Then using multiple rule indicies could become repetitive.

One alternative would be to, on toggle, either append or remove the style tag from the <head>. Another alternative would be to assign or clear its textContent. See below for example.
hideLinks is not an altogether precise name. At first glance, someone seeing a variable named hideLinks would probably think it sounds like a function that, when called, hides links. Maybe call it something else, like linksAreHidden. You can also make its toggling more DRY:
if (hideLinks) {
    styleSheet.deleteRule(0);
    hideLinks = !hideLinks;
} else {
    styleSheet.insertRule(hideLinksRule, 0);
    hideLinks = !hideLinks;
}

can be
if (hideLinks) {
    styleSheet.deleteRule(0);
} else {
    styleSheet.insertRule(hideLinksRule, 0);
}
hideLinks = !hideLinks;

Or, even better, rather than having a persistent outside variable, you could simply check to see whether the style element is attached or has content. See below for example. This is what I'd prefer - let the style node (which must exist regardless) be the source of truth, rather than introducing another variable that needs to stay in sync.
Request object You currently have
if (request.isQuery) {
    return Promise.resolve({
        hideLinks
    });
}
// otherwise, insert or remove style rule

I think it'd be better to be more explicit. What if you add a 3rd request command, or a 4th request command? Instead of having an implicit "Else, if this isn't a query, then do THIS instead", I'd prefer to always send a property indicating what the command should be.
Perhaps like this, using a isToggle property:
const hideLinksStyleText = `
a,
a:hover,
a:focus,
a:active,
a:visited {
text-decoration: none !important;
color: inherit !important;
background-color: inherit !important;
border-bottom: initial !important;
}`;
const styleTag = document.head.appendChild(document.createElement('style'));

function handleRequest(request) {
    const linksOriginallyHidden = Boolean(styleTag.textContent);
    // Do not modify if request is only a query
    if (request.isQuery) {
        return Promise.resolve({
            linksAreHidden: linksOriginallyHidden
        });
    }
    if (request.isToggle) {
        styleTag.textContent = linksOriginallyHidden
            ? hideLinksStyleText
            : '';
        return Promise.resolve({
            linksAreHidden: !linksOriginallyHidden
        });
    }
}

The conditional operator can be used to make conditional expressions tersely. This:
const showLinksIconPath = {
    path: 'icons/link-icon.png'
};
const hideLinksIconPath = {
    path: 'icons/broken-link-icon.png'
};
function updateIcon(response) {
    if (response.hideLinks) {
        browser.browserAction.setIcon(hideLinksIconPath);
    } else {
        browser.browserAction.setIcon(showLinksIconPath);
    }
}

can turn into
function updateIcon(response) {
    browser.browserAction.setIcon({
        path: `icons/${response.hideLinks ? 'broken-' : ''}link-icon.png`
    });
}

Or, if you don't like the interpolation:
function updateIcon(response) {
    browser.browserAction.setIcon({
        path: response.hideLinks
            ? 'icons/broken-link-icon.png'
            : 'icons/link-icon.png'
    });
}

Tab checking You have:
if (!(tabs === undefined || tabs.length == 0)) {
  const activeTab = tabs[0];

The negations are slightly tougher to parse logically at a glance than they can be. Consider instead:
if (tabs && tabs.length) {

In a larger project, you could use optional chaining and Babel:
if (tabs?.length) {

But optional chaining is only supported in very new versions of FF, and Babel isn't worth it just for this. (Babel is a good idea if you want to write a reasonably sized script and want to permit older browser versions to be able to understand the JS syntax you use. For a FF extension, it's less important, because almost all users will be on reasonably up-to-date browsers anyway - no need to transpile down to ES5 for those crummy IE11 users)


Avoiding pointers in this C++ linked list

I see some things that may help you improve your code.

Write member initializers in declaration order

One of the constructors for node looks like this:

node(node * prev, node * next, const T & data) :
        prev(prev), next(next), data(data) {
}

That looks fine, but in fact, next will be initialized before prev because members are always initialized in declaration order and next is declared before prev in this class. To avoid misleading another programmer, you should swap the order of those such that it says instead:

node(node * prev, node * next, const T & data) :
        next(next), prev(prev), data(data) {
}

This way the initialization actually proceeds from left to right as one might expect at first glance.

Eliminate the default constructor

At the moment, one of the constructors for node is written like this:

node() : T() { }

However, this is not good at all since, if it were ever used, it would leave next and prev uninitialized.  Better would be to explicitly delete it like this:

node()  = delete;

Add a destructor

Because you're allocating memory with new you must also deallocate it with delete or your program will leak memory.  Here's one way to write it:

virtual ~linkedlist() {
    for (auto it = begin(); it != end(); it = begin()) {
        remove(it);
    }
}

Provide move semantics for iterators

Right now, it's not possible to do this:

linkedlist<std::complex<float>> ll;
ll.remove(ll.begin());

The reason is that ll.begin() is an "rvalue" and so can't be passed as a reference.  To fix this, create a version of remove with move semantics:

bool remove(iterator &&iterator) {
    if (iterator.current_node == &first || iterator.current_node == &last)
        return false;
    node *to_remove = iterator.current_node;
    to_remove->prev->next = to_remove->next;
    to_remove->next->prev = to_remove->prev;
    delete to_remove;
    return true;
}

Provide const versions of iterators

The cbegin() and cend() forms of the iterators are missing.  Here's a simple cbegin():

iterator cbegin() const {
    return iterator(first.next);
}

Provide an initializer_list constructor

At the moment, this form of the constructor doesn't work:

linkedlist<std::complex<float>> ll{{3,4}, {5,12}};

It's simple to add, however:

linkedlist(std::initializer_list<T> list) :
        first(nullptr, &last, T()),
        last(&first, &last, T())
{
    for (auto &item : list) {
        add(item);
    }
}

Provide copy function or delete it

At the moment, a copy function is compiler generated but almost certainly not what you want because it will only copy pointers and not the underlying data.  Either delete the function explicitly or provide one.

Provide member functions to suit the data structure

A linked list is not a very good data structure for many purposes, but one thing that is efficient is the ability to insert one linked list within another (a splice).  Unfortunately, this function is not provided, so any advantage is unrealized.

Provide a full iterator implementation

In order to use the algorithms in <algorithm>, you will need first class iterators, but although somewhat useful, yours are missing a number of pieces.  See this reference page for details on what a real iterator provides.


Unit testing F# code without using an existing test library (MSTest, xUnit, etc.)

Overall this looks ok, just a couple nitpicks:

In assertAreEqual, you're using string concatenation and then passing the resulting string to formatting function. You could use the formatting function to begin with:

if expected <> actual then
    printfn "Test failed, expected %A, actual %A" expected actual
else
    printfn "Test passed"

Parentheses around tuples are not required, so:

let testsToRun =
[
    "test newHeightMap will return a 0 initialized height map",
    testNewHeightMapReturnZeroInitializedHm
]

Function parameters are actually patterns, so you can destructure the tuple right there, instead of on a separate line:

let runSingleTest (testName, testFunction) =
    ...

As a general rule, if you have to use ignore, it means that there is something wrong somewhere. ignore is a hack, a way to squeeze a round peg in a square hole. In your particular case, you're mapping over a list solely for the side-effects. To do this, use List.iter, which returns unit, so no need for `ignore.

testsToRun |> List.iter runSingleTest

The pervasive use of side-effecting computations (i.e. printfn etc.) sets off my spidey sense: this makes your code inflexible (e.g. what if you want to have different reporting formats - one for console run, one for CI server, etc.).
You should structure your code in such a way that it doesn't produce side effects as it runs, but instead produces a value that describes the run, and which can later be used (or not used) to produce the effects. For example, in your case, rather than printing out errors, I would return a list of them, and have the consumer decide what to do with that list. Of course, this would mean significant restructuring of your whole program, so I won't give a code example.
Finally, "parametrize all the things!" Try to take stuff as parameters as much as possible, rather than relying on stuff existing in the environment. For example, the runTests function should really take the list of tests as parameter.
As far as the thing that bugs you, there is an easy solution for it: you don't have to name your functions, you can declare them inline as lambda-expressions:

let testsToRun =
    [
        "test newHeightMap will return a 0 initialized height map",
        fun() ->
            let hm = newHeightMap 5
            let result = hm.Map |> Array.sum
            assertAreEqual 0.0 result
    ]

Or, alternatively, you can give a name to the pair of name+function, and then include that pair in the list:

let theTest = "test newHeightMap will return a 0 initialized height map", fun() ->
    let hm = newHeightMap 5
    let result = hm.Map |> Array.sum
    assertAreEqual 0.0 result

let testsToRun = [ theTest ]


Drawing a roaming figure in a field, with less flickering

You may want to use the curses library.

def clear():
    os.system('cls')

You complain about "flicker", which is related to perceptible "slowness". Almost certainly your environment supports xterm/vt100 ANSI escape sequences. You forked off a command, cls, that printed <ESC>[H to put cursor at top of screen, and <ESC>[2J to clear screen. You could more quickly print() such escape sequences.

map1=("#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#")

Please don't do that. Express it as map1 = '#' * 31

del edit_map[x]
edit_map.insert(x, "o")

Delete and insert both have linear cost, which is small for a 31-char string, but still, avoid turning O(1) ops into O(n) ops. Instead, just assign: edit_map[x] = 'o'.

You can reposition the cursor with a simple CR rather than ANSI sequences: print(edit_map + '\r'). That alone could make the flicker negligible.


Style

Comments

I stated this in a comment (pun unintended but a happy side effect) that I think comments like this are unneeded and make the code harder to read.

if (null == inputArray || 0 == inputArray.length) {
    throw new IllegalArgumentException(
            "Input Array is either null or of zero length");
} // end of null and 0 length check

// Return if the input array has only one item
if (inputArray.length < INPUT_LESS_THAN_TWO) {
    return inputArray;
} // end of check for length less than 2

Compare that to this

if (null == inputArray || 0 == inputArray.length) {
    throw new IllegalArgumentException(
            "Input Array is either null or of zero length");
}

// Return if the input array has only one item
if (inputArray.length < INPUT_LESS_THAN_TWO) {
    return inputArray;
}

Because everything is properly indented I just know by looking that the if-block if over.

Lastly, the comments for i and j are poor. You state what they are originally pointing to but not what they're used for throughout the method which would be more useful. Something like this,

int j = 0; // Marks the end of the sorted subarray to return
int i = 0; // Points to the element being checked

(It may be better to switch the names of i and j because i is usually used for the outer most "loop" meaning it moves less.)

Doc Comments

Adding javadoc comments is good practice and it's good to see you do this. The only issue I see with it is it starts by saying it's a method and it gives the name. This is redundant. The name is beneath the doc comment and if you view the javadoc as html it is still clear what the name is. Just remove "Method removeDuplicateElement."

Throws IllegalArgumentException

See this if you do not know the difference between checked and unchecked exceptions. IllegalArgumentException extends RuntimeException. Because of this it is an unchecked exception.

The throws clause of a method is to alert the compiler that it can possibly throw the exception. Because this is an unchecked exception though the compiler doesn't care if the caller handles/throws it or not, and because of that it is redundant. I suggest either removing this or making your own exception that doesn't extend RuntimeException if you really want to make the called handle/throw the error. (I think this is a bad idea.)

Note: I did not say there was an issue with throw new IllegalArgumentException( ... ); when the array is invalid for your method, this is fine. However, one could argue that because the point of the method is to remove duplicate elements that a null/empty array has the elements removes and you could simply return the null/empty array instead of throwing the error. In fact, I think I like that better. It's best to throw little and handle quietly when it comes to exceptions.

Utility Class

I seem to be linking back to my own answer a lot. For the same reasons as here I suggest you make this into a "utility class". Because everything about this class is always the same no matter how you make an instance of it, there's no point in having to make an instance of it. Quick summary,

make it a final class,
add a private constructor, and
make all methods static.

private static final fields

There is nothing wrong with these but in this case I don't think making INPUT_LESS_THAN_TWO into one makes sense. You'd return the array if it only had one element no matter what, there's not something that's likely to change down the line that would make this value different.

inputArray.length < 2 is simply more readable in this case, or better yet inputArray.length == 1 because earlier you already checked if it was 0 and it should never be below 0. (If it's ever below 0 the JVM is messing up and there's bigger issues! It's safe to assume it won't.)

Code choice

System.arraycopy

  Edit: 200_success's suggestion of Arrays.copyOf is better than my suggestion here. System.arraycopy is better when you already have an array you want to put things in, Arrays.copyOf makes a new array for you. Better to do away with making outputArray altogether and simply doing return Arrays.copyOf(inputArray, j + 1);. System.arraycopy is still a good tool to know of so I will leave this section, bold italic text is text I added in this edit.

This is preferred to using a for-loop to make an array from an array specifically when you already have an array that you want to put the copied elements in.

for (int k = 0; k < outputArray.length; k++) {
    outputArray[k] = inputArray[k];
}

That becomes simply System.arraycopy(inputArray, 0, outputArray, 0, outputArray.length); (You may need to remove the final modifier for the output array, I am not entirely sure.)

Increment operators

This is simply my taste, no issue with your code, but I dislike inputArray[++j] = inputArray[i++]; because it's a little confusing. I prefer

j++;
inputArray[j] = inputArray[i];
i++;


Delete all elements from list whose sum with preceding element equals target value

Breaking down the requirements:

  You are given a list of integers (std::list<'int'>).

The algorithm is required to at least work with std::list<int>, so we cannot rely on random-access/contiguity.

  Iterating over the list only once,

Requires a single-pass algorithm.  Single pass algorithms have special rules associated with them, like only accessing the current element once and only moving forward.  Your implementation exhibits multi-pass behavior.

std::prev(nmbrs.end())
--i;

  delete all elements that give a sum of 10 with the preceding element.

Applying this to a single pass approach, you will need to store the preceding element in a temporary.

A source file should be self-sufficient in providing the definition of every symbol used.  Some implementations may include the library for you (<list> including <iterator>, but that behavior is neither standard nor portable.  std::prev requires <iterator>.

bool target_sum(const int i, const int j)
{
    return (i+j) == 10;
}

Don't use magic numbers.  The target sum for this test is 10, but will it always be 10?

void print(const std::list<int> &nmbrs)
{
    for (const int p : nmbrs)
        std::cout << p << " ";
    std::cout << std::endl;
}

Every line that gets printed prints an extra delimiter at the end of the list.  An extra whitespace character might not do anything, but it certainly isn't intended.  Strive for correctness in your programs.

Avoid std::endl. Directly state your intent in code and be aware of what std::endl does. The following two statements are equivalent (ignoring localization).

std::cout << std::endl;
std::cout << '\n' << std::flush;

Again, be explicit with your intent.

std::cout << std::endl;           // Flush intended?
std::cout << '\n';                // Definitely don't flush.
std::cout << '\n' << std::flush;  // Definitely flush.

// initialises a list that holds the numbers
std::list<int> nmbrs = {5, 5, 3, 7, 7, 7, 3, 3, 1, 2, 3, 7, 4, 6};

if (nmbrs.size() > 1)                     //if there are at least 2 numbers

Don't say in comments what can be or is already stated in code.

Vowels do not cost $500.  Having a smaller variable name because your abbreviation strips vowels or truncates the end doesn't translate to better code or performance.  Abbreviations negatively impacts readability and maintainability, which are two very important aspects in programming.

Factor out common code into functions.  Functions promote reuse and limits the scope for errors (making testing easier).

std::list<int>::iterator i = nmbrs.begin();

Use auto to avoid repetition of type names.

target_sum(*i, *(i++))

C++ has special rules regarding evaluation order.  In this case, the , of the argument list is not a sequence point because the argument list itself is not an expression.  Since the arguments are indeterminately sequenced, modifying the variable and trying to access the variable is undefined behavior.

// print(nmbrs);

Remove dead code rather than commenting.

_getch();

You don't need _getch(); or conio.h.  If you need to pause on input, the standard library already provides such a facility (std::cin.get()).

Instead of cluttering your program with unnecessary debugging support code, learn about your terminal emulator and how to use it correctly.  Some IDE's provide an option to keep the window open after running.  Other IDE's offer a full fledged debugging system (MSVC) where you can use breakpoints to externally "pause" the program.


Take all underlined words, put in Excel column

In the Word document

Click on an underlined word
In the Home menu, in the Editing  section, click Select > Select Text with Similar Formatting
Copy
Open Excel and paste

You may need to clean it up in Excel, but you don't need VBA to do this.


The merge method

The implementation of merge is difficult to understand.

Naming is one problem. a, b, x, y are hard to distinguish. Was a the value and x the index of the first array? Or the other way around? It's easy to get lost.
Another issue with naming is that arrayA and arrayB differ by one letter. It's recommended to avoid using similar variable names, as the human eye may overlook too minor differences. first and second would be unmistakable.
A loop with a long body, multiple continue statements, and multiple incremented variables, is generally hard to read. It's all too easy to get lost in this code.

A simpler, almost naive implementation of the same thing:

private static int[] merge(int[] first, int[] second) {
    int[] merged = new int[first.length + second.length];

    int firstIndex = 0;
    int secondIndex = 0;
    int index = 0;

    while (firstIndex < first.length && secondIndex < second.length) {
        if (first[firstIndex] < second[secondIndex]) {
            merged[index++] = first[firstIndex++];
        } else {
            merged[index++] = second[secondIndex++];
        }
    }

    while (firstIndex < first.length) {
        merged[index++] = first[firstIndex++];
    }

    while (secondIndex < second.length) {
        merged[index++] = second[secondIndex++];
    }

    return merged;
}

Note that I also changed the visibility to private. This method is an implementation detail of your sorting algorithm, no need to expose it.

The mergeSort method

It's recommended to minimize the live time of variables: the number of lines between declaration and last use. In other words, declare variables right before they are needed, not sooner.

In mergeSort, look at outputArr:

    // Creating resulting array
    int[] outputArr = new int[n];

    // Initializing arrayA
    for (int i = 0; i < arrayA.length; i++) {
        arrayA[i] = inputArr[i];
    }

    // Initializing arrayB
    for (int i = 0; i < arrayB.length; i++) {
        arrayB[i] = inputArr[i + (n / 2)];
    }

    // Divide array into 2 halves
    arrayA = mergeSort(arrayA);
    arrayB = mergeSort(arrayB);
    outputArr = merge(arrayA, arrayB);

    return outputArr;

It's not used until much later in the method. Notice what happens when you delay the declaration as much as possible:

    // Creating resulting array
    int[] outputArr = new int[n];
    outputArr = merge(arrayA, arrayB);

    return outputArr;

Do you see a problem? A new array is allocated in new int[n], only to be thrown away. Such mistakes become visible when you delay the declaration as much as possible. The above can be reduced to:

    return merge(arrayA, arrayB);

Memory/space inefficiency

You asked for comments "other than this". That's not a good idea. Usually there's a good reason why obvious problems should be avoided.

A merge sort can be implemented with essentially the same algorithm, but without creating the half-arrays. You will still need an extra array to perform the merge step. But the number of arrays created will be reduced drastically.

The JDK has Arrays.sort and Collections.sort utility methods for sorting arrays and collections, respectively. Both operate in-place. Usually it's good to follow example practices of the JDK. If you don't want to destroy the original array/collection, you can create a simple wrapper that copies the original collection, sort the copy and return a copy.


Function to erase original element but also linked

OK. This is NOT C++ code. This is C that happens to use a few C++ features like std::list. I would call this "C with classes".

What you have failed to do is define the ownership of the pointers. Without ownership calling delete is a pain (because you don't know if calling delete is a good idea because you don't know the ownership).

There is no point in reviewing further until you define ownership semantics.
Who owns the pointer.

Is it shared ownership.
Is it exclusive ownership.
Are there cycles?

This looks really awful:

  A* a1 = new B(0);
  A* a2 = new B(1);
  A* a3 = new B(2);
  A* a4 = new B(3);
  A* a5 = new B(4);
  A* a6 = new B(5);

You have 6 RAW pointers. What happens if the constructor to B(3) throws an exception. Then you have just leaked a1/a2/a3. In modern C++ it is very rare to see RAW pointers. Pointers are usually contained inside an object (usually a smart pointer).

Now you are passing the pointers to a list.

  //put them in a list
  std::list<A*> alist;
  alist.push_back(a5);
  alist.push_back(a6);
  alist.push_back(a1);
  alist.push_back(a2);
  alist.push_back(a3);
  alist.push_back(a4);

So now you have two people pointing at each object. So who is supposed to destroy them? You have not defined the ownership semantics thus we do not know who is responsible for deleting the pointers. Even worse if they are deleted via one method the other pointer points at an invalid location (as there is no feedback) between the pointers.

boost::ptr_list would hold and take ownership of the pointers very nicely.

Cleanup outside a destructor!!!

  //cleanup
  it = alist.begin();
  while(it != alist.end()) {
     delete *it;
     it = alist.erase(it);
  }

This is not exception safe. You need to use RAII to make sure you can never leak resources even in the presence of pointers.


Having less code for the current program

Applying the good ol' DRY principle and by adding coef as a parameter, we'd get something like :

function setChoices(coef) {
    var relevantArray = (coef === 0) ? time :
                        (coef === 1) ? category :
                                       complexity;
    for (var i = 0; i < relevantArray.length; i++) {
        var node = document.createElement('option');
        node.value = relevantArray[i].toString();
        node.innerHTML = relevantArray[i];
        select.appendChild(node);
    }
}

function updateObject() {
       for (var coef = 0; coef<3; coef++)
       {
           ((coef === 0) ? choice.time :
            (coef === 1) ? choice.category :
                           choice.complexity) =  select.value;
            removeChildren();
            setChoices(coef);
       }
}

(Also, I have changed a few things which I assumed to be wrong, for instance, updateObject did not call setChoices with coef=0.


Regarding your questions:

No, I think the functions as they are are fine, not everything needs
to be moved into a class.
If it's an implementation detail, sure.
AFAIK no, but if it's otherwise empty the method doesn't have to be
added.

Also:

In load_module the loop can be more compact by using a combination
of list.extend and filter.

def load_module(self, module):
    self.plugins.extend(filter(_is_plugin_class,
                            module.__dict__.values()))

The numbered arguments for str.format could be left out.

Looks good otherwise.  If you're really concerned with keeping the
internals safe you could also not expose the plugins list directly,
but provide a separate accessor instead.


You asked:

  ... am I properly handling memory leaks by declaring [weak self] when I create a new Image instance?

By using [weak self], yes, you are preventing a strong reference cycle.

By the way, you can always use the “Debug memory graph” feature to confirm whether you have any strong reference cycles. See this answer for information about this feature.

  Should I set the closure handler to nil after it executes?

As a general rule, yes,

You should make the handler an optional:

var handler: ((Image) -> Void)?

and
Set it to nil after calling it:

if propertiesAreSet() {
    handler?(self)
    handler = nil
}

The idea is, just in case the caller neglected to use the [weak self] pattern, this will resolve any accidental strong reference cycles. It is a defensive programming approach that minimizes the chances of unresolved strong reference cycles (and also minimizes the chance of introducing a bug that will call the closure multiple times). But this is not used in lieu of [weak self], but rather in conjunction with it.

  Is what I am doing ok or am I violating any Swift principles?

Your code works, but is brittle. (This isn’t a “Swift principle” but rather a generally programming one.) For example, these two types are too tightly coupled: What if Image is extended at some future date to have some additional property that can’t be nil? You have to remember to go back to the other types that instantiate Image and make sure you update them accordingly, too, or else you might not see images loaded into your UI at all.

Setting that aside, I’d also suggest that the fact that the handler is called when those two properties are set isn’t very obvious. You really have to carefully read the code of both types to reason about what’s going on.

I’d refactor this, simplifying your model object, the Image, and putting the retrieval logic in the controller.

E.g.

var images = [Image]()

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    // assignment of closure
    var cellImage = Image()
    let group = DispatchGroup()

    group.enter()
    session.loadObjects(ofClass: NSURL.self) { urls in
        cellImage.url = urls.first as? URL
        group.leave()
    }

    group.enter()
    session.loadObjects(ofClass: UIImage.self) { images in
        if let image = images.first as? UIImage {
            cellImage.aspectRatio = Double(image.size.height / image.size.width)
        }
        group.leave()
    }

    group.notify(queue: .main) { [weak self] in
        guard
            let self = self,
            cellImage.url != nil,
            cellImage.aspectRatio != nil  else { return }

        self.images.append(cellImage)
        self.collectionView.insertItems(at: [IndexPath(item: self.images.count - 1, section: 0)])
    }
}

// in ImageGallery.swift
struct Image {
    var url: URL? = nil
    var aspectRatio: Double? = nil
}

A few other observations:

Notice that above, rather than reloading the whole collection view, you can just reload the new cell.
The above code snippet begs the question as to whether you really should be creating a Image first and retrieving its properties later, or whether you should retrieve the necessary data, and when you have what you need, only then instantiate and return the Image object. It’s hard to get too specific here without more information about this loadObjects method, why it’s taking multiple calls to retrieve the image details, etc. I don’t think we want to get into that level of detail here, but I only mention this as something you should think about as you work on the broader design of your app.
If your reaction to my code snippet above is “gee, I really don’t like adding all of this code to the view controller”, that’s a good intuition. Often, as apps scale, we like to pull this sort of logic out of the view controller and put it in some other object (perhaps a “view model”, perhaps a “presenter”, perhaps “network controller” ... there are lots of ways to skin the cat). But the goal is to limit our view controllers to configuring and responding to views, in the spirit of the “single responsibility principle”. This will make it easier for us to reason about our code and improve its testability (e.g. we want to test our business logic without worrying about collection view behaviors).

This is a pretty complicated topic and is beyond the scope of this question but the stretch objective is to keep view controllers as minimal as possible. But I might refer you to these sources to get you thinking about these concepts:

Dave DeLong is an advocate for not giving up on MVC, but being more prudent in its use. See A Better MVC.
Medium has an old survey of some of the MVC alternatives that you’ll see bandied about including MVP, MVVM, VIPER, etc. See iOS Architecture Patterns.


Determine if a point is inside or ouside of an irregular shape on a bitmap

If shape on bitmap is not filled and only one shape present on bitmap:
Start at point (x,y). For each of the four directions (left, right, top, bottom), keep going until either IsBitIsOn is true or a border of the bitmap has been reached. In the former case, point is in shape. Else (if border of bitmap reached), point is not in shape.
Pseudocode:
def IsInTheShape(x, y):
  curr_x = x
  curr_y = y
  # Check left
  while curr_x >= -1:
    if (curr_x == -1):
      return false
    if IsBitIsOn(curr_x, y):
      break

  curr_x = x
  curr_y = y
  # Check right
  while curr_x <= bitmap.width + 1:
    if (curr_x == bitmap.width + 1):
      return false
    if IsBitIsOn(curr_x, y):
      break

  # Check top
  # Check bottom

  # All directions hit IsBitIsOn, so must be in shape
  return true

If shape on bitmap is not filled and one or multiple shapes are present on bitmap:
Same as above, but once an outline has been reached, check all connected outline pieces recursively until the starting point has been reached. If the traversal around the outline visits all of the other outlines from the other three directions, then point is inside shape.
If shape on bitmap is filled:
Suppose that we want to check if (x,y) is in shape. Let (x,y) be cell E in the following grid:
+---+---+---+
| A | B | C |
+---+---+---+
| D | E | F |
+---+---+---+
| G | H | I |
+---+---+---+

Case 1 (point trivially not in shape):

Point is not in shape if E is off: if not IsBitIsOn(E): return false

Case 2 (point not in shape):

Point is not in shape if any of the 8 surrounding bits around E is off:

if not (IsBitIsOn(A) and IsBitIsOn(B) and IsBitIsOn(C) and IsBitIsOn(D) and IsBitIsOn(F) and IsBitIsOn(G) and IsBitIsOn(H) and IsBitIsOn(I)): return false

Case 3 (point in shape):

Point is all of the 8 surrounding bits around E is on:

else: return true

All together, the pseudocode is:
if not IsBitIsOn(E):
  return false
else if not (IsBitIsOn(A) and IsBitIsOn(B) and IsBitIsOn(C) and IsBitIsOn(D) and IsBitIsOn(F) and IsBitIsOn(G) and IsBitIsOn(H) and IsBitIsOn(I)):
  return false
else:
  return true


Insert Model object effectively using entity framwork

Entity

public partial class TblCustomer

The Tbl prefix belongs in the database, if it belongs anywhere at all. You have plenty of ways with Entity Framework, to map an entity type to a specific table, there's no need to carry database design mistakes into the code. Also entity types don't need to be partial.
One way could be to use annotations:
using System.ComponentModel.DataAnnotations.Schema;

[Table("TblCustomer")]
public class Customer
{
}

Another way could be to use the fluent API in the OnModelCreating method override of your DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>().ToTable("TblCustomer");
}

The most verbose way would be to create an EntityTypeConfiguration class:
public class CustomerMap : EntityTypeConfiguration<Customer>
{
    public CustomerMap()
    {
        ToTable("TblCustomer");
    }
}

And then to load that configuration into the model builder:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new CustomerMap());
}

You'll probably want to prefer convention over configuration, so simple data annotations should do the trick.

This comment:

public int CustomerId { get; set; }  //Primary key Identity

Doesn't need to exist. Entity Framework understands [EntityName]Id as your primary key (also just Id works), by convention - the mapping is automagic.
If you prefer it to be explicit (/by configuration) you can, again, use data annotations:
[Key()]
public int CustomerId { get; set; }

..or configure it in OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>().ToTable("TblCustomer");
    modelBuilder.Entity<Customer>().HasKey(e => e.CustomerId);
}

..or configure it in an EntityTypeConfiguration class:
public class CustomerMap : EntityTypeConfiguration<Customer>
{
    public CustomerMap()
    {
        HasKey(e => e.CustomerId);
        ToTable("TblCustomer");
    }
}

And then to load that configuration into the model builder:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new CustomerMap());
}

The comment doesn't add anything new, and at worst it could be just a lie (because if you're using configurations the entity type itself doesn't know which property is a key). I'd just remove it.

ViewModel

#region Bindable Properties

Don't. Any property that is public is bindable. This comment/region can only turn into an eventual lie. Remove it.

using(var context=new R_MaizeEntities())

R_MaizeEntities is an awful name for a type. Syntax highlighting doesn't even pick it up as a C# type name, that's a sign. I don't know what the R_ stands for, and I'm pretty sure it's meaningless - the type should be named MaizeEntities or MaizeContext.
One problem you have in your ViewModel, is that you can't test it without hitting the database and actually performing a save: your ViewModel is strongly coupled with everything you're newing up in that class.
Think of it: anything the ViewModel is newing up, is a dependency. If it makes sense for the ViewModel to be tightly coupled with specific commands, being tightly coupled with a specific data context makes your code pretty much untestable.
I would either constructor-inject the context (as an abstraction), or constructor-inject a context factory (as an abstract factory) whose job would be to instantiate a data context - and unit tests can inject a stub factory that instantiates a mock context for testing purposes.

The CustomerName property should be using _customerModel - it being null wouldn't result in a NullReferenceException at runtime, only as a silent binding error that you wouldn't be getting if _customerModel was constructor-injected instead of being new'd up in the property getter.

I think there might be a bug here:
_saveCommand = new RelayCommand(() => Save());

Looks like the command should be calling the SaveCustomer() method. Or there's a Save() method somewhere else?

RaisePropertyChanged doesn't follow naming conventions: if the method does what it says it does, it should be named OnPropertyChanged.
Raising a PropertyChanged event is surely something that's common to all your ViewModel classes. Why not write a ViewModelBase abstract class, and shove the property-changing logic in there? See this post for some ideas, more specifically about referring to property names in a strongly-typed manner.


I see a number of things that may help you improve your code.

Fix your formatting

The code as posted has inconsistent indenting which makes it hard to read.  Choose a particular style and apply it consistently to make your code easier to read.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Validate the input

Nothing in the code currently prevents the user from entering a list size of 3000 or -98.  The main routine should validate the input size and reject numbers that are not within range.

Don't use std::endl if you don't really need it

The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Simplify boolean expressions

The code currently contains this:

if (f == 0)
    return (true);
else
    return (false);

However, since the == operator already returns a bool, you can simplify this to a single line:

return f == 0;

Also note that return is not a function and does not need parentheses.  Similarly within main, we have this:

bool v = strictlyEqual(list1, list2, size);
if (v == true)
    cout << "identical" << endl;
else
    cout << "not identical " << endl;

But one could instead write this:

if (strictlyEqual(list1, list2, size)) {
    std::cout << "identical\n";
} else {
    std::cout << "not identical\n";
}

Or perhaps this:

std::out << (strictlyEqual(list1, list2, size) ?  "" : "not ")
        << "identical\n";

Read the problem statement carefully

The problem says that the size is not part of the array, but your program inserts the size as the first element of the array.  Instead, you could read the size from the user and store it in a separate variable that is passed to the strictlyEqual function.  Also note that as the current code is written, if the two lists are not of equal size, the program prints nothing.

Make sure your arguments match

The declaration of the function in the current code is this:

bool strictlyEqual(int const list1[], int const list2[], int size);

but the actual defintion has this:

bool strictlyEqual(int x1[], int x2[], int n)

First, if the function is defined before use, there's no need for a separate declaration at all.  Second, if you do have a separate declaration, make sure that everything matches, including const and the parameter names.  Strictly speaking, it's not an error to have different parameter names, but it can be confusing to readers of the code, so it's generally best to have them match. A difference in const, however, modifies the signature of the function

Think more carefully about the algorithm

Because only one size is passed to the function, it seems that we must assume that the two arrays are of equal size.  (I'd say this is a flaw in the question, but presumably out of your control.)  Given that, the function only returns true if all elements are equal, so the simple way to do that would be this:

bool strictlyEqual(const int list1[], const int list2[], int n) {
    for (int i=0; i < n; ++i) {
        if (list1[i] != list2[i]) {
            return false;
        }
    }
    return true;  // we only get here if every element was equal
}

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


I found a case where the solution #3 doesn't work : when you're dealing with scroll bars.

In your example, if you put a container smaller than the content, the scrollbar behave strangely in RTL, scrolling right when you press the left arrow and vice versa.

The same thing happen when you press the mouse's middle click and move to any horizontal direction.


Binding data to a ComboBox and then showing ValueMember in another TextBox

It looks pretty clean. As far as I can tell, you have a good separation of concerns. Everything is properly cased and your functions have verb-noun names. All good things.

The only nitpick I have is the bs variable. I'm not a fan of ultra short names of any kind. You could call it source or some such thing. Seriously though, that's a huge nitpick. I just couldn't find anything else to comment on.


Data declarations

Your data types are not large enough.  By the C standard, an int is only guaranteed to hold up to 32767, which is smaller than 100000.  Similarly, an int could be insufficient to hold the values of A, B, and M.  You'll need a long long or int64_t.

A big block of declarations like this is not ideal:

unsigned int n, i, j, k, h,count=0,l=0;

You should declare variables as close to the point of use and in as tight a scope as possible.
Single-character names are cryptic.

Algorithm

You don't have to simulate a kangaroo, counting hops, to answer these questions.  The answer will be roughly

$$\frac{B - A}{M}$$

… except that you have to take care of fencepost (off-by-one) errors at the edges.  I'll leave it to you to figure out the details.


Overall

You don't use encapsulation. Which makes your list vulnerable to incorrect initialization and accidental incorrect modification from outside the list.

You use several C based style choice rather than C++ style which make your codde harder to read.

Code Review

Only a list of int?

class Node {
    public:
        int value;          // int only
        Node* next = NULL;
};

Passing a pointer to a pointer. You can simplify this by passing a reference.

void push(struct Node** head_ref, int new_data)

In C++ you don't need to use struct keyword when using struct types.

void push(struct Node** head_ref, int new_data)

A better declaration would have been:

void push(Node*& head_ref, int new_data)

C++ you should always use new (rather than the malloc family).

    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));

There are two reasons for this:

If your code combines both C and C++ memory allocation you need to track which is which and use the correct de-allocation method. Thus it is best to simply use one allocation method then you always know how to deallocate it.
Using new calls the constructor to initialize the object.
Remember this line from your class declaration.

    Node* next = NULL;

This is not going to happen if you call malloc() you must use new to get that to happen.

Its also simpler to write:

Node* new_node = new Node{new_data, *head_ref};

Your find returns the nth index of the list. But your index is 1 based. Most C based languages use a zero based index. But if I pass 0 to find() this function will recurse for ever.

In recursive funtions always check for the end of the recursion first. So as the first check in find you should check that the list pointer is not nullptr.

This is not modified.

    int count = 1;

So this should be a constexpt. The whole point of using a named type is to make the code more expressive. A better name would help the code be more expressive.

Don't leave redundant code commented out. Delete it.

    //if count equal too n return node->data

Source control system allow you to keep older versions of the code around

It is now easy to install git on all machines learn to use it.

Use better indentation

    if(count == n)
    return head->value;

In C++ we use nullptr rather than NULL.

    struct Node* head = NULL;

The difference is that nullptr is correctly typed as a pointer, while NULL is a macro (bad) for an integer (bad type). Thus you can not incorrectly use nullptr while NULL can be abused.

In C++ we use the C++ streams std::cout.

    printf("Element at index 3 is %d", find(head, 3));

The C++ streams have a more advanced type checking system that prevents accidents.

    std::cout << "Element at index 3 is " << find(head, 3);

Beter implementation

template<typename T>
class LinkedList
{
    struct Node {
            T value;
            Node* next;
    };
    Node*   root;

    public:
        LinkedList()
            : root(nullptr)
        {}
        ~LinkedList() {
            while(root) {
                Node* next = root->next;
                delete root;
                root = next;
            }
        }
        LinkedList(LinkedList const&)            = delete;
        LinkedList& operator=(LinkedList const&) = delete;

        void push(T const& new_data)
        {
            root= new Node{new_data, root};
        }

        int find(int n)
        {
            Node* result = findElement(root, n);
            if (result == nullptr) {
                throw std::runtime_error("message");
            }
            return result->value;
        }
    private:
        Node* findElement(Node* n, int n) {
            if (n == nullptr) {
                return nullptr;
            }

            if (n == 0) {
                return n;
            }
            return findElement(n->next, n-1);
        }
}

Main.cpp

int main()
{
    LinkedList<int> list;

    list.push(1);
    list.push(4);
    list.push(1);
    list.push(12);
    list.push(1);

    std::cout << "Element at index 3 is " << find(head, 2) << "\n";
    getchar();
}


Parallel and Sequential array looping with async/await

JavaScript's execution model

  My understanding is that the first one is parallel because the await applies to each invocation of the async lambda that is passed to map.

This is not quite right since JavaScript (i.e. ECMAScript) is not multi-threaded.

Simply speaking, the VM executing the code has a queue from which it dequeues an action (e.g. "run this file") and executes it. This is done ad infinitum. It runs every dequeued element either to completion, to a yield (in generator functions), an await (in async functions) or an iterator.next() (on a generator function).
The only way your code can be interfered with (preempted) is using these statements. But even then no parallelism is created, the VM just switches the current queue item it is processing, e.g. to the caller of iterator.next() when the generator function just yielded a value.

I recommend you to read Concurrency model and Event Loop on MDN, which explains it in more detail and formally better than I can off the top of my head :)

The effects of the execution model

Endless loops cannot be avoided

The following code will print Processed 1 and then hang in the endless loop.

await [1, 2, 3].forEachParallel(async (element: number) => {
  if (element === 2) {
    while (true);
  }
  else {
    console.log('Processed ' + element);
  }
});

Your forEachParallel will call Array#map, which will iterate the array's elements one-by-one and apply (i.e. call, not await!) the passed function on it. It is now useful to mentally desugar your passed function from the aync/await syntactic sugar:

async (item: any) => await func(item)
// <=> (just return the Promise)
async (item: any) => func(item)
// <=> (an async function without awaits does not need to be async anymore)
(item: any) => func(item)

After desugaring, it is now apparent that this is the reason why Array#map will hang on the second iteration.

forEachParallel vs. forEachSequential

  In contrast, the await in the sequential function applies to the outer function, so each iteration of the for loop will block, and the next iteration will only occur once the previous one completes.

Exactly!

forEachSequential guarantees that func will be called and completed in-order on the array elements. In contrast, forEachParallel guarantees as well that func will be called in-order on the array elements, but not that they complete in-order, too!

await [1, 2, 3].forEachParallel(async (element: number) => {
  console.log('Processed ' + element);
});

The code above might print:

Processed 3
Processed 1
Processed 2

Whereas the following code will always print 1, 2, 3 in-order:

await [1, 2, 3].forEachSequential(async (element: number) => {
  console.log('Processed ' + element);
});

// This will print 1, 2, 3 as well, necessitating 1000ms for *each*
// element.
await [1, 2, 3].forEachSequential(async (element: number) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('Processed ' + element);
      resolve();
    }, 1000);
  });
});

Quiz: forEachParallel with timeouts

Will the following code hang? If yes, where does it happen (in map, in await Promise.all(), in neither)? What does it print?

await [1, 2, 3].forEachParallel(async (element: number) => {
  setTimeout(() => {
    if (element === 2) {
      while (true);
    }
    else {
      console.log('Processed ' + element);
    }
  }, 0);
});

   Processed 1 will be printed and then the program will hang.

 setTimeout(..., 0) immediately adds the function to the end of the VM's queue (see the MDN link above). Since Array#map works sequentially on all elements, the VM's queue will look like
 [current: forEachParallel] | setTimeout from first element | setTimeout from the second element | setTimeout from the third element

 Actually, I am not really sure where it will hang. I suppose it might happen in forEachParallel (because await Promise.all(...)) will pave the way for the execution of the setTimeout callbacks (and thereby escpecially for the second one) or it might happen after forEachParallel has entirely completed its execution. Note that the promise returned by the function passed to it are resolved directly at the end through the implicit return, not in the setTimeout callback!

Design Suggestions

I would opt to not use async for the function you pass to Array#map:

await Promise.all(this.map(async (item: any) => await func(item)));

The first time I read the code, I thought: "Is this really the Array#map function which is passed an async function? But how should that work? Array#map does not deal with async functions, or does it?"

Put another way, I usually expect functions getting async functions passed as arguments to be aware of them and deal with them in a special way. Here, you are just using the fact that Array#map accepts a general and generic (element: T) => U function, where you happen to instantiate U with Promise<void>.

You can also leave out the type annotation, this results in the following line:

await Promise.all(this.map(item => func(item));
You are correctly using the generic type inside the Array interface, that's good!
In the implementation, however, you are leaving them out and thus lose type safety in the implementation. The code still benefits from the interface type safety, though.
I am not entirely sure about the best practices on this, but simply annotating the implementation as well worked flawlessly for me:

Array.prototype.forEachParallel = async function<T>(this: Array<T>, func: (item: T) => Promise<void>): Promise<void> {
  // TypeScript now correctly infers the result from this.map
  await Promise.all(this.map(item => func(item)));
};

Array.prototype.forEachSequential = async function<T>(func: (item: T) => Promise<void>) {
  /* ... */
};


Implementation of a Resizing Array Queue

The code does not compile cleanly.  Use @SuppressWarnings("unchecked") if necessary.

$ javac -Xlint:unchecked ArrayQueue.java
ArrayQueue.java:8: warning: [unchecked] unchecked cast
    private E[] a = (E[]) new Object[1];
                          ^
  required: E[]
  found:    Object[]
  where E is a type-variable:
    E extends Object declared in class ArrayQueue
ArrayQueue.java:26: warning: [unchecked] unchecked cast
        E[] temp = (E[]) new Object[cap];
                         ^
  required: E[]
  found:    Object[]
  where E is a type-variable:
    E extends Object declared in class ArrayQueue
2 warnings

This test would crash:

public class ArrayQueueTest {
    public static void main(String[] args) {
        ArrayQueue<Integer> q = new ArrayQueue<>();
        q.enqueue(1);
        for (Integer n : q) { System.out.println(n); }
    }
}

1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
  at ArrayQueue$ArrayIterator.hasNext(ArrayQueue.java:93)
  at ArrayQueueTest.main(ArrayQueueTest.java:5)


This is a partial review.

$file_loc and $json_folder

Use $json_folder in the construction of $file_loc. If you decide to use a different folder, you need change two variables.

$file_loc = "{$json_folder}/twitter.json";

Naming of function

You named your function get_twitter_json()... which... does essentially nothing. It does not return json like the function name suggests. It doesn't even return the twitter result. Instead this seems a partial implementation of a processing function. If it is supposed to return tweets, then name at least something like get_tweets().

Whitespace

Use consistent whitespace. Trying to align all assignments to the same indentation will create problems sooner than later. Changing one assignment will mess up the rest. Multi-line assignments will look even weirder. I would recommend 1 space before the assignment operator (=) and one space after it.

$results and $tweets

The if-else-statement should have some code behind it. The if-statement loads the decoded json-file in $results, while the else-statement loads it in $tweets. Use one of them.

While you are at it, while php allows you to use $tweets undefined like that, it doesn't make for clear code.

foreach with a counter

You are using a foreach loop with a custom counter. That... defeats the purpose of a foreach loop. Either use a for loop and use the exposed counter from that, or use the append syntax to don't need a counter.

foreach($results as $tweet) :
    $new_tweet = array();
    $new_tweet['created']      = $tweet['created_at'];
    $new_tweet['text']         = $tweet['text'];
    $new_tweet['username']     = $tweet['user']['name'];
    $new_tweet['screenname']   = $tweet['user']['screen_name'];
    $new_tweet['url']          = $tweet['user']['url'];
    $tweets[] = $new_tweet;
endforeach;


Playability
I ran your game to test it out first, and noticed something odd when a letter is found twice in the same word, such as "glass" here:

Pick a letter
 A
You guessed correctly!
['-', '-', 'a', '-', '-']
Pick a letter
 s
You guessed correctly!
['-', '-', 'a', 's', '-']
['-', '-', 'a', 's', 's']

I'm not sure if that is by design, but as a player I find it odd that it's displayed twice. I found where it originated in the code:
for x in range(0, length_word): #This Part I just don't get it
    if secretWord[x] == guess:
        guess_word[x] = guess
        print(guess_word)

If you just unindent print(guess_word) by two levels, you'll avoid that behavior since it won't run in a loop:
for i in range(0, length_word):
    if secretWord[i] == guess:
        guess_word[i] = guess
print(guess_word)

Printing a raw array like ['-', '-', 'a', 's', 's'] is a bit confusing, at first I didn't know what it was for until I guessed one right and saw the results. So let's make it print something more friendly:
print("Word to guess: {0}".format(" ".join(guess_word)))

Pick a letter
 o
You guessed correctly!
Word to guess: - o -

Much better! But it will get a bit clunky to type all that each time, so let's make a utility function for it and we can use it for the print(guess_word) at the beginning of a game too.
def print_word_to_guess(letters):
    """Utility function to print the current word to guess"""
    print("Word to guess: {0}".format(" ".join(guess_word)))

Then we just print_word_to_guess(guess_word) whenever we need it. It would also be possible to make an optional different message but default to Word to guess:, but I'll leave that for you as a challenge.

The game also doesn't ever tell me anything about how many chances I have left, so I'm left guessing (literally) until I figure it out. That's very easy to make a small utility function to do:
def print_guesses_taken(current, total):
    """Prints how many chances the player has used"""
    print("You are on guess {0}/{1}.".format(current, total))

Then a few code additions:
def guessing():
    guess_taken = 1
    MAX_GUESS = 10
    print_guesses_taken(guess_taken, MAX_GUESS)

    while guess_taken < MAX_GUESS:

And:
for i in range(0, length_word):
    if secretWord[i] == guess:
        guess_word[i] = guess
print_word_to_guess(guess_word)
print_guesses_taken(guess_taken, MAX_GUESS)

Your list of words is pretty limited, for future consider perhaps looking for a text file online with a whole bunch of words and just read a random one from it, that would bring more variety!

Code Improvements
main function
You run all your game functions as soon as you make them. It would make more sense to put them inside the __main__ function:
if __name__ == "__main__":
    beginning()
    newFunc()
    change()
    guessing()

By the way, newFunc() doesn't work well as a name, as it says nothing about what it does. Something like ask_user_to_play() would be much better.

Constants naming
Python doesn't have real constants, but nevertheless, it's good practice to name variables that shouldn't change (by change I mean reassigned to a different values) in ALL_CAPS_WITH_UNDERSCORES. A simple find & replace in an IDE or text editor does the trick to fix your whole script.
GUESS_WORD = []
SECRET_WORD = random.choice(wordList) # lets randomize single word from the list
LENGTH_WORD = len(SECRET_WORD)
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

Docstring
It's a good habit to add a docstring to all functions, classes, and modules, to describe for other programmers what the code in question is for. I've done that for the above 2 utility function.

Type hints
Since Python 3, you can now use type hints for your function and method signatures, and use static code analysis tools. This also makes the code easier to read for humans.

Improved code
Here is what I came up with,applying all of the above, and improving the spacing (yours had too many blank lines everywhere). There are likely other things that could be improved, but this should be a good start.
import random, sys
from typing import List

# TODO try to load these from a text file
WORD_LIST = [
"lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop",
 "laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat"
           ]

GUESS_WORD = []
SECRET_WORD = random.choice(WORD_LIST) # lets randomize single word from the list
LENGTH_WORD = len(SECRET_WORD)
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

# Utility functions

def print_word_to_guess(letters: List) -> None:
    """Utility function to print the current word to guess"""
    print("Word to guess: {0}".format(" ".join(letters)))

def print_guesses_taken(current: int, total: int) -> None:
    """Prints how many chances the player has used"""
    print("You are on guess {0}/{1}.".format(current, total))

# Game functions

def beginning() -> None:
    """Starts the game"""
    print("Hello Mate!\n")
    while True:
        name = input("Please enter Your name\n").strip()
        if name == '':
            print("You can't do that! No blank lines")
        else:
            break

def ask_user_to_play() -> None:
    """Ask user if they want to play"""
    print("Well, that's perfect moment to play some Hangman!\n")
    while True:
        gameChoice = input("Would You?\n").upper()
        if gameChoice == "YES" or gameChoice == "Y":
            break
        elif gameChoice == "NO" or gameChoice == "N":
            sys.exit("That's a shame! Have a nice day")
        else:
            print("Please Answer only Yes or No")
            continue

def prepare_secret_word() -> None:
    """Prepare secret word and inform user of it"""
    for character in SECRET_WORD: # printing blanks for each letter in secret word
        GUESS_WORD.append("-")
    print("Ok, so the word You need to guess has", LENGTH_WORD, "characters")
    print("Be aware that You can enter only 1 letter from a-z\n\n")
    print_word_to_guess(GUESS_WORD)

def guessing() -> None:
    """
    Main game loop to have user guess letters
    and inform them of the results
    """
    guess_taken = 1
    MAX_GUESS = 10
    print_guesses_taken(guess_taken, MAX_GUESS)

    while guess_taken < MAX_GUESS:
        guess = input("Pick a letter\n").lower()
        if not guess in ALPHABET: #checking input
            print("Enter a letter from a-z ALPHABET")
        elif guess in letter_storage: #checking if letter has been already used
            print("You have already guessed that letter!")
        else:
            letter_storage.append(guess)
            if guess in SECRET_WORD:
                print("You guessed correctly!")
                for i in range(0, LENGTH_WORD):
                    if SECRET_WORD[i] == guess:
                        GUESS_WORD[i] = guess
                print_word_to_guess(GUESS_WORD)
                print_guesses_taken(guess_taken, MAX_GUESS)
                if not '-' in GUESS_WORD:
                    print("You won!")
                    print("Game Over!")
                    break
            else:
                print("The letter is not in the word. Try Again!")
                guess_taken += 1
                print_guesses_taken(guess_taken, MAX_GUESS)
                if guess_taken == 10:
                    print(" Sorry Mate, You lost :<! The secret word was {0}".format(SECRET_WORD))

if __name__ == "__main__":
    beginning()
    ask_user_to_play()
    prepare_secret_word()
    guessing()


When I had to create an XML file for one of my projects, I basically created a class for each element and passed along a class that contained all the data I needed to use in the XML.

It started with this class:

internal sealed class XmlCreator
{
    public static XElement Execute(RequestConfig requestConfig)
    {
        return ImportElementCreator.Execute(requestConfig);
    }
}

Which in turn used this class:

internal sealed class ImportElementCreator
{
    public static XElement Execute(RequestConfig requestConfig)
    {
        var element = new XElement("Import");

        element.Add(PersElementCreator.Execute(requestConfig));

        return element;
    }
}

etc etc etc. I'm sure you get the point.

Part of the reason was that the resulting XML file could differ, depending on the action in the request: an "Update" required more data than a "Delete", and thus some classes contained some logic:

    public static XElement Execute(RequestConfig requestConfig)
    {
        var element = new XElement("Access-Rule",
            new XAttribute("id", requestConfig.Position ?? 1),
            new XAttribute("operation", requestConfig.RequestType.ToString().ToLowerInvariant())
            );

        if (requestConfig.RequestType != RequestType.Update)
        {
            return element;
        }

        element.Add(RuleElementCreator.Execute(requestConfig.AccessRuleId));

        element.Add(StartDateElementCreator.Execute(requestConfig.StartDate));

        element.Add(EndDateElementCreator.Execute(requestConfig.EndDate));

        return element;
    }

The downside is that you might end up with a lot of small classes if you have a complicated XML file, and that you need to look out for duplicate class names.

Of course, if you look at XmlCreator, you end up with an XElement, not an XML file.

To actually write the XML file, I had this:

internal sealed class FileWriter
{
    private readonly string _localDirectory;
    private readonly XmlWriterSettings _xmlWriterSettings;

    public FileWriter(string localDirectory)
    {
        _localDirectory = localDirectory;

        _xmlWriterSettings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = false,
            Encoding = _idTechConfiguration.Encoding
        };
    }

    public string Execute(RequestConfig requestConfig, XElement content)
    {
        var xmlDirectory = Path.Combine(_localDirectory, "xml");
        Directory.CreateDirectory(xmlDirectory);

        var filePath = Path.Combine(xmlDirectory, GetFileName(requestConfig));
        using (var xmlWriter = XmlWriter.Create(filePath, _xmlWriterSettings))
        {
            content.WriteTo(xmlWriter);
        }

        return filePath;
    }

    private string GetFileName(RequestConfig requestConfig)
    {
        return string.Format("{0}_{1}_{2}_{3}_{4}.xml",
            requestConfig.ApplicationName,
            requestConfig.RequestType,
            requestConfig.UserData,
            DateTime.Now.AsYyyyMmDdDashed(),
            DateTime.Now.AsHhMmSsDashed());
    }
}


I tend to advocate not passing things around which need to be closed, thus my advice is:

inline the read method
remove the reader field, and
... declare the same as a local variable
perferably, declare that local reader variable in a try-with-resources block and throw out the explicit close()-call

Note that these changes are just about robustness and maintainability and will not affect performance or error handling.

Edit, after the comment asking for code edit. (Note: sorry, I am a newbie in the code review community, I hope this does not break any principle here.)

public class FileReader {

    private String path;
    private List<String> linesList;
    private Set<List<String>> splitLinesSet;

    public FileReader(String path) {
        this.path = path;
    }

    public boolean readFile() {

        this.splitLinesSet = new HashSet<>();
        File file = Paths.get(path).toFile();

        try (
            CSVReader reader = new CSVReaderBuilder(new java.io.FileReader(file))
                    .withCSVParser(new CSVParserBuilder()
                            .withSeparator('|')
                            .withFieldAsNull(CSVReaderNullFieldIndicator.NEITHER).build())
                    .build();
            ) {
            String[] lines;
            while ((lines = reader.readNext()) != null) {
                linesList = new ArrayList<>();
                Collections.addAll(linesList, lines);
                splitLinesSet.add(linesList);
            }
        } catch (IOException e) {
            System.err.println("Error in reading CSV: " + e.getMessage());
            return false;
        }

        return true;
    }

    public Set<List<String>> getSplitLinesSet() {
        return splitLinesSet;
    }
}

Note: this was just syntactic shuffling of lines in a text editor - I have not put this through an IDE or a compiler, but I think it shows the principles.


foreach(var c in Path.GetInvalidPathChars())
    path = path.replace(c, '_')

That's a bit inefficient as it can allocate a string on every itteration, but usually not a problem. Alternative:

var chars = Path.GetInvalidPathChars()
path = new string(path.Select(c => chars.Contains(c) ? '_' : c).ToArray())


Expression tree creation from postfix expression

Make your structs immutable
TreeNode is a helper structure, with public members, which is fine, but you better make them final, so you know they won't be changed after the object is created.

Choose your validations
Don't throw NullPointerException on your own. It may confuse a future debugger. Either throw an IllegalArgumentException or let the runtime throw the NullPointerException for you.

Choose your comments
Most of your comments do not add much to the methods, and are therefore redundant. Let the names of the method and variables do the work for you. If you feel the name prefix is not clear enough on its own, it is better to rename it (maybe to toPrefixNotation()) and then you can safely remove your comments.

Being nice is better than being strict
Unless there is some requirement restriction, I don't think you need to throw an exception if root is null - why not simply call createExpressionTree() instead of telling the developer he should?
Since there is no meaning for calling createExpressionTree() twice (postfix is final...), you might as well hide it altogether, and call it when needed.

Use the power of String
Use String#indexOf to make isOperator more succinct:

private boolean isOperator(char c) {
    return "+-*/".indexOf(c) != -1
}


How to apply multiple filters in one statement

Nope, that's pretty much the way.
If you really, really want to make this shorter and less cluttered, and if you face similar situations multiple times in your codebase, you could make yourself a special operator for combining predicates:
let (.&&.) f g c = f c && g c

Then you can use this operator in your filter:
|> Seq.filter (needSpecialDocument .&&. wantToMoveTo)

But base on my own experience I wouldn't advise this. You make the program slicker and cooler looking, but you're losing some readability. Now whoever reads your program will have to look up the meaning of .&&.. Programs are read more often than they are written.


Listing files whose names match a pattern with a date

Firstly some tips:

Your code uses a mixture of snake_case and camelCase, you should stick to a specific style. If you're going to write python, PEP8 states snake_case should be used as the expected style.
Your code lacks a if __name__ == "__main__": starting section. It's recommended to have this. As an example, if you don't have this, when you use tools like Sphinx to produce code documentation, it will actually run your code instead of just building the objects. Also, it's kind of expected :-)

As to the core questions you have, you can use pathlib's Path object to assist with the globbing of files and matching file parameters, as well as the string formatting format function to replace "placeholders" with a certain value. For instance:

from pathlib import Path

def get_path_list(directory, base_filename_list, saved_as_of):
    for template in base_filename_list:
        file_date = template.format(saved_as_of)
        print(f"looking for {file_date}")
        files = Path(directory).glob(file_date)
        for file in files:
            print(str(file))

if __name__ == "__main__":
    today = "2018-07-25"
    files_market = ['apples_{}.xml', 'peaches_{}.xml', 'cucumbers_{}.xml', 'potatoes_{}.xml', 'tomatoes.{}.csv']
    get_path_list(".", files_market, today)

The code above will get you 90% of the way there, but I'll leave that as an exercise for you to complete.

Good Luck!


Efficient smart pointer implementation in C++

So the idea behind this is mainly educational...

Cool. Always good to try and understand how things work under the covers.

  ...but I might even consider using it in reality if turns out to be good.

Please rethink this. Smart pointer implementations are incredibly difficult to get right. Scott Myers, of Effective C++ fame, famously tried to implement a shared_ptr. After feedback from something like 10 iterations, it was still wrong.

Let's go through a few things here.

smart_pointer(T* p = NULL)
  : pointer(p), refs(new std::size_t(1))

This constructor should be explicit to avoid implicit type conversions through construction.

Your operator=(T* p) leaks. Here's a small example:

int main()
{
    int *x = new int(5);
    {
        smart_pointer<int> sp(x);
        sp = new int(6);
    } // sp destroyed here

    std::cout << *x << "\n"; // This should have been deleted but wasn't
}

To convince yourself that this is the case, modify your clear() method:

void clear(){
    if (!--*refs){
        std::cout << "deleteting " << *pointer << " at " << pointer << "\n";
        delete pointer;
        delete refs;
    }
}

This will print out "deleting 6 at <some memory address>".

Here's just a small rundown of what boost::shared_ptr (or std::shared_ptr) provides that is missing here:

Constructors allowing a Deleter, which is used instead of a raw delete.
Constructor allowing construction from <template Tp1> shared_ptr(Tp1 * ...) where Tp1 is convertible to type T.
Copy constructor allowing construction from a shared_ptr with convertible template type <T1>.
Copy constructor taking weak_ptr, unique_ptr.
Move constructor and assignment operator.
Usage of nothrow where it is required to be.
reset, which will replace the currently managed object.
All the non-member operators like operator<, operator==, etc that allow containers and algorithms to work correctly. For example, std::set will not work correctly with your pointer class, neither will things like std::sort.
A specialization of std::swap.
A specialization of std::hash. Your pointer class won't work correctly with std::unordered_set or std::unordered_map.
explicit operator bool conversion for nullptr tests, so that one can write if (<some_shared_ptr>) { ... }.
Utility functions like std::make_shared which you should pretty much always use when creating a shared_ptr.

The big pain point, and the reason why boost::shared_ptr or std::shared_ptr will be slower is the fact that they are thread-safe. Your smart_ptr when accessed by multiple threads could very easily delete the pointer it holds before another class is done with it, leading to dereferencing of a deleted object, and thus undefined behaviour. Furthermore, all of the atomic operations are specialized for shared_ptr.

The above is not an exhaustive list.

I don't write this to discourage you, but merely to try and reinforce the fact that writing something like this is a lot of work. It is very technical, and really, really easy to get wrong. In terms of the standard library, shared_ptr may be one of the most difficult things to write correctly.


Perhaps use some strategies to counter CSRF as well. Take a look at this comprehensive guide: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet


I want to write code like this:
  setBackground(theme.game.screenBackground) instead of
  setBackground(theme.game().screenBackground())

Read this : http://c2.com/cgi/wiki?AccessorsAreEvil

The URL is misleading, it is a 'balanced' article, the part I want you to pay particularly attention is this:

  The examples [...] they are really structures (data), not quite
  objects.

Your theme class should really be a structure, and be too simple to have getters.

In response to @bowmore, the Theme should not be responsible for loading resources, the theme should really return resource identifiers.

If it were me, by the way, I would probably go for

game.drawBackground()

where game knows what the theme is, and gets from theme the resource name for the background which a loader class then loads and a UI class then displays.


Find the index of the element with maximum absolute deviation

Note that in Python 3, you don't need * 1.0 to get floating-point division.  On the other hand, in Python 2, range(len(A)) would use O(N) space.

I recommend three changes:

Put the special case first, to reduce the separation between return -1 and the reason for returning -1.
Rename max_avg → max_deviation.
Use enumerate() to iterate over the array.

The revised solution would be:

def solution(A):
    if not A:
        return -1
    average = sum(A) * 1.0 / len(A)
    max_deviation = 0
    pos = 0
    for i, a in enumerate(A):
        if abs(a - average) > max_deviation:
            max_deviation = abs(a - average)
            pos = i
    return pos