Class creating dropdown options from MySQL data for multiple scripts

For such a use case a class would be rather useless. A class is used to encapsulate the stuff that belongs to just a single matter. Here, there is nothing in common between these functions.

If you want to use a class, consider creating a class related to Skills, with one of its methods responsible for returning a list of skills.

but if you want to just refactor your code, a set of functions will do as well. Make your PopulateDropdown.php as

function skillSelect($category){
    //query to db to get skills
    return $skillArray;
} //end function

function groupSelect($category, $mem_type, $selected_group=NULL){

// query to get list of clients
    return $grpArray;
} //end function

function facilitySelect($selected_group){
    //query to get list of facilities associated with a $selected_group
        return $facArray;

} //end function

and then

require '../appwpclass/PopulateDropdown.php';
$skillsArr = skillSelect($category);
$groupArr = groupSelect($category, $memType, $selGroup);
$facilityArr = facilitySelect($selGroup);

So you will have the desired functionality without a single class.

You may also want to create another helper function, to reduce the amount of duplicated code,

function show_option($array, $selected) {
    foreach( $array as $id => $name ) {
        $selected = ( $id == $selected ) ? ' selected' : '';
        ?>
        <option value="<?= $id ?>"<?= $selected ?>><?= $name ?></option>
        <?php
    }
}

which will make your HTML much cleaner

<select name="selGroup" id="selGroup" size="1" class="textfield" onchange="submit()">
    <option value="0">--Any--</option>
    <?php show_option($groupArr, $selGroup); ?>

  So I thought about just using them in a "require" somewhere in each script, but I'm thinking there has to be a better OOP way

Well, to use some function or a class you must require them, this way or another. Although classes could be autoloaded, you have to require the autoloader definition anyway. So, although there are other ways, your current approach is good enough.


SICP exercise 1.3 - sum of squares of two largest of three numbers

First of all, the name sum-of-squares is misleading.  Longer names-separated-with-hyphens are quite acceptable in Scheme, so why not tell the whole truth?  I suggest sum-of-squares-except-min or sum-of-squares-of-greatest-two.

The first solution is a bit of a brute-force approach.  It works, but it is not obvious at a glance how it works unless you trace all paths of the decision tree.

The second solution, if the indentation and naming were improved, would be a bit clearer.

(define (sum-of-squares-except-min a b c)
    (let ((max-of-bc (if (> b c) b c))
          (max-of-ac (if (> a c) a c)))
         (if (> a b)
             (+ (square a) (square max-of-bc))
             (+ (square b) (square max-of-ac)))))

Personally, I would adapt the second approach and go "all the way" with it.  Then, all the possibilities would be laid out logically, one per line.

(define (sum-of-squares-except-min a b c)
    (let ((least (min a b c)))
         (cond ((= least a) (+ (square b) (square c)))
               ((= least b) (+ (square a) (square c)))
               (else        (+ (square a) (square b))))))

min should be built in, but you can implement it as a helper function yourself if you need to.

Alternatively, sum all the squares, then subtract the square of the least.

Which approach is fastest?  It's hard to say, without benchmarking, whether it's better to define fewer intermediate variables, do less branching, or do less arithmetic.  I wouldn't worry about performance for such a simple problem.


Style

In Java it is common practice to have class names to use PascalCase (a.k.a. UpperCamelCase). Also the name spaceship doesn't make sense to me and is confusing. Also, why is the instance called kling?

Readability

I prefer to prefix my formal parameters with a for argument, for example aInputArray. I believe it would help readability of your code.

Please prefer descriptive names. Currently I have no idea what x, co and res are.

Nested for loops

You are basically implementing a multi-byte counter. You can do something like this (not tested, but you get the idea):

boolean incr(int[] co, int max, int min, int pos){
     if(co[pos] + 1 > max){
         co[pos] = min;
         if(pos == 0)
              return false;
         return incr(co, max, min, pos - 1);
     }
     else{
         co[pos]++;
         return true;
     }
}

void solveAll(){

    int[] co = new int[len];
    while(incr(co, bestFound, 1, co.length - 1)){
       res = solve(co);
    }
}

Performance

Lets look at solve(int[] in). You're using HashSet which is fast as long as you don't get excessive collisions. Seeing as you are dealing with many numbers that are possibly small, you could be having many hash collisions. If profiling indicates this is the case, you can try a better hash function (for example multiply by a large prime number).

Here:

int[][] arr = new int[size][size];

you allocate space for the whole triangle but you only ever use the last two rows. So you only need to store two rows and alternate between them. This has the added benefit that both rows will be hot in cache all the time, avoiding cache misses as you go from line to line. It will also avoid some extra indirections in your inner most loop.

Better algorithm

The first thing we need to realize is that the problem is kind of recursive (I can't remember the proper term off the top of my head).

What I mean by that is that if a base {a,b,c} for n=3 crumbles, then the all bases {a,b,c,x} for any x will also crumble. This means that by solving the easier problem n=3 we get information about a lot of combinations for n=4 that will crumble.  (1)

The second thing to realize about this problem is that if {a,b,c} crumbles, then {c,b,a} will also crumble. And if {a,b,c} doesn't crumble and has top value x then {c,b,a} will also not crumble and have the same top value x. (2)

The third thing is that for the base {a,b,c} the top value will be strictly larger than a+b+c. This is a useful stopping condition. (3)

Knowing the above, you have to unrestrainedly search for the combination of n base elements that produces the smallest top value as result. Use a greedy search for the smallest top value and terminate when all the nodes remaining fulfil (3).

The difficult part is to generate the nodes to be searched. This can be done effectively by starting with small n and then combinatorially incrementing the base elements and adding an additional base element to create triangles with n+1 base for any triangle that doesn't crumble. This exploits (1) to prune large sets of crumbling triangles from the start.

One should also take care to not generate symmetry pairs to triangles that have already been tried to exploit (2).

It is useful to store the base and right edge of the triangle in addition to a  HashSet of all the values in the triangle.

I.e. for the triangle:

      20
    8   12
  3   5   7
1   2   3   4

store:

1   2   3   4 (base row)

and

4   7   12   20 (right edge, bottom -> up).

Using the right edge, we can quickly calculate any expansion of this triangle. For example:

1   2   3   4   10

is easily calculated as:

       53
      20 33
        12 21
          7  14
            4  10

if we have the right edge.

I hope this helps. It's an interesting problem.


Initiating an action based on product type

You have a conditional based on the type of object. You can apply the Replace Conditional with Polymorphism refactoring pattern.

In this case, you might have a base class Product, with subclasses DigitalProduct and PhysicalProduct which each implement discount(). I don't think it's sensible to have a MembershipProduct class - membership should be related to the buyer. From an OO perspective, it should feel wrong when you have methods like discount_for_X() - the method should be part of the respective class so that you can make use of polymorphism.


From a once over,

I strongly suggest lowerCamelCase: sticky_footer -> stickyFooter, screen_height -> screenHeight etc. etc.
You should compare to undefined with === or use a falsey comparison, I would suggest the falsey comparison:

if(header && footer && content) {

This: var elem_id = id; makes no sense to me, why not simply keep working with id ?
If you are going to return the sum of all 6 css values (return prop_padding+prop_margin+prop_border; ), then I would not use the temporary values but just return the actual calculation
Do not use console.log in production code
That gives something like this:

//Returns the sum of float values of padding-top/bottom,margin-top/bottom, border-top/bottom,
//if no element is provided, returns 0
var sum_of_top_bottom_props = function(id){
    if(id && id.length){
        return parseFloat(elem_id.css('padding-top')) +
               parseFloat(elem_id.css('padding-bottom')) +
               parseFloat(elem_id.css('margin-top')) +
               parseFloat(elem_id.css('margin-bottom')) +
               parseFloat(elem_id.css('border-top-width')) +
               parseFloat(elem_id.css('border-bottom-width'));
     }
     return 0;
}};

else return false is pointless, just do return false
Finally, you require the user of your script to take care of $(window).resize(function(){, your script should take care of that instead.


Find minimum number of coins (count and list of coins too)

Here are some things that I would maybe do in another way:

replace Integer.MAX_VALUE by Int.MaxValue
replace cascade if-else statements by pattern matching
return value of Int.MaxValue replaced by throwing an IllegalArgumentException
try to make recursive functions tail-recursive and use the @tailrec annotation
maybe use Seq instead of List. IMHO you can use List as a concrete implementation for Seq. I am not 100% sure in this case that there won't be additional overhead (e.g. by creating unnecessary collection objects). Read about scala's collection API.
Maybe you would like to simplify the whole thing by writing just on top-level function def minimumCoins(amount: Int, availibleCoins: Seq[Int]): Seq[Int]. It returns the coins as solution. An empty Seq means you need no coins. You can easily get the number of coins by the size of the Seq. There can be cases where no solution exists! What should happen in those cases? Maybe an ecxeption should be thrown again. Or was that the sense of the boolean return value? Maybe you wrap the returned Seq with an Option like Option[Seq[Int]].
I did not really spend time understanding your algorithm. If that is what you want you should tell it explicitly. Anyway some collections have combinatorical functions like mySeq.combinations(5) and mySeq.permutations which can be useful for such problems. If you have an specific analytic algorithm (from your brain or from anywhere else) it is probably better and more efficient than those based on those functions. Those functions tend to solve problems by something like brute-force. So the code used for this may be of little amount and you get something useful quickly and with less analytics. You can be more productive and let the computer do the work. On the other side, processing all combinations or permutations can be very inefficient especially on large parameters their number gets quickly very very high. Those functions are alluring.


Your solution works, but it will be quite slow. For every element in your matrix (m*n many), you check if it is the maximum in the row (n comparisons), and then check if it is the minimum in the column (m comparisons). This will mean that you do a total of m*n*(m+n) many comparisons. You can save some time by only computing the maximum and minimum once, going down to m*n + m + n.

Also, MATLAB hates for loops. Built-ins are optimized and can take advantage of any hardware acceleration or parallelism that your computer offers. Loops on the other hand are always executed sequentially. If you can avoid them and use built-ins instead, it will usually make your code faster.

function [row, col]=saddle(matrix)

% first lets get the min/max for the column/row respectively
minima = min(matrix,[],1) % minimum of each column
maxima = max(matrix,[],2) % maximum of each row

% then, for each element in the column/row check if it matches the min/max
isMinimum = minima == matrix
isMaximum = matrix == maxima

% it needs to be both to be a saddle
saddles = isMinimum & isMaximum

% lastly, figure out the index of each saddle point
% and transform it to the desired output format
[row, col] = find(saddles)

Disclaimer: My MATLAB licence expired this week and I have to wait to renew it. The above code is untested, so there might be the odd typo.


Make a version of make-rat that handles positive and negative arguments

To normalize a fraction, one needs to do two things:

fix the signs of numerator and denominator; and
reduce them to their lowest terms.

Your implementation does these two things just fine.  However, there is an easier way.  To do (1), simply negate both numerator and denominator if the denominator is negative.  To do (2), divide by the greatest common divisor.

One could combine the two steps above.  Divide the numerator and denominator by the greatest common divisor with its sign fixed to be the same as the denominator's sign.  Implementation follows:

(define (make-rat n d)
  (let
      ((div ((if (< d 0) - +) (abs (gcd n d)))))
    (cons (/ n div) (/ d div))))

If gcd always returns a positive number (which your implementation does not), you may remove the call to abs above.


Binary file validity in C++/C++11: checking a binary header

The most unforgivable fault with this function is that calling isValidBuffer() also erases the buffer! That completely violates the Principle of Least Surprise. If anything, the parameter should be const.


I'm not sure about what makes your code slow, but first I should point out some ways to improve its readability. Actually, it should help you to think about your code complexity to make it more readable, since performance in complex nested loops and such things is really difficult to evaluate.

To begin with a detail, I believe that:

std::for_each(v.begin(), v.end(), [&k](auto& x){x%=k;});

isn't the most readable. When you iterate over the whole container, the "range-based" for is better:

for (auto& x : v) x %= k;

unless you want to make your intent yet more apparent with the transform algorithm:

std::transform(vec.begin(), vec.end(), vec.begin(), [k](auto&& i) {return i%k;});

More importantly, I think you should dissociate traversal and counting, because it makes for a code very difficult to read. Why don't you make it in two steps:

// first step: counting modulo populations
std::map<int, int> counter;
for (auto elem: v) ++counter[v%k];

// second step: traversing different modulos
auto no_duplicates = std::unique(vec.begin(), vec.end());
std::for_each(vec.begin, no_duplicates, [](auto etc) { do_something(etc); });

A last point, you can put the two special cases out of the way early, instead of dragging them along until the end. So deal with multiples of k and k/2 at the first occasion, it also allows you to get rid of a certain number of elements.

To sum it up, here's my suggestion:

int nonDivisibleSubset(int k, std::vector<int> vec) {
    // 1. check for multiples of k, multiples of half of k, and retain only one of each
    int res = 0;
    auto multiples = std::remove_if(vec.begin(), vec.end(), [k](auto&& i) { return i%k == 0; });
    if (multiples != vec.end()) ++res;
    auto half_multiples = std::remove_if(vec.begin(), multiples, [k](auto&& i) { return 2*(i%k) == k; });
    if (half_multiples != multiples) ++res;
    // 2. for each possible modulo-complementary couple, choose the one with the most occurrences
    std::transform(vec.begin(), half_multiples, vec.begin(), [k](auto&& i) {return i%k;}); // calculate modulos
    std::sort(vec.begin(), half_multiples);
    std::map<int, int> mods; // count their occurrences
    std::for_each(vec.begin(), half_multiples, [&mods](auto&& i) {++mods[i];});
    // and then examine each possible couple
    auto uniques = std::unique(vec.begin(), half_multiples);
    auto bottom_up = vec.begin();
    auto top_down = std::reverse_iterator<std::vector<int>::iterator>(uniques);
    while (bottom_up < top_down.base()) {
        if (*bottom_up + *top_down == k) { // complementary
            res += std::max(mods[*bottom_up], mods[*top_down]);
            ++bottom_up, ++top_down;
        }
        // if not complementary advance the closest from its origin
        else if (*bottom_up < k - *top_down ) {
            res += mods[*bottom_up++];
        }
        else res += mods[*top_down++];
    }
    return res;
}

P.S: I've tried to submit that code and it passes correctly.


Simple Cookie Service - Returns value of cookie based on cookie name passed in

Re using reduce(): There are many Javascript programmers who like to find clever ways to use this method, and your pattern is probably popular among them. I'm not one of them. I would use forEach() instead, and assign to this.cookies[key] within it. But if you like reduce(), that should be fine; it's a common enough pattern that you shouldn't have to worry about other programmers not understanding it.

However, there's a bug in the way you're using reduce(). The callback function has to return a result every time, but your function only returns in the if block. You should move return cookies; outside the if.

You have some unnecessary code when expanding currentValue.
String.prototype.split always returns an array of strings, so it's not necessary to test if typeof cookie[i] == "string". And once you have tested this, it's not necessary to use String(cookie[i]). You don't have to go overboard on defensive coding.

When returning the cookie, you can simplify the code. It's not necessary to test the value and then return false if it's not truthy; you can simply return the value, and if it doesn't exist you'll return undefined, which is just as falsey as false. And rather than test specifically for typeof this.cookie == "undefuned", you can just test if the property is truthy (if you want to be really defensive, you could go the other way and test whether it's actually an array).

Since you're using other EcmaScript 6 features, you could use destructuring of the split() assignment, rather than referring to cookie[0] and cookie[1] repeatedly. Then you can simplify the validation checks -- all the invalid values are also falsey, so if (key && value) will suffice.

export class CookieService {

    // Constructor
    constructor(){

        // Initialize the cookie service
        this.init()
    };

    // Holds the resulting cookies object after init is run
    cookies: any;

    // Initializes the cookie service by getting all cookies on the document and creating an object that holds each cookie by name in a key/value pair
    init: Function = () => {

        // Get the document cookie
        this.cookies = document.cookie

            // Split it on the ";" character to get each individual cookie in an array
            .split(";")

            // Reduce the array into an object
            .reduce(

                // Pass in the cookies object and the current value to the reduce callback function
                ( cookies, currentValue ) => {

                    // Split the cookie into key and value
                    let [key, value] = currentValue.split("=");

                    // Sanity check to make sure we got two values from the split and each value has a length.  Filters out malformed cookies.
                    key = key && key.trim();
                    value = value && value.trim();
                    if ( key && value ){

                        // Set the new cookie on the cookies object
                        cookies[key] = value;

                    }

                    // Return the updated cookies object
                    return cookies;

                }, {}
            )
    };

    // Gets a cookie from the cookies object
    getCookie: Function = cookieName => {

        // If we have a cookies array, and the requested cookie exists, return it
        return this.cookies && this.cookies[cookieName];

    }
}


Designing object oriented clean code structure with spring services

I would inject the converterservice into ShoppingList and implement an add() function, which adds an element to the ShoppingList after conversion.
void add(name, ingredient, unit) {
    IngredientQuantity toAdd = this.converterService.convert(name, ingredient, unit); // terrible naming, todo!
    this.ingredients.add(toAdd);
}

Now the shopping list is the owner of conversion which (arguably) is modelling real life. When I need to shop for milk, I convert the American recipes to litres instead of ounces or whatever.
This also simplifies your last lambda function, you just need to iterate over the keyset and call ShoppingList::add, which is Java8+ method ref syntax.
The other huge lambda should probably also be split into parts, I mean, I love functional java as much as anyone, but I believe this is cutting the line of functional utility over readability.
Pseudocode
foreach Recipe:
    foreach Ingredient : Recipe
        compute(ingredient)

These are my 2 cents.


You're doing things quite the hard way. You don't need to call sqrt, or determine perfect squares at all. Simply track y, and as soon as the row's x == y, make a newline, increment y and set x = 0.

The following examples show different results from what you've described:

import java.io.StringWriter;
import java.lang.Math;

class Pyramid {
    interface ChartMethod {
        abstract void run(int n);
    }

    static boolean isPerfectSquare(int n){
        int root = (int) Math.sqrt(n);
        return root * root == n;
    }

    static void chart_squares(int maxValue) {
        int number = 1;
        while (number <= maxValue) {
            System.out.print(number + " ");

            /* A number n can be determined to be triangular iff
             8n+1 is a perfect square;  if n is a triangular number,
             print a line after it*/
            if (isPerfectSquare(8*number + 1))
                System.out.println();
            number++;
        }

        System.out.println();
    }

    static void chart_coords(int maxValue) {
        int number = 1, y = 0, x = 0;
        while (number <= maxValue) {
            System.out.print(number + " ");

            if (x == y) {
                x = 0;
                y++;
                System.out.println();
            }
            else
                x++;

            number++;
        }
        System.out.println();
    }

    static void chart_coordloop(int maxValue) {
        int number = 1;
        for (int y = 0;; y++) {
            for (int x = 0; x <= y; x++) {
                System.out.print(number + " ");
                if (number++ >= maxValue) {
                    System.out.println();
                    return;
                }
            }
            System.out.println();
        }
    }

    static void chart_incr(int maxValue) {
        int increment = 2, next = 1;
        for (int number = 1; number <= maxValue; number++) {
            System.out.print(number + " ");
            if (number == next) {
                next += increment;
                increment++;
                System.out.println();
            }
        }
        System.out.println();
    }

    static void chart_buf(int maxValue) {
        StringWriter sw = new StringWriter();
        int increment = 2, next = 1;
        for (int number = 1; number <= maxValue; number++) {
            sw.write(number + " ");
            if (number == next) {
                next += increment;
                increment++;
                sw.write('\n');
            }
        }
        System.out.println(sw.toString());
    }

    static final ChartMethod[] methods = new ChartMethod[] {
        Pyramid::chart_squares,
        Pyramid::chart_coords,
        Pyramid::chart_coordloop,
        Pyramid::chart_incr,
        Pyramid::chart_buf
    };

    static void test(ChartMethod method) {
        method.run(7);
    }

    static void time(ChartMethod method) {
        long start = System.nanoTime();
        final int N = 200000;
        method.run(N);
        long dur = System.nanoTime() - start;

        System.err.println(String.format("%.3f us", dur / 1e3 / N));
    }

    public static void main(String[] args) {
        for (ChartMethod method: methods)
            time(method);
    }
}

This shows:

1.381 us
1.196 us
1.157 us
1.140 us
0.234 us

The most important thing is to buffer the output before writing.


In the case of linked lists, the pointer to the next value should be a pointer to another Node instance, not a pointer to another data entry. This would allow you to walk the entire list node-by-node.

You have defined methods for using a stream to read/write the node's value, but what if I just want to access the value do something else with it that doesn't involve a stream? A getter like T& getValue(); and/or const T& getValue() const should be mandatory. This will also allow you to extract the stream operators outside of the class and be able to implement them without friend.

When it comes to templates T is preferred as the typename insteam of tNode which can be easily mistaken for a specific class instead of a template.


Implement a blocking counter with a reader/writer lock

You are really writing C
C++ has its own language specific features to handle multi threading.
Your interface is broken.
The only way to test the value of the counter is via GetCount() but by the time you can use the value the counter may have changed.
 Thread1                      Thread2                    Thread3
 if (b.GetCount() == 0) {     if (b.GetCount() == 0) {   if (b.GetCount() == 0) {
     b.Increment();                b.Increment();             b.Increment();
     // I have the lock.
     Do stuff                      Do stuff                   Do stuff
 }                            }                          }

As you can see your mechanism does not stop all three threads from doing something. The only real use for the counter is to print the count (and even that may not be accurate but at least it wont break anything).


Enforcing C# Task to exist only once at any given point of time for a given ID

What's the point of _continuations? I can see three options which use a single dictionary:

Just store and return concreteTask. If this fails because the continuation is GC'd, document this for the benefit of maintainers.
Just store and return the continuation. If this fails because the continuation is executed multiple times, document it.
Store the task and return the continuation, so the first caller has the hard reference. I can't think how this could fail unless the caller actively discards the task.

TL;DR: if there are obvious ways of simplifying the code which break for non-obvious reasons, document the reasons so that the maintainer doesn't break it.

A further advantage of using a single dictionary would be that you could use ConcurrentDictionary instead of the manual locking. (In fact you could do this even if you do need both copies of the task, using ConcurrentDictionary<string, Tuple<Task, Task>>). The code might be as simple as

    public class TaskManager : ITaskManager
    {
        private readonly ConcurrentDictionary<string, Task> _tasks = new ConcurrentDictionary<string, Task>();

        public Task<T> ExecuteOnceAsync<T>(string taskId, Func<Task<T>> taskFactory)
        {
            var task = _tasks.GetOrAdd(
                taskId,
                id => taskFactory().ContinueWith(_ => _tasks.TryRemove(taskId, out var _)));
            return (task as Task<T>) ??
                throw new Exception($"Task with id {taskId} already exists but it has a different type {task.GetType()}. {typeof(Task<T>)} was expected");
        }
    }

I would like to add: I like the level of detail in the exception message. That should be very helpful in tracking down bugs if it is thrown and logged.


This code works well but it's using too many slow operations to get the values.

Not sure what really bugs you:

You read the entire file with a single Files.readAllBytes. Doesn't get faster than that. If the file is huge, I imagine this could take time, but if you want the entire file, there's just no way around it
You convert the byte[] to a String so that you can use a Pattern + Matcher. The alternative I see would be parsing the digits by yourself, but that wouldn't be as optimized as the built-in regex engine, so you won't be better off
I imagine the number parsing and Integer object creation might cost you a couple of extra cycles. But I don't see an alternative to make that significantly faster

My point is, if you want to read and parse the entire file,
and store the result in a List,
then I don't think it can get much faster than this.

  Is there a way to improve the code?

When a method is expected to return a List or other collection type,
it's good to avoid returning null values,
as that forces the caller to add null checks.
A more ergonomic solution is to return an empty list,
for example Collections.emptyList().

Code is usually easier to read when not so deeply nested.
The majority of the method is nested within a if (myFile.exists()) { ... } block.
If you flip this condition and return early, you can reduce the nesting level.

It's better to declare variables in the most limited scope where they are used.
In this example the byte[] fileBytes is only used if the file exists,
so you could declare it later.

Putting these tips together, the method body becomes:

List<Integer> list = new ArrayList<>();
File myFile = new File("/proc/net/sockstat");
if (!myFile.exists()) {
    return list;
}

byte[] fileBytes;
try {
    fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
    return list;
}

if (fileBytes.length <= 0) {
    return list;
}

String doc = new String(fileBytes);

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(doc);

while (m.find()) {
    list.add(Integer.valueOf(m.group()));
}

return list;

Also, the convention is to put opening braces on the same line as their statement,
not on the next line as you did (C# style).

Finally, the variable names are kind of fishy.
Single letter names like p and m are considered a bad practice,
and doc doesn't seem to give a clue about what this variable is about.

Alternative approach

Although as I wrote above,
if you want to read and parse a large file it's bound to be slow,
but there's a different approach that might still help.

Instead of reading the entire file at once (time-consuming),
you could read part of the file and return results as you go.
You could do this using the iterator pattern:

Create a class that implements the Iterator interface
Use an internal buffer to store the next chunk of the file
When hasNext is called, check if there is still data left in the buffer, or read in the next chunk
When next is called, return the next integer

This approach has the following advantages over the original:

Instead of waiting for the entire file to be processed, users of the iterator can start processing sooner. That is, when you read the entire file at once, it may seem to the user that the program freezes for a couple of seconds. If you process chunk by chunk, this doesn't happen
If the user of the iterator stops in the middle, the rest of the file won't be read and parsed unnecessarily
Since the integers don't need to be stored in a list anymore, you can reduce the memory use dramatically

Potential disadvantages:

More work to implement. (Or, you could play with a Scanner)
If you always need to read in the entire file, then it will be more efficient to do it once and be done with it, like the original code


Localisation

The strings are in Spanish

Great! However, that's not the only thing in Spanish: your variables (elegir_magnitud, unidad_temperatura, etc.) are as well.
This is non-ideal for at least a couple of reasons:

Python, being a language whose syntax is written in English, conflicts with your code that is then a mixture of English and Spanish. This is inconsistent.
For better or worse, the de-facto language of software development is English. Particularly for international collaboration or online open-source development, it is important to use a language that is accessible to more people.

It's a wonderful thing to apply internationalization (i18n) to your strings, but it should be to your strings only, and not the code.
Factor out common code
Consider refactoring your code to:

Have only one method that asks for units, called twice (once for source unit and once for destination unit)
Make a tuple of coefficient-offset pairs. These represent the linear function from the given unit to Kelvin and back. This will only need two unit conversion formulae, rather than (worst-case) 2^n with the current strategy.

Bug?
Are you sure that this works?
cantidad_temperatura % 9*5 -32

I doubt that modulus is the right thing to do here. You should be using division /.
Example code
Notes:

This does a rough i18n, with some strings from Google Translate (so my apologies for the likely poor Spanish).
Only English and Spanish are implemented but any other language can be added.
This assumes that your operating system is set to the correct locale
For these purposes, only the ISO639-1 language without country code is considered
Enums are used for stricter type assurance
Type hints are used for better static analysis and documentation
I have not bothered to add the complexity of input validation, so if input is invalid, there will be an exception thrown
Note the use of locale methods rather than direct int and float construction and formatting

strings.py
from locale import getlocale, getdefaultlocale

# For testing only
# from locale import setlocale, LC_ALL
# setlocale(LC_ALL, 'es_ES.UTF8')

def get_lang() -> str:
    lang, _ = getlocale()
    def_lang, _ = getdefaultlocale()
    return (lang or def_lang)[:2]

LANG = get_lang()

if LANG == 'en':
    DIMENSIONS = (
      'Temperature',
      'Length',
      'Mass',
      'Volume',
      'Time',
      'Currency',
    )
    TEMP_UNITS = (
      'Kelvin',
      'Celsius',
      'Fahrenheit',
    )
    ENTER_NUMBER = 'Enter the desired number: '
    CHOOSE_TEMP_SOURCE = 'Choose the source temperature unit to convert: '
    CHOOSE_TEMP_DEST = 'Choose the destination temperature unit to convert: '
    PROVIDE_TEMP = 'Provide the source temperature: '
    RESULT = 'The result of the conversion is:'

elif LANG == 'es':
    DIMENSIONS = (
      'Temperatura',
      'Longitud',
      'Masa',
      'Volumen',
      'Tiempo',
      'Divisa'
    )
    TEMP_UNITS = (
      'Kelvin',
      'Centígrada',
      'Fahrenheit'
    )
    ENTER_NUMBER = 'Entra número deseado: '
    CHOOSE_TEMP_SOURCE = 'Elija la unidad de temperatura fuente para convertir: '
    CHOOSE_TEMP_DEST = 'Elija la unidad de temperatura de destino para convertir: '
    PROVIDE_TEMP = 'Proporcionar la temperatura de la fuente: '
    RESULT = 'El resultado de la conversión es:'

convert.py
from enum import Enum
from locale import format_string, atof, atoi
from typing import TypeVar, Type, Iterable

from strings import *

class Dimension(Enum):
    TEMPERATURE = 1
    LONGITUDE = 2
    MASS = 3
    VOLUME = 4
    TIME = 5
    CURRENCY = 6

class TempUnit(Enum):
    KELVIN = 1
    CELSIUS = 2
    FAHRENHEIT = 3

# To get from this unit to Kelvin:
# kelvin = m * this_unit + b
TEMP_PARAMETERS = {
    # This unit       m  b
    TempUnit.KELVIN: (1, 0),
    TempUnit.CELSIUS: (1, 273.16),
    TempUnit.FAHRENHEIT: (5/9, 273.16 - 5/9*32),
}

InputEnum = TypeVar('InputEnum', bound=Enum)

def enum_from_input(t_enum: Type[InputEnum], labels: Iterable[str]) -> InputEnum:
    print(
        '\n'.join(
            format_string('%d = %s', (enum.value, label))
            for enum, label in zip(t_enum, labels)
        )
    )
    result = t_enum(atoi(input(ENTER_NUMBER)))
    print()
    return result

def main():
    dimension = enum_from_input(Dimension, DIMENSIONS)
    if dimension != Dimension.TEMPERATURE:
        raise NotImplementedError()

    print(CHOOSE_TEMP_SOURCE)
    source = enum_from_input(TempUnit, TEMP_UNITS)
    print(CHOOSE_TEMP_DEST)
    dest = enum_from_input(TempUnit, TEMP_UNITS)

    temp1 = atof(input(PROVIDE_TEMP))

    # Use a simple linear transformation where y = mx + b; first convert to
    # the base unit (Kelvin)
    m, b = TEMP_PARAMETERS[source]
    kelvin = m*temp1 + b

    # Now calculate inverse to the destination unit
    m, b = TEMP_PARAMETERS[dest]
    temp2 = (kelvin - b)/m

    print(format_string('%s %.1f', (RESULT, temp2)))

if __name__ == '__main__':
    main()

Example output
1 = Temperatura
2 = Longitud
3 = Masa
4 = Volumen
5 = Tiempo
6 = Divisa
Entra número deseado: 1

Elija la unidad de temperatura fuente para convertir:
1 = Kelvin
2 = Centígrada
3 = Fahrenheit
Entra número deseado: 3

Elija la unidad de temperatura de destino para convertir:
1 = Kelvin
2 = Centígrada
3 = Fahrenheit
Entra número deseado: 2

Proporcionar la temperatura de la fuente: 81
El resultado de la conversión es: 27,2


Use collections.defaultdict to "bucketize" the items in your list. Then collect the buckets to get the desired result.
from collections import defaultdict

bucket = defaultdict(list)

for record in lst:
    bucket[record['name']].append(record)

lst_new = list(bucket.values())


Here are a few things:

container.__len__() – You should never call magic methods directly. Just use len(container).
As you don’t know to what amount you need to increment (i.e. your COUNTTO), it would make more sense to have a while loop that keeps iterating until you reach your final length result:

while length < 1000:
     # do stuff with i
     length += # update length
     i += 1

You could also make use of itertools.count:

length = 0
for i in itertools.count(1):
    length += # update length
    if length > 1000:
        break

not i % 100 == 0 – When you already have a operator (==) then don’t use not to invert the whole condition, but just use the inverted operator: i % 100 != 0
Also having additional counting logic outside of your num2eng does not seem to be appropriate. What does that function do exactly? Shouldn’t it rather produce a real number using a complete logic? Ideally, it should be as simple as this:

length = 0
for i in itertools.count(1):
    length += len(num2eng(i))
    if length > 1000:
        break


You are doing twice the work by having a function to get the starting row and a second function get the last row.  Passing the starting row into the GetLastRow() function would be more efficient.

I prefer to have a single function return the range object.  Using the WorkshetFunction.Match() is far more efficient then iterating over the cells.

Results

getDateRange:Function

'Enumerations to clarify column data content
Public Enum DataColumns
    dcStocks = 1
    dcDates
    dcTimes
    dcValues
End Enum

' https://docs.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.match
Function getDateRange(ByVal StartDateTime As Date, ByVal EndDateTime As Date) As Range
    Const LargestValueGreaterThanOrEqualTo As Long = -1
    Const FirstExactMatch As Long = 0
    Const LagestValueLessThanOrEqualTo As Long = 1

    Dim Target As Range
    With ThisWorkbook.Worksheets(1)
        Set Target = .Range("A4:Z4", .Cells(.Rows.Count, dcDates).End(xlUp))
    End With

    Dim dates
    Dim RangeStart As Long, RangeEnd As Long
    Dim SearchValue As Double
    SearchValue = StartDateTime - 1
    On Error Resume Next
    RangeStart = WorksheetFunction.Match(SearchValue, Target.Columns(dcDates), LagestValueLessThanOrEqualTo)
    On Error GoTo 0

    If RangeStart = 0 Then Exit Function
    Dim r As Long
    Dim StartFlag As Boolean
    Dim DateTime As Date

    With Target
        For r = RangeStart To .Rows.Count
            DateTime = .Cells(r, dcDates).Value + .Cells(r, dcTimes).Value
            If DateTime >= StartDateTime And Not StartFlag Then
                RangeStart = r
                StartFlag = True
            End If

            If DateTime > EndDateTime Then
                RangeEnd = r - 1
                Exit For
            End If
        Next

        If r > .Rows.Count Then RangeEnd = .Rows.Count

        Set getDateRange = .Rows(RangeStart & ":" & RangeEnd)
    End With
End Function

Worksheet Test Preparation

Sub Prep()
    Const RowCount As Long = 260000
    'https://codereview.stackexchange.com/questions/226360/vba-loop-optimization
    Dim codes, dates, stocks, times, Values
    Dim d As Date, t As Date
    codes = Array("ACB", "AYI", "A2B", "ABP", "ABL", "AEG", "ABT", "AJC", "AKG", "AX8", "AX1", "ACS", "ACQ", "ACF", "ACR", "ACW", "AIV")

    ReDim stocks(1 To RowCount, 1 To 1)
    ReDim dates(1 To RowCount, 1 To 1)
    ReDim times(1 To RowCount, 1 To 1)
    ReDim Values(1 To RowCount, 1 To 1)
    Dim r As Long, r2 As Long
    d = #1/1/2010#
    For r = 1 To RowCount - 48
        d = d + 1
        For r2 = 0 To 47
            t = TimeSerial(0, r2 * 30, 0)
            stocks(r + r2, 1) = codes(WorksheetFunction.RandBetween(0, UBound(codes)))
            dates(r + r2, 1) = d
            times(r + r2, 1) = t
            Values(r + r2, 1) = Int((Rnd * 100) + 1) + Rnd
        Next
        r = r + r2 - 1
    Next
    Range("A4").Resize(RowCount) = stocks
    Range("B4").Resize(RowCount) = dates
    Range("C4").Resize(RowCount) = times
    Range("D4").Resize(RowCount) = Values
End Sub

Test

Sub Main()
    Dim Results(5) As String * 25
    Const TestCount As Long = 10
    Dim n As Long
    Results(0) = "Date Range"
    Results(1) = "StartDateTime"
    Results(2) = "EndDateTime"
    Results(3) = "MinPrice"
    Results(4) = "MaxPrice"
    Results(5) = "Time"
    Debug.Print Results(0), Results(1), Results(2), Results(3), Results(4), Results(5)
    For n = 1 To TestCount
        Test
    Next
End Sub

Sub Test()
    Dim Results(5) As String * 25

    Dim t As Double: t = Timer
    Dim Target As Range
    Dim d As Date, StartDateTime As Date, EndDateTime As Date

    StartDateTime = WorksheetFunction.RandBetween(#1/2/2010#, #8/30/2024#)
    EndDateTime = StartDateTime + TimeSerial(WorksheetFunction.RandBetween(1, 24) - 1, WorksheetFunction.RandBetween(1, 2) * 60, 0) + WorksheetFunction.RandBetween(1, 60) - 1

    Set Target = getDateRange(StartDateTime, EndDateTime)

    Dim MinPrice As Double, MaxPrice As Double
    MinPrice = WorksheetFunction.Min(Target.Columns(4))
    MaxPrice = WorksheetFunction.Min(Target.Columns(4))

    Results(0) = Target.Address
    Results(1) = StartDateTime
    Results(2) = EndDateTime
    Results(3) = MinPrice
    Results(4) = MaxPrice
    Results(5) = Round(Timer - t, 2)
    Debug.Print Results(0), Results(1), Results(2), Results(3), Results(4), Results(5)
    Target.Select
End Sub

CandleStick Chart

The dataset in the image shows that you need to know the Open, High, Low, and Close for each day to create the Chart.  Considering there are over 200 K rows, I presume that you will also need to filter by stock.  If this is true then I would take a different approach.

I would have a dictionary that stores a sub-dictionary for each stock that stores a dictionary for each day that stores an arraylist to store the values.

Create Array From Data Structure and Write it To New Sheet

Dim CandleStickData

ReDim CandleStickData(1 To RowCount, 1 To 6)
r = 0
For Each StockKey In StockMap
    Set DateMap = StockMap(StockKey)
    For Each DateKey In DateMap
        Set ValueList = DateMap(DateKey)
        r = r + 1
        rowData = ValueList.ToArray
        CandleStickData(r, 1) = StockKey
        CandleStickData(r, 2) = DateKey
        CandleStickData(r, 3) = rowData(0)
        CandleStickData(r, 4) = WorksheetFunction.Max(rowData)
        CandleStickData(r, 5) = WorksheetFunction.Min(rowData)
        CandleStickData(r, 6) = rowData(UBound(rowData))
    Next
Next

Worksheets.Add
Range("A1:F1").Value = Array("Stock", "Date", "Open", "High", "Low", "Close")
Range("A2").Resize(RowCount, 6).Value = CandleStickData
Debug.Print Round(Timer - t)

I did a quick mock up and it took 21 seconds to load 259,967 rows of data into the dictionaries and ArrayList and just 11 seconds to build a new Array and write it to a worksheet.  After the data has been processed, it would be a simply matter of getting the date range and updating the chart table.  Changing the stocks or chart data should take no more than 1 tenth of a second.


Checking if a directory is empty when having over a million files inside

Why is there a catch for a PDOException?  Also, why are you masking it with another exception?  That doesn't make much sense.  How is the final catch block supposed to know what it's actually catching?

Anyway, you need to use a lower-level method than scandir.  You could use a DirectoryIterator instance, but I would probably just go with opendir.

For example:

 function is_directory_empty($path)
 {
      $dir = opendir($path);
      while (($f = readdir($dir)) !== false) {
           if ($f !== '.' && $f !== '..') {
                return true;
           }
      }
      return false;
  }

The important part here is that the loop bails upon finding the first file.  Additionally, . and .. will usually be the first two entries, so it should only have to run 3 times at maximum (though that is implementation specific, I believe, since the dots are not required to be first -- if the dots aren't first, it would run at most twice for an empty directory and once for a non-empty one).

It's worth noting that this function has terrible error handling.  In particular, there's no way to know if the directory is empty or the opendir call failed.  You could throw an exception:

if ($dir === false) {
     //I chose UnexpectedValueException because it's what DirectoryIterator throws
     throw new UnexpectedValueException("Unable to open directory: {$path}");
}

Another way would be to take a more procedural, C-esque approach:

define('DIR_EMPTY', 0);
define('DIR_NOT_EMPTY', 1);
define('DIR_ERROR_OPEN', 2);

function is_directory_empty($path)
{
    $dir = opendir($path);
    if ($dir === false) {
         return DIR_ERROR_OPEN;
    }
    while (($f = readdir($dir)) !== false) {
         if ($f !== '.' && $f !== '..') {
              return DIR_EMPTY;
         }
    }
    return DIR_NOT_EMPTY;
}

$dir_empty = is_directory_empty("/some/path");
if ($dir_empty == DIR_EMPTY) {
    echo 'Empty!';
} else if ($dir_empty == DIR_NOT_EMPTY) {
    echo 'Not empty!';
} else {
    //(Should arguably be an else-if to check the last condition)
    echo 'Error opening path';
}

I would consider having your file-counting functionality, and your is-empty functionality be two separate functions.  There's a definite relation possible between them (is_empty(x) === !file_count(x)), but they're really different functionalities.

I'm not much a fan of a boolean flag changing the functionality of a function.  It's an anti-pattern in my opinion (and quite a few other people's opinion, though I'm too lazy to find links at the moment).

Instead, consider:

function count_directory_files($path)
{
    ...
}

function is_directory_empty($path)
{
    ...
}

The names clearly express the functionality.  There's no need for a magical flag.

directory_with_contents is a bit badly named to begin with, but if I had to guess what it does, I would guess that it returns true if a directory is empty, and false otherwise.  The counting-functionality is hidden.

(On the bad naming note: what does directory_with_contents mean?  Consider if you hadn't named it.  Could you look at that and know, with certainty, what it does?  I would imagine not.  In my opinion, functions that return booleans should typically be named as a binary predicate: is_<object>_<property>, can_<object>_<property>, etc.  [I'm actually a fan of camelCase, like, isDirectoryEmpty, but that's a superfluous opinion to this post :p.])


A few main points you should attempt to improve in this code:

Start using nullptr if you can (C++11). It is much better than the old NULL macro.
Never "use namespace" in a header file (Not sure if this is a header file? Doesn't seem like...). That would leak the imported declarations to every other place that included the header. Also be conservative about using namespace in a cpp file. Prefer to explicitly declare the things your are using (e.g.: using std::cout;) or don't do any of that and prefix everything with std::. It is not much more typing anyways. Further discussion here.
Properly initialize data in constructors by calling the constructors of the sub-objects:

Node(T dataNew)
    : data(dataNew)   // Better would be 'data(std::move(dataNew))' if C++11
    , lChildptr(NULL) // Better 'nullptr' if C++11
    , rChildptr(NULL) // Same here
{ }

#include <stdlib.h> is the C header file. For C++, use <cstdlib>.
Why this:

   Node *newData;
   newData= new Node(item);

Instead of just: Node * newData = new Node(item);?
PrintTree() would be more flexible if it took the output stream as a parameter. Also, consider providing the stream output operator << instead. It is the most idiomatic way of printing an object in C++.
Mind Const Correctness. PrintTree() is not mutating any member variables, so it should be const.
Your new allocated instances are never being freed and are leaking in your test code. If you are going to use dynamic memory, make sure to first attempt a smart pointer or a standard container. This will make your life a lot easier and your code a lot more bug-free. Side note: These local variables you've declared in main() have no reason for being pointers. They could very well be declared by value in the program stack.
A little inconsistency with naming: insertnode() is not following your PascalCase notation. As a side note, camelCase is more popular for method names (except for Windows-centric projects perhaps).


class BencodeObject:

Putting object inside Class names is generally not a good idea, because it doesn't tell me anything.

def __init__(self,filename):
    with open(filename,'rb') as diskbytes:
        self.loads(diskbytes)

def _isdictionary(self,bits): return(bits == b"d")

There is no need for the parens around the expression. They just clutter things

def _isnumber(self,bits): return(bits > b"/" and bits < b":")

That's a confusing way to express this. Instead use bits >= b'0' and bits <= '9'

def _iscolon(self,bits): return(bits == b":")
def _isint(self,bits): return(bits == b"i")
def _islist(self,bits): return(bits == b"l")
def _isend(self,bits): return(bits == b"e")
def _isnull(self,bits): return(bits == b"")

Its not clear how useful these functions are. You call them once, and calling them isn't shorter then just checking the string for equality in the first place. Also the pythons style guide recommends using underscores_to_seperate_words. As it is I keep reading isend as i send.

def loads(self,bcbuffer):
    tokens = []
    null = b""
    numbuffer = null # a buffer for storing number bytes

I'm not sure a constant for an empty string is neccessary. If you insist I suggest it should be a global constant.

    last = []

Last suggests, well, last. But this is more of a stack. I think it could have a better name

    while True:
        atom = bcbuffer.read(1)
        if self._isdictionary(atom): last.append(atom)

Mixing between on-the-same-line, and on-the-next lines within a string of if-elifs looks ugly and makes it harder to read. I'm generally not a fan of putting the body on the same line as the if expression. But it really doesn't work when you mix both styles.

        elif self._isnumber(atom):
            numbuffer += atom
        elif self._iscolon(atom):
            tokens.append(bcbuffer.read(int(numbuffer)))
            numbuffer = null
        elif self._isint(atom): last.append(atom)
        elif self._islist(atom): last.append(atom)

You last.append(atom) a lot. Consider or to combine the conditions

        elif self._isend(atom):
            char = last.pop()
            if self._isint(char):
                tokens.append(int(numbuffer))
                numbuffer = null
        else: break

You don't distinguish between finding invalid characters and the end of the file. In both case you just quit. I'd recommend throwing an exception if you find an invalid character.

    self.bytestrings = tokens

But the tokens also include numbers. So storing them in bytestrings is kinda odd.

    self.trackerURL = str(self.bytestrings[1],"utf-8")

Your loop follows the common pattern of building data structures over several iterations of the loop and then consuming them. Don't do that. It ends up being hard to follow the logic of the function because I've got to figure out what happens over several iterations of the loop. Instead, each iteration of the loop should handle a logical unit.

Here is how I'd approach the problem:

def read_number(bcbuffer, terminator):
    read_byte = lambda: bcbuffer.read(1)
    bytes_iter = iter(read_byte, terminator)
    text = ''.join(bytes_iter)
    return int(text)

def parse_tokens(self, bcbuffer):
    tokens = []

    while True:
        atom = bcbuffer.read()
        if atom == b'i':
            tokens.append( read_number(bcbuffer, b'e') )
        elif atom >= b'0' and atom <= b'9':
            length = read_number(bcbuffer, b':')
            tokens.append( bcbuffer.read(length) )
        elif atom in b"lde":
            pass # ignore the structure which we don't care about
        elif atom == b'':
            break
        else:
            raise IOError('Did not expect %s' % atom)

   return tokens

Notice that I don't have a collection of variables to store partial results. Because each iteration of the loop handles a single "token" I don't need to store data other then my result across the iterations. It is also much clearer, I think, what is going on in the parsing.

I've not tested this code in anyway, use at own risk. I've ignored the possiblity of invalid bencodes. read_number will end up in an infinite loop if it cannot find the terminator. non-digits before the terminator will cause int to throw a ValueError. Various methods to handle those exist. I'd probably wrap file.read() to throw an exception when trying to read past the end of the file.


If you are using a dependency injection framework then you are not using it correctly. AlbumService's constructor should have in this case another parameter that is the SqlDependencyEx. You should not be creating it by yourself. You are already injecting the other two services. Why not this one too?

And I'm wondering where you have the _masterTable parameter from? I don't see it to be passed to the AlbumService. It has only two arguments.

_listener = new SqlDependencyEx(
    connectionString: "SERVER=localhost;DATABASE=dbsample;User Id=usr;pwd=cE$6adadZ'[:3;",
    databaseName: "KEMITEKS",
    tableName: _masterTable);

Another thing is that the name of the SqlDependencyEx does not match the field. Why do you call it a _listener? It's very confusing.


Find if the string contains ALL the vowels

I would like to make one remark concerning the performance of your solution: you need to check if the word contains all vowels ('a', 'e', 'i', 'o' and 'u'), which means the following:

If the word does not contain 'a', then it's not good, else:
If the word does not contain 'e' (we already know it contains 'a'), it's not good, else:
...

But: in the English language, some vowels are more popular than others. Imagine following percentages (not real ones):
60% of the English words contain an 'a'
80% of the English words contain an 'e'
40% of the English words contain an 'i'
20% of the English words contain an 'o'
10% of the English words contain an 'u'

If you start searching with 'a', then with 'e', then with 'i', 'o', and 'u', you have following situation:
40% probability that you have found out that the word is not good, then:
20% probability that you have found out that the word is not good, then:
60% probability that you have found out that the word is not good, then:
80% probability that you have found out that the word is not good, then:
90% probability that you have found out that the word is not good.

=> in other words, you'll spend a lot of time investigating letters which are not popular.

However, if you re-order your search criteria:

first search for 'u'
then search for 'o'
then search for 'i'
then search for 'a'
and only finally search for 'e'

=> like this, you will find much sooner the words without 'u' (90% of the words), or the ones without an 'o' (80% of the words), ..., and this might heavily improve the performance of your search.

I must add that the percentages I have written down are just examples (for the correct percentages you need to search on frequency analysis of the English language).

Good luck


First, I think you might separate the input/output part from processing data by enclosing the merging routine in a separate procedure. Then the merging procedure can be reused in many places of your program. And if you move it to a separate unit you'll be able to reuse it in other programs, too, if necessary.

 program merge (input, output);
    { Reads two ordered lists of integers keyed in by the user, and merges
    them into a third ordered list, without checking their order.
    If the input is not sorted, the result will be undefined.}

const
  FELDLAENGE1 = 5;
  FELDLAENGE2 = 8;
  ERGEBNISFELDLAENGE = 13; { FELDLAENGE1 + FELDLAENGE2}

type
  tFeld1 = array [1..FELDLAENGE1] of integer;
  tFeld2 = array [1..FELDLAENGE2] of integer;
  tErgebnisFeld = array [ 1..ERGEBNISFELDLAENGE] of integer;

procedure mergeTwoArrays( var Feld1 : tFeld1; var Feld2 : tFeld2;
                          var ErgebnisFeld : tErgebnisFeld)
    var
        i : integer;
        j : integer;
        k : integer;
    begin
        i := 1;
        j := 1;
        k := 1;

        while (i <= FELDLAENGE1) and (j <= FELDLAENGE2) do
            if Feld1[i] <= Feld2[j] then
              begin
                ErgebnisFeld[k] := Feld1[i];
                i := i + 1;
                k := k + 1
              end
            else
              begin
                ErgebnisFeld[k] := Feld2[j];
                j := j + 1;
                k := k + 1
              end;
        { add remaining values to ErgebnisFeld}
        if i > FELDLAENGE1 then
            repeat
               ErgebnisFeld[k] := Feld2[j];
               j := j + 1;
               k := k + 1
            until k = ERGEBNISFELDLAENGE+1
        else
            repeat
                ErgebnisFeld[k] := Feld1[i];
                i := i + 1;
                k := k + 1
            until k = ERGEBNISFELDLAENGE+1;
    end;

var
  Feld1 : tFeld1;
  Feld2 : tFeld2;
  ErgebnisFeld : tErgebnisFeld;
  i : integer;
  j : integer;
begin
  { read ordered lists (Felder) }
  writeln (' Please key in', FELDLAENGE1:2, ' values in ascending order for the first list. ');
  for i := 1 to FELDLAENGE1 do
      readln (Feld1[i]);
  writeln (' Please key in', FELDLAENGE2:2, ' values in ascending order for the second list. ');
  for j := 1 to FELDLAENGE2 do
      readln (Feld2[j]);

  { Merge Feld1 and Feld2 into ErgebnisFeld}
  mergeTwoArrays( Feld1, Feld2, ErgebnisFeld);

  { output results from ErgebnisFeld}
  writeln ('The merged list is: ');
  for k := 1 to ERGEBNISFELDLAENGE do
      write (ErgebnisFeld[k], ' ');
  writeln;
  readln;

end.

Another change I would make is simplifying the code to append input lists' tails in the final part of merge – you can do that with two separate while loops, similar to the main merging loop. Exactly one of them will do the actual work, and the cost of not entering the other one equals the cost of the conditional (if-then-else) in your version.

      { add remaining values from Feld1 to ErgebnisFeld}
      while i <= FELDLAENGE1 do
          begin
              ErgebnisFeld[k] := Feld1[i];
              i := i + 1;
              k := k + 1
          end;

      { add remaining values from Feld2 to ErgebnisFeld}
      while j <= FELDLAENGE2 do
          begin
              ErgebnisFeld[k] := Feld2[j];
              j := j + 1;
              k := k + 1
          end;

Then you may use open arrays to make the routine more generic, so it could merge arrays of arbitrary lenghts, not just 5 plus 8.

You can also explicitly pass the lengths of both input lists as parameters to the routine, so it can merge lists shorter than arrays in which they're stored.

procedure mergeTwoArrays( var Feld1 : array of integer; feldLange1 : integer;
                          var Feld2 : array of integer; feldLange2 : integer;
                          var ErgebnisFeld : array of integer)
    var
        i, j, k : integer;
    begin
        i := 0;    { indices of open arrays start from 0 }
        j := 0;    { and end at length-1 }
        k := 0;

        { merge Feld1 and Feld2 to ErgebnisFeld until one of them becomes empty}
        while (i < feldLange1) and (j < feldLange2) do { note the comp. operator }
            if Feld1[i] <= Feld2[j] then
              begin
                ErgebnisFeld[k] := Feld1[i];
                i := i + 1;
                k := k + 1
              end
            else
              begin
                ErgebnisFeld[k] := Feld2[j];
                j := j + 1;
                k := k + 1
              end;

        { add remaining values from Feld1 to ErgebnisFeld}
        while i < feldLange1 do
            begin
                ErgebnisFeld[k] := Feld1[i];
                i := i + 1;
                k := k + 1
            end;

        { add remaining values from Feld2 to ErgebnisFeld}
        while j < feldLange2 do
            begin
                ErgebnisFeld[k] := Feld2[j];
                j := j + 1;
                k := k + 1
            end;
    end;


C++: Am I managing memory the right way?

First of all, you have no copy constructor (or assignment operator). This will be a problem in this case:

void foo(Array a) {
   //...
}

int main() {
   Array a(10);
   foo(a);
   //a is still around, but the pointer has been destroyed.
}

Since there will be two instances of Array using the same pointer. Once one of them goes out of scope, the destructor is called, so the delete[] happens. However, there is still another instance of Array with that same pointer, which has no way to know that delete happened. This is solved by following the "Rule of Three" See "Dynamically allocating an array of objects for a simple example.

In second place, you have a member called array. What's it for? It's never used so why have it?

In third place, some members are protected. Why? Does this mean you plan to have Array be inherited? In that case, you might want to make the destructor virtual. But I'd advise against inheritance, as it would feel counter-intuitive.

The implementation of get and set use unnecessary pointer arithmetic.
Just do:

return arrayPointer[index];

This does the same thing and it's much cleaner to look at.

In fourth place, you do a check on the values of index for set, but not for get. Why not?

In fifth place, index is a signed integer. You may want to consider using size_t instead. It will also make the < 0 check redundant.

In sixth place, usage of get and set feels unnatural. You may want to look at operator overloading.

In seventh place, I would not use cout for the error message. Use assert(), cerr or an exception, depending on what your exact needs are.

In eighth place, you call it Array but you only allow integers to be stored. I'd either name it IntArray or make it a template to allow other types to be stored.

As for "Putting your class in another file", that might be a good idea, especially if you want Array to be used in multiple files. Put it in a header file.

Also, why create your own Array class? Is this for learning purposes? If not, you may want to use std::array or std::vector instead.


Your loop doesn't work because the initial value for exitFlag variable (which is used as condition for the loop) is zero, and it is only being set to 1 under a special set of circumstances which apparently doesn't happen when you run an application.

If you really want to loop forever and only quit application when it fails your loop, have your function return 1 unless it fails. It should look something like this:

int Main(string[] args)
{
    while (CounterApp() != 0)
    {
    }
    return 0;
}

public static int CounterApp()
{
    // do some stuff

    try
    {
        // do some stuff that might fail
    }
    catch (Exception)
    {
        return 0;
    }

    // do some other stuff

    return 1;
}


What would be the idiomatic F# way to write optional parameters?

I would argue that if you need optional parameters your interface is different hence you need another function.
With that said, if you really want optional parameters you must always define a default value, an you could then use partial application for that.
let f op1 op2 nonOpt = op1 + op2 + nonOpt

let fWithDefaults = f 1 2

Then you can use your fWithDefaults whenever you want the defaults.
For your particular example I would write it like this :
type VisaLengths =
     | Thirteen
     | Sixteen

let generateVisa (length : VisaLengths option) =
     let length = Option.defaultValue Sixteen length
     match length with
     | Thirteen -> "4000000000001"
     | Sixteen -> "4000000000000001"

It would be the most "idiomatic", even if it can be a litter cumbersome but it does what you want to do.
Agree, you still have to passe None... But at least your intention about a optional value is explicit, which is very valuable for others reading your code.


Input format

There are a few things I don't like about the way input is handled:

Having all of your input done via the command line is awkward.  Suppose you wanted to try a test case of 10 million integers.  How would you even do that?  I propose that you read your input from stdin instead.  That way you could just create a test input file and run your program like countsort < input.txt to test it.
I don't feel like the user should have to specify the maximum value as the second input value.  Your program could just compute the maximum value as it reads in all the numbers.  This would also allow you to remove some of the error checking you have where you test the array values against the maximum value.
I don't think there is a need for the [ and ] parts of the input, and also the comma separators.  It would be simpler to just have the input be: the count n followed by n numbers without any extra brackets or commas.

Overflow in size computation

It looks like you took care of the special case where the maximum value was UINT_MAX, because in your call to malloc() you used the value max+1 and didn't want that to overflow to zero.  However, there are many other ways to overflow in that same line:

unsigned int *counts = malloc(sizeof(int)*(maxval+1));

Suppose you were on a 32-bit platform with size_t being 32-bits wide, and suppose maxval were 0x40000000.  The expression sizeof(int) * (maxval+1) would evaluate to 4 * 0x40000001 or just 4 because the result would be truncated to 32 bits.  Note that 0x40000000 is just one example.  Any value greater than or equal to 0x3fffffff would cause problems for this platform.

Bug: using uninitialized memory

You allocate your counts array using malloc(), but you never clear your counts array to 0 before you start to use it.  So you could end up with garbage values for your counts.  I would suggest using calloc() so that your allocated array is cleared to zero automatically.  A side benefit to using calloc() is that it avoids your overflow problem because the arguments are split into a size and a count:

unsigned int *counts = calloc(maxval+1, sizeof(int));

Overflow in counts

If you were on a 64-bit platform with 64-bit size_t and 32-bit unsigned int, you could run into another type of overflow problem.  Since your counts array is of type unsigned int (32-bit), your counts could overflow because your array could have more than 2^32 elements. For example, suppose your array had 5 billion instances of the number 5.  Your program would overflow counts[5] and get the wrong count in the end.


TL;DR; skip to if/else if/else statements

I can't say much because there is so little context, it looks like your code functions properly and efficiently,
Your indentation on the other hand is a little weird to me, I would do it like this with out so many tabs and new lines
switch (true) {
    case (interval == 7):
        //weekly
        //Push in the selected dates in the selected array.
        for (var i = 0; i < between.length; i += 7) {
            selected.push(between[i]);
        }
        break;
    case (interval == 30):
        //Monthly
        //Push in the selected dates in the selected array.
        for (var i = 0; i < between.length; i += 30) {
            selected.push(between[i]);
        }
        break;
    case (interval == 15):
        //Bi-Monthly
        //Push in the selected dates in the selected array.
        for (var i = 1; i < between.length; i += 15) {
            selected.push(between[i]);
        }
        break;
    case (interval == 0):
        //One time event
        //Push in the selected dates in the selected array.
        for (var i = 0; i < 1; i++) {
            selected.push(between[i]);
        }
        break;
    default:
        return undefined;
}

EDIT:
Mateon1's answer points out a break; that isn't indented correctly, I have fixed this in my code snippet.

after removing indentation I noticed that your one time event is smelly, you should just select the first date
    case (interval == 0):
        //One time event
        //Push in the selected dates in the selected array.
        selected.push(between[0]);
        break;

you use more overhead for a for loop than is necessary, don't get into the habit of using bigger things than you need.
After all that I also removed some unneeded comments they were just saying the same thing that the code was telling me outright.
Here is the Code that is left
switch (true) {
    case (interval == 7):
        //weekly
        for (var i = 0; i < between.length; i += 7) {
            selected.push(between[i]);
        }
        break;
    case (interval == 30):
        //Monthly
        for (var i = 0; i < between.length; i += 30) {
            selected.push(between[i]);
        }
        break;
    case (interval == 15):
        //Bi-Monthly
        for (var i = 1; i < between.length; i += 15) {
            selected.push(between[i]);
        }
        break;
    case (interval == 0):
        //One time event
        selected.push(between[0]);
        break;
    default:
        return undefined;
}

if/else if/else statements
After viewing the other answer, I think that this would be much better written as an if/else if/else statement like the following
if (interval == 7) {
    for (var i = 0; i < between.length; i += 7) {
        selected.push(between[i]);
    }
} else if (interval == 15) {
    for (var i = 0; i < between.length; i += 15) {
        selected.push(between[i]);
    }
} else if (interval == 30) {
    for (var i = 0; i < between.length; i += 30) {
        selected.push(between[i]);
    }
} else if (interval == 0) {
    selected.push(between[0]);
} else {
    return undefined;
}

and since I have gone this far I think that we could actually create a nice little function that does all of this when given an interval, I included the tests to make sure that the interval stays within the constraints but you could alter that to make it much more extendable.
function GetRecurringDates(interval) {
    if (interval != 0 || interval != 7 || interval != 15 || interval != 30) {
        return undefined;
    }
    for (var i = 0; i < between.length; i += interval) {
        selected.push(between[i]);
    }
}

From @Rolfl's answer I noticed that I too missed the 0-base array bug, so here is the function with the fix
function GetRecurringDates(interval) {
    if (interval != 0 || interval != 7 || interval != 15 || interval != 30) {
        return undefined;
    }
    for (var i = 0; i < between.length - 1; i += interval) {
        selected.push(between[i]);
    }
}

I wrote it like that so that the user doesn't have to know that the code is based on a 0-based array.

You might want to look into using JavaScript's Built in Date functionality.


Program to automate skipping users on a chat website until the username meets certain conditions (v.2.0)

There are instructions you should not repeat inside the loop, and they should be written before it:

from bs4 import BeautifulSoup should be written much above in your code, within the import section.
getName() should be defined outside the loop, and named get_names() according to the naming conventions (actually it should be named get_names() because you are dealing with more than one name)

You do not get all female users:

When you run userName = getName(userNames), you are getting the last female user whereas you are obviously looking for all of them. So you should create a list of usernames and append useName (should be written user_name) to it whenever found.

Main performance issue:

You quickly refresh the page using driver.get('https://talkwithstranger.com/talk-to-strangers') whereas when I visited the link, it does not refresh as frequently as you do it. In opposite, most often I am kicked out of the room and had to wait a dozen of seconds. I think it also depends on whether there are users or not. In all cases, you are refreshing the page too quickly and you have to study the behavior of the website to decide on the strategy and criteria upon which you can refresh the page


A prime number checker (Multi numbers).py

First improvement I see is mathematical: to check if a number n is prime, it's sufficient to verify that it's not divisible by any integer between 2 and math.ceil(math.sqrt(n)) (don't forget to import math at the top of your file). That's going to make your program more efficient.
Another improvement would be to split the code that deals with getting the list of numbers lista from the user, and the code that finds if a single number is prime or not, into two separate functions that you call from the main while True loop. This will aid readability and code reuse.
A third improvement is to rename the variable lista to a more expressive name like numbers or candidates or something else.


Possible improvements:

Don't use __repr__ for a human readable version of the object. That is what __str__ is for. When writing your own __rerp__ you should aim to make eval(repr(obj)) work.
Rather than str.replace, you could str.format the values to the correct format. And so I'd change your Day.__repr__ to something more like:

def __str__(self):
    return '\n'.join(' {!s}'.format(x) for x in self.lessons)

Rather than making two near duplicate loops, you could abstract the logic into one function, get_input. You could also make it so that it shows the user what input they are allowed to pick.

This could be implemented as:

def get_input(question, valid):
    question += '[{}] '.format('/'.join(valid))
    valid = set(valid)
    while True:
        answer = input(question).lower()
        if answer in valid:
            return answer

I'd change Day.__str__ so that it also displays the name and week.
I'd rather read a JSON file, than build the week structure in your program. This is as you may want to later build a GUI, and allow other students to enter their time-tables.

I'll leave this down to the both of you to look into. :)

Excluding the last bullet point I'd change your code to:

class Lesson:
    def __init__(self, name, room):
        self.room = room
        self.name = name

    def __str__(self):
        return '{}: {}'.format(self.name, self.room)

class Day:
    def __init__(self, name, week, lessons):
        self.name = name
        self.week = week
        self.lessons = lessons

    def __str__(self):
        return '{} {}\n{}'.format(
            self.name,
            self.week,
            '\n'.join(' {!s}'.format(x) for x in self.lessons)
        )

def get_input(question, valid):
    question += '[{}] '.format('/'.join(valid))
    valid = set(valid)
    while True:
        answer = input(question).lower()
        if answer in valid:
            return answer

days_str = [str(day) for day in sorted(days.keys())]
while True:
    day = get_input('Day: ', days_str)
    print(days[int(day)])
    if 'n' == get_input('Again? ', ['y', 'n']):
        break


Pandas transform series values until condition is met without for loop

Use a combination of Series.cummax() and Series.shift()
a = pd.Series([0,0,1,0,0,1])

a.cummax()                               # [0,0,1,1,1,1]

a.cummax().shift(fill_value=0)           # [0,0,0,1,1,1]

Then "invert" the 0's and 1's
df = 1 - a.cummax().shift(fill_value=0)  # [1,1,1,0,0,0]


Minimize component state

It's better to use a single field listToShow rather than having a show* field per each list. You don't have to change anything in your template if you wrap the show*List() around listToShow using accessor syntax.

private listToShow: number = 1;
get showingListOne(): boolean { return this.listToShow === 1; };
get showingListTwo(): boolean { return this.listToShow === 2; };
get showingListThree(): boolean { return this.listToShow === 3; };

public showFirstList(): void {
  this.listToShow = 1;
}

public showSecondList(): void {
  this.listToShow = 2;
}

public showThirdList(): void {
  this.listToShow = 3;
}

Injectable

I am very positive your component does not have to be annotated with @Injectable(), therefore it should not be. The component is not really being injected anywhere, right?


Finding difference between adjacent integers in an array - recursive Implementation

In situations like this, it is much simpler to handle the corner case outside the recursive call:

    differenceSequence(int array[], int size, int resultArray[])
    {
        if (size == 0) {
            do_corner_case();
            return;
        }
        differenceSequenceRecursive(array, size, resultArray);
    }

and the helper differenceSequenceRecursive function only deals with regular case.


You are doing the same thing in case of failure at any stage - returning an empty list.  You should use a for comprehension to chain these stages; if any one stage returns None, then the other stages will not be followed.  If you do something like this:

  for {
    wb <- workbook;
    sheet <- Option(wb.getSheetAt(0));
    titleRow <- Option(sheet.getRow(0));
    titleCell <- Option(titleRow.getCell(0)) if titleCell.getStringCellValue == "title";
    priceCell <- Option(titleRow.getCell(1)) if priceCell.getStringCellValue == "price";
  } yield { sheet.get.tail.map{r => (r.getCell(0).getStringCellValue, r.getCell(1).getNumericCellValue)}.toList
  }

This will return Option[List[(String, Double)]], containing either a real list or None.  If any of those stages returns None, the following stages will not be executed and you just get your None back early.  You can pattern match against this output to return the contents of Some(list) or List() if the output is None.

Note: I took the annotated val list out of there, so you would either need to have specified the return type for a val to which you assign the output of the for comprehension or put it back into the yield block.

Note how I turned your if...else expression into guards.  Can you see just how much simpler the code is and how each conditional is paired with the appropriate object? Particularly since the else was just returning another empty list.  This way, it fails and returns None.

"for comprehensions" can be overused in Scala, but this really is where they shine.  You correctly chose Option, but possibly the best thing about Option for any Java coder is the way it can remove boilerplate and defensive coding.  Your code still has the defensive coding, while the for comprehension just throws all that away. Learn to be free ;)


Obtaining information about the logged in user

Usually the logged in user and it's common used information is stored in the session. And the session is usually wrapped in a Context class (like SecurityContextHolder itself). This is done because you can decouple your code from the session or from the servlet api (or whatever api you're using). It also makes it easier to test.

Most of web pages do show your user information when you're logged in, e.g. your avatar on this page on the top. So for every request you do not have to look up the user's information.

I'd introduce a Context class which provides a setUser and getUser method.

Beside that:

AuthorizationService: Authorization means: Is the user allowed to do x. (While authentication means: Is the user really the user he pretends to be). Or in other words: The name of the type is misleading.
getUser(): This method calls this.getUsername() -> I don't see the code of this one, bit I assume it looks up the username by SecurityContextHolder. This means, the AuthorizationService is tightly coupled Spring Security, which is bad. Same for getUserId() -> it's better to pass the arguments and put the responsibility to the presentation layer (which includes security usually)


What a crooked way to compute the next straight string (advent of code 11)

First of all, I can't tell if your code is simply matching some password with the rules, generating one, or generating the next valid one. It's best if you split the operations into small functions so that it's easy to read through. I'd expect a function like generateNextPossiblePassword(pwd) somewhere that goes like:

var newPassword = generateNextPossiblePassword(OLD_PASSWORD);

The code also needs some formatting. You have an object which you are one-lining, then some you expand. Just ran this through JSBeautifier and it looks better than the one posted. Much readable.

As far as I understand, you're just generating passwords and checking if it passes the requirements. Generating should be a straightforward function:

function generateNextPossiblePassword(oldPassword){...}

var potentialPassword = generateNextPossiblePassword('abcdefgh'); //abcdffaa

Now, you don't have to pack everything in the generateNextPossiblePassword function. You can split the operation into generateNextString and checkIfStringIsValidPassword. That way, generateNextString can focus on string generation while checkIfStringIsValidPassword is the actual function that checks the validity.

function generateNextString(str){...}

function doesPasswordPassAllTests(str){...}

function generateNextPossiblePassword(pwd){
  var potentialPwd = generateNextString(pwd);
  var isValidPwd = doesPasswordPassAllTests(potentialPwd);

  // If the value passes, return. Otherwise, call again.
  // Yep, recursion. Lesser temporary counter variables.
  return isValidPwd ? potentialPwd : generateNextPossiblePassword(potentialPwd);
}

Checking against requirements is simply an every operation. every runs the callback for each item. If everything returns true, the result of every is true. If it finds one false, it immediately bails out and the operation results in a false.

Also note that the checks are functions which are then put into an array. This makes it easy to just define a function, then if we ever want to add it, we just pop in its name in the array. Your array isn't very bulky, just references to the functions.

// They take in a password, and simply return true or false
function checkForStraight(pwd){...}

function checkForInvalidLetters(pwd){...}

function checkForTwoPairs(pwd){...}

function doesPasswordPassAllTests(pwd){
  return passwordTests.every(function(test){
    return test(pwd);
  });
}

var passwordTests = [
  checkForStraight,
  checkForInvalidLetters,
  checkForTwoPairs,
];

var passwordPassesAllTests = doesPasswordPassAllTests(NEW_PASSWORD);

I renamed noIOL to checkForInvalidLetters. That's because I, O and L are arbitrary. A more general way to classify this would be character restriction, hence the new name.

By now, we've simplified your code. You can then worry about writing the logic and squeeze performance. Now that they're split, you can optimize them individually. For instance, you can optimize generateNextString to generate passwords as close to the rules as possible to avoid excessive cycles. The checks may easily be regex checks or even just regular string parsing.

It's also very readable. You can easily fold the function blocks in your IDE, only revealing their very meaningful names. Additionally, it's really easy to test each function.

function generateNextPossiblePassword(oldPassword){...}

function generateNextString(str){...}

function doesPasswordPassAllTests(pwd){...}

function checkForStraight(pwd){...}

function checkForInvalidLetters(pwd){...}

function checkForTwoPairs(pwd){...}

var passwordTests = [
  checkForStraight,
  checkForInvalidLetters,
  checkForTwoPairs,
];

var newPassword = generateNextPossiblePassword(OLD_PASSWORD);


You could return the string directly:

fn main() {
    let file_name = "test.txt";
    let file_contents = match get_file_contents(file_name) {
        Ok(s) => s,
        Err(err) => panic!("{}", err)
    };

    println!("{}", file_contents);
}

fn get_file_contents(name: &str) -> Result<String, io::Error> {
    let mut f = try!(File::open(name));
    let mut contents = String::new();

    try!(f.read_to_string(&mut contents));

    Ok(contents)
}

and unwrap if you don’t intend to handle the error usefully:

let file_contents = get_file_contents(file_name).unwrap();


Get string distance for a pseudo fuzzy search

The code becomes 25% faster if we extract values not changed in the loops to variables, but of course it's observable only on large number of repetitions or long strings as tested in Chrome.

function getEditDistance(a, b) {
    var lenA = a.length, lenB = b.length;
    if (lenA == 0) return lenB;
    if (lenB == 0) return lenA;

    var matrix = [];
    var i;
    for (i = 0; i <= lenB; i++) {
        matrix[i] = [i];
    }

    var j, m0 = matrix[0];
    for (j = 0; j <= lenA; j++) {
        m0[j] = j;
    }

    for (i = 1; i <= lenB; i++) {
        var m = matrix[i], mPrev = matrix[i - 1];
        var bChar = b.charAt(i - 1);
        for (j = 1; j <= lenA; j++) {
            if (bChar == a.charAt(j - 1)) {
                m[j] = mPrev[j - 1];
            } else {
                m[j] = Math.min(mPrev[j - 1] + 1, Math.min(m[j - 1] + 1, mPrev[j] + 1));
            }
        }
    }

    return matrix[lenB][lenA];
}

P.S. Replacing s.charAt(i) with s[i] provides no tangible speedup and is not cross-browser.


I came out with this:

nested :: Request -> Maybe Response
nested = nest [ (prefixed "/name", app1)
              , (prefixed "/surname", app2)
              ]

  where
    nest xs request =
        getAlt $ foldMap (Alt . (\(p,a) -> reroute p a request)) xs

    reroute p app = preview p >=> app

Alt is only available in base-4.8.0.0, however it shouldn't be difficult to implement your own Alt.


Dijkstra's Algorithm modified to take negative edge weights

I am afraid your implementation is in \$\Theta(EV)\$ in the worst case, and that is because in the outer while loop you iterate \$V\$ times and popping a node from your custom priority queue runs in \$n = V\$ steps, so we already have \$\Theta(V^2)\$. If your graph is really dense, the complexity will rise to \$\Theta(EV)\$.

In order to get it done efficiently without writing your (say, Fibonacci-) heap, you could import heapq

With it, you can come up with something like:

def sssp(graph, start_node):
    open = [(0, start_node)]
    closed = set()
    distance_map = {start_node: 0}
    while open:
        current_node = heapq.heappop(open)[1]
        if current_node in closed:
            continue
        closed.add(current_node)
        for child, arc_weight in graph[current_node]:
            if child in closed:
                continue
            tentative_distance = distance_map[current_node] + arc_weight
            if child not in distance_map.keys() or distance_map[child] > tentative_distance:
                distance_map[child] = tentative_distance
                heapq.heappush(open, (tentative_distance, child))
    return distance_map

The above runs in \$\Theta((E + V) \log V)\$. Also, the above version has a desirable property: it does not visit nodes that are disconnected from the source node. You might need to know which nodes are not reachable; to this end, you just make a lookup into distance_map: if a node is not there as a key, it is unreachable. This "pruning" may boost the performance if most graph nodes are not reachable from the source node.

About code

Note that PEP8 complains: you should have a single space after , and :. Also, in Python, it is customary to write the class names in CamelCase. Also, in line if  color[j] < temp and color[j] == 'b' you have two spaces after the the if; PEP8 requires one space only.

Hope that helps.

Post scriptum

On G16 = {'a': [('b': -1)], 'b': [('a': -1)]} your implementation goes into an  infinite loop; mine provides invalid results but does exit. If your graph has negative-weight cycles, I suggest you stick to Bellman-Ford; alright, its worst case running time is \$\Theta(EV)\$, but its constant factors are small, since it is just two nested loops.


Checking if a string matches an array of valid characters

memory is surprisingly fast and efficient. If your string-to-test is even modestly large (like 1K), then you may find the following algorithm is efficient. This is especially efficient when the valid-character set is reusable....

boolean[] isvalid = new boolean[Character.MAX_VALUE + 1];
for (char c : VALID_CHARS) {
    isvalid[c] = true;
}
for (char c : name) {
    if (!isvalid[c]) {
       System.out.println("You failed!.");
       return;
    }
}
System.out.println("You succeeded!.");

Now, in your case, there is no reason why VALID_CHARS cannot be declared as:

private static final boolean[] VALIDCHARS = buildValidChars();
private static final boolean[] buildValidChars() {
    ....
}

I have used, and benchmarked this sort of system to great effect when building the JDOM Character validator... you can see how I did it there.... but using a bit-mask representation to use less memory.... which is a bit faster. I also put together a bit of a benchmarh and writeup for the JDOM Verifier performance.


Variables

Go has two ways of declaring new variables: a var notation and a short one. It's preferable to use the short one:

wg := sync.WaitGroup{}
countHmLmFiles := -1
countHmFiles := 0
countLmFiles := 0

Also when declaring lots of global variables in the package block you may use block notation:

var (
    a int = 1
    b string = "foo"
)

You can declare variables directly in the for loop:

for countHmLmFiles, file := range f {
    // countHmLmFiles and file will be visible only here
}

This way their scope will be limited to for body.

Maps in Go

You've created a map with make:

names := make(nameMap, 1)

I don't see a point in creating a map for a single element. Also when you don't need the size argument in make you may simply write names := nameMap{}.

No need pass maps with pointer. Maps and slices are already a reference type and may be passed directly by value. It won't issue a full copy.

Error handling

You've missed lots of error checks. Ideally every error must be handled in place. Otherwise use _ to ignore it and make a comment to be specific on this as it looks like a broken code.

The switch lacks the default case. It worth adding it to catch other possible values of filename.Name[:2].

Also don't forget to add terminating \n to fmt.Printf to separate log messages.


I would assume that Company has e setter method signature as setEmployees(List employees) or setEmployees(Arraylist employees) or some ? wildcard setter, since it accepts as parameter List<Employee> and List<Contractor>.

I would also assume that Employee and Contractor extend one another or the same super class.

In that case, I don't see the benefit of creating such a custom generic setter. Instead I would use the same setter, and mitigate the type identification in the parsing method: company.setEmployees(parseFromReader(currentToken, reader))
and have the List<Employee> parseFromReader(currentToken, reader) worry about the specific instance type, since I assume also most of the information to be parsed would be the same (if the classes extend the same super class).


Imperative Sieve of Eratosthenes using destructive updates in Haskell

takeWhile (<=n) $ iterate (+k) (k+k) can be written as [2*k, 3*k..n] which, here, can be replaced with [k*k, k*k+k..n].

Similarly, takeWhile (<= kMax) . iterate (+1) $ 2 can be written as [2..kMax].

Algorithmically, we can work with odds only, and switch to [k*k, k*k+2*k..n] and [3,5..kMax] (special-casing the 2). Taking it further to pre-ignoring the multiples of 3 (5,7...) also, this is known as wheel factorization optimization.

mapM and mapM_, though very idiomatic, can be faster if coded manually as loops (recursive functions). This would also enumerate the numbers manually, instead of creating the interim lists and hoping the compiler won't actually  create them.

Using unsafeRead and unsafeWrite should be faster than the safe variants.

Lastly, last . primesSmallerThanOrEqualTo can be replaced with lastPrime,

lastPrime n = let arr = sieve n in
              take 1 [ i | i <- [n, n-1..2], arr ! i]

Even faster is to move the last prime-finding code into the sieve function itself, and return that prime from it, instead of the array.


Simple JS validation for two contact forms

The simplest way to minimise your code is to change the functions you've written to accept parameters.

HTML:

<form action="contact.php" method="post" name="form1"
    onsubmit="return validateForm(this)">
...
<input type="email" name="conEmail" id="inputConfirmMail1"
    onblur="mailConfirm(this, 'inputMail1')" placeholder="Confirm E-mail">

JS:

function validateForm(form) {
  var c = form.name.value;
  var d = form.tel.value;
  var e = form.address.value;
  var f = form.topic.value;
  var g = form.email.value;

  if (!c) {
     alert("insert your name");
     return false;
  }
  else if (!d) {
     alert("insert your telephone");
     return false;
  }
  else if (!e) {
     alert("insert your address");
     return false;
  }
  else if (!f) {
     alert("insert a topic");
     return false;
  }
  else if (!g) {
     alert("insert your email");
     return false;
  }
}

function mailConfirm(input, target) {
  var mail = document.getElementById(target).value;
  var conMail = this.value;
  if(mail != conMail) {
     alert('both emails are not the same');
  }
}

However this doesn't stop you from submitting the form with both email addresses being different or having never entered the confirmation email.

Also, hand writing out every single validation rule for each individual input would be very time consuming and prone to business logic errors.

I would highly recommend you use an open source validator to assist like Parsley or Bootstrap Validator