HackerRank Regex Challenge: Detect HTML Tags

Naming/Style

public class Detect_HTML_Tags {

Usually classes get noun names, like HTML_Tag_Lister.

        int N = Integer.parseInt(br.readLine().trim());

It's more common in Java for all upper case variables to be constants:

        final int N = Integer.parseInt(br.readLine().trim());

Note that you can assign constants at runtime in Java.

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

Most places you put the { on the same line as the command.  Here you put it on the next line.  While both are valid, it's generally easier to read the code if you pick one style or the other.  There are some exceptional cases, but this isn't one of them.

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

As I went through your code, I added additional spaces for readability.

Favor interfaces over implementations

        TreeSet<String> tree=count_html_tags(s);

A TreeSet is a specific implementation.  As a general rule, you want variable types to be interfaces.  This allows you to switch the implementation without changing the variable type in multiple places.  You could make the type a NavigableSet, but it should be sufficient to make it a SortedSet.  It might even be enough to make it a Set or Collection with the current code.  So something like

        SortedSet<String> tags = find_html_tags(s);

Note that you don't count the HTML tags.  You find and return them.

Also, I find tags to be a more descriptive name than tree or set.

Later

    private static TreeSet<String> count_html_tags(String s) {

changes to

    private static SortedSet<String> count_html_tags(String s) {

Keep it simple if you can

In the following

        String s1="";
        for(String t:tree){
            s1=t;
            if(i==tree.size()-1)
                break;
            System.out.print(t+";");
            i++;
        }

You could change to

        if (tags.empty()) {
            return;
        }

        String last = tags.last();
        tags.remove(last);
        for (String tag : tags) {
            System.out.print(tag + ";");
        }
        System.out.println(last);

This avoids the i variable and updating the s1 variable on every iteration of the loop.  You also don't have to check on every iteration of the loop in order to end it exactly one iteration early.

Note that last is a method on SortedSet.  As best I can tell, this is the only reason why tags can't be a simple Collection in main.

Bugs?

The problem statement suggests that < p /> is a valid tag, but your regular expression won't match it because of the space between the < and the p.

The problem statement also suggests that <p> is only a valid tag if it has a matching </p>, but you never check for that.  Perhaps that's not actually necessary.  The problem statement says what is valid but doesn't mention you enforcing it.


Math is fun; why waste it on the computer?

    double angle = Math.toRadians(90);
    double sin = Math.sin(angle);
    double cos = Math.cos(angle);

This is the same as

    int sin = 1;
    int cos = 0;

So

            int xx = (int) (+a * cos - b * sin + x0);
            int yy = (int) (+a * sin + b * cos + y0);

simplifies to

            int xx = (int) (- b + x0);
            int yy = (int) (+a + y0);

which simplifies to

            int xx = (int) (y0 + x0) - y;
            int yy = x + (int) (y0 - x0);

And you don't need a or b at all.  But you could precalculate

    int sum = (int) (y0 + x0);
    int difference = (int) (y0 - x0);

right after you calculate y0 and x0 (i.e. before the loop).  Then in the loop, you just need

            int xx = sum - y;
            int yy = difference + x;

Then you could rewrite

            if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
                outRaster.setPixel(x, y, inRaster.getPixel(xx, yy, pixel));
            }

as

            if (sum >= y && sum - width < y && x >= -difference && x < height - difference) {
                outRaster.setPixel(x, y, inRaster.getPixel(xx, yy, pixel));
            }

But then we can change

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {

to

    int right = Math.min(width, height - difference);
    int bottom = Math.min(height, sum + 1)
    for (int x = Math.max(0, -difference); x < right; x++) {
        for (int y = Math.max(0, sum - width + 1); y < bottom; y++) {

Now we don't have to check if xx and yy fit in the bounds.  We only iterate over the pixels where they do.  So we can drop the if and just say

            outRaster.setPixel(x, y, inRaster.getPixel(xx, yy, pixel));

TL;DR

private static void rotateImage(BufferedImage pic1) throws IOException {
    int width = pic1.getWidth(null);
    int height = pic1.getHeight(null);

    // point to rotate about center of image
    double x0 = 0.5 * (width - 1);
    double y0 = 0.5 * (height - 1);

    int sum = (int) (y0 + x0);
    int difference = (int) (y0 - x0);

    WritableRaster inRaster = pic1.getRaster();
    BufferedImage pic2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster outRaster = pic2.getRaster();
    int[] pixel = new int[3];

    // rotation
    int right = Math.min(width, height - difference);
    int bottom = Math.min(height, sum + 1)
    for (int x = Math.max(0, -difference); x < right; x++) {
        for (int y = Math.max(0, sum - width + 1); y < bottom; y++) {
            int xx = sum - y;
            int yy = difference + x;

            outRaster.setPixel(x, y, inRaster.getPixel(xx, yy, pixel));
        }
    }

    ImageIO.write(pic2, "bmp", new File("Images/Output2.bmp"));
}

I also changed the spelling to rotateImage.

Now the only math done inside the loops is incrementing the index variables and simple integer subtraction and addition.

And we only increment over pixels that we're copying.

It's odd to take an image as input and then write a different image to a file.  Why not return the image instead?  Then the caller can save it.

Consider if you can make inRaster a Raster instead.  I don't think that it needs to be writable, just outRaster.


Indenting and dedenting ASP Classic code with Python

You should always write the main program protected within a if __name__ == '__main__': block, so that you can import the file in another program without automatically executing code.  Eg)

if __name__ == '__main__':
    ind = Indenter(s.readlines())
    ind.main()

Don't write classes where you create the class object just to call one instance method of the object.  See the video Stop Writing Classes.

Your code has:

ind = Indenter(s.readlines())

which reads every single line of the file into memory, and stores it in a list.  Then, you call the Indenter.main() function which executes ...

while self.count < len(self.string):
    # ... many lines of code omitted ...
    self.count += 1

... sequentially loops through every element of the list (line of the file) for processing one at a time.  Each member function, including this main() function, uses self.string[self.count] to reference the current line.  This must have been maddening to write, having to type (or copy/paste) the same code over and over.  It is frightening to read.

Let's clean this up.

print_ln(self, string) is structured correctly.  It takes the current line string as input.  Let's duplicate that in indent(), dedent(), and dedent_indent(), by adding the string argument to them, like:

def indent(self, string):
    self.print_ln(string)
    self.space += 4

In the main() function, we now need to pass the line to each function, just like it was passed to self.print_ln(self.string[self.count]).  But that is a lot of duplicate self.string[self.count] access, so let's make a temporary variable for it.  We can use that temporary variable in the re.search(....) calls too.

while self.count < len(self.string):
    string = self.string[self.count]
    if re.search("^\s*if.*then", string, re.IGNORECASE):
        self.indent(string)
    elif # ... many lines of code omitted ...
    else:
        self.print_ln(string)
    self.count += 1

Note that each string is a string, so the str(...) calls can just be omitted.

Now that self.count is only used in main(), we can make it a local variable, instead of an instance member.

count = 0
while count < len(self.string):
    string = self.string[count]
    # ... many lines of code omitted ...
    count += 1

A while loop which counts from 0 up to some limit an be replaced by a for ... in range(...) loop:

for count in range(len(self.string)):
    string = self.string[count]
    # ... many lines of code omitted ...

And since count is only ever used to index into the list that we are looping over the indices of, we can omit the indices altogether, and just loop over the list of strings itself.

for string in self.string:
    # ... many lines of code omitted ...

Now that we are looping directly over self.string, we don't need to explicitly know that it is a list of strings.  It can be any iterable object that returns, one-at-a-time, all the string we are interested in.  Like a file object.  And that file object can be passed to the main() function.

class Indenter:
    # ... omitted ...

    def main(self, lines):

        for line in lines:
            if re.search("^\s*if.*then", line), re.IGNORECASE):
                self.indent(line)
            elif # ... many lines of code omitted ...
            else:
                self.print_ln(line)

if __name__ == '__main__':
    with open('scratch.html') as file:
        ind = Indenter()
        ind.main(file)

Now we are no longer reading the entire file into memory.  Rather, we are opening the file, and reading it line-by-line, processing each line as it is read in, and then discarding it.

What does your code do if it encounters a file which is already indented?  It indents it some more!

That is probably undesired behaviour.  You probably want to strip off any existing indentation before adding the new indentation.

        for line in lines:
            line = line.strip()
            # ... if/elif/else statements omitted ...

Note that this removes the newline from the end of the lines as well, so you'll want to add that back in, perhaps by changing the sys.stdout.write(...) \ sys.stdout.flush() into a simple print(...) statement.

With each line stripped of any previous indentation, you can remove the \s* from the start of all of the reg-ex patterns.

There are 6 reg-ex patterns where you want to indent, 5 where you want to dedent, and 3 where you want to do both.  You always print.  You dedent before printing.  You indent after printing.

Instead of writing many lines of code which do the same thing with different patterns, it is much, much easier to write a loop, which loops through the patterns.  Let's put the patterns into lists:

indent_patterns = ['^if.*then', '^for', '^with', '^do until', '^do$', '^select case',
                   '^case', '^else', '^elseif.*then']
dedent_patterns = ['^end select', '^loop', '^end with', '^end if', '^next',
                   '^case', '^else', '^elseif.*then']

Now we can say if the current line matches any of the dedent_patterns, reduce space.  Then print the line.  Then, if the current line matches any of the indent_patterns, increase space.

if any(re.search(pattern, line, re.IGNORECASE) for pattern in dedent_patterns):
    self.space -= 4

self.print_ln(line)

if any(re.search(pattern, line, re.IGNORECASE) for pattern in indent_patterns):
    self.space += 4

... and the indent, dedent and dedent_indent functions just became unnecessary.

Since print_ln() is called in one spot, we can write than inline as well, which eliminates the need for self.space to be a member variable.

With no member variables left, the entire class can be replaced with one function.

import re

def indent(lines, spacing=4):

    indent_patterns = ['^if.*then', '^for', '^with', '^do until', '^do$', '^select case',
                       '^case', '^else', '^elseif.*then']
    dedent_patterns = ['^end select', '^loop', '^end with', '^end if', '^next',
                       '^case', '^else', '^elseif.*then']

    space = 0

    for line in lines:
        line = line.strip()

        if any(re.search(pattern, line, re.IGNORECASE) for pattern in dedent_patterns):
            space -= spacing

        print(" "*space + line)

        if any(re.search(pattern, line, re.IGNORECASE) for pattern in indent_patterns):
            space += spacing

if __name__ == '__main__':

    with open('scratch.html') as file:
        indent(file)

And like what was said above, stop writing classes.

This does not address the sporadic indentation caused by HTML and Javascript in the file, but

this is a Code Review, which only addresses the code you have actually written.  This is not a forum where you come to get help writing new code, but to get a review of code you have already written.
with a cleaner implementation of the indent code, you should have an easier time addressing that issue.  When you have finished, feel free to post a follow-up question.


Barring any compiler heroics, you are computing n*n a total of \$n^3\$ times.  You might want to cache that result.

const int nn = n*n;

B[j + n_times_i] is a linearly increasing address location, given that j increases by 1 for each middle loop, and and i increases once for each outer loop, which is n increases of j.  Taking advantage of that, you can skip the j + n*i calculation, and B[ ] indexing.

int *pB  = &B;
// ... loops & calculation of temp omitted for brevity.
      *pB++ = temp;

Result:

const int nn = n*n;
int *pB = B;

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        temp = 0;
        for (int k = 0; k < nn; k += n) {
            temp += A[i+k] * A[j+k];
        }
        *pB++ = temp;
    }
}

You may find that you can get additional speed by using pointer arithmetic for A[i+k] and A[j+k].

int *pAi = A + i;
int *pAj = A + j;
for (k=0; k<n; k++) {   // Note: n.  The nn variable is no longer needed.
    temp += *pAi * *pAj;
    pAi += n;
    pAj += n;
}

But, you’ll need to profile to find out.  It depends on the number of free registers you have ... and the compiler/optimizers these days are pretty darn good.


That huge if/else conditional could be converted to for loop with break statement.Assuming 1200 and 2000 as range's lower/upper boundaries.

Padding bottom-left value has the most variation depending on width.That fixed variation can be declared as predefined array:

const paddingSteps = [5.5, 8.5, 11.5, 14, 16, 18, 19, 21];

The final concise implementation:

const paddingSteps = [5.5, 8.5, 11.5, 14, 16, 18, 19, 21];

function navPadding() {
    let width = window.innerWidth;

    if (width < 1200) {
        navDesktop.style.padding = "unset";
        return;
    }
    for (i = 1200; i <= 2000; i += 100) {
        if (width >= i && width <= i + 100) {
            padRight = (width >= 1900) ? 20 : 19;
            navDesktop.style.padding = `0 ${padRight}% 0 ${paddingSteps[i % 1200 / 100]}%`;
            break;
        }
    }
}

navPadding();


Ajit,

Essentially this is a problem of 1-dimensional collision detection.

A useful tool for that is spatial-partitioning.

The book "Real-Time Collision Detection" by Christer Ericson (Morgan-Kaufmann, 2005) contains a wealth of information.  See pages 300–307 for an excellent discussion of 1-dimensional spatial hashing and pages 316—318 describing Morton keys.  The code given there is in C++ but could easily be adapted to C.

You can view a sample by clicking on "Search Inside This Book" at Amazon and then searching for "Hierarchical Grids".  The 5th link or so is page 300.

—Todd


As a first step, I think this is cleaner than the switch

if (change <= 10)
{
    Instantiate(cube, here, Quaternion.identity);
}
else if (change <= 16)
{
    Instantiate(cube1, here, Quaternion.identity);
}
else
{
    Instantiate(cube2, here, Quaternion.identity);
}

But there's still repetition with the calls to Instantiate. I'd suggest creating a new method like this

private GameObject GetRandomCube()
{
    var change = (int)Random.Range(0, 19);
    if (change <= 10)
    {
        return cube;
    }

    if (change <= 16)
    {
        return cube1;
    }

    return cube2;
}

And then use it like this in your loop

Instantiate(GetRandomCube(), here, Quaternion.identity);

If here isn't being used elsewhere in the class, move its declaration inside the inner loop, or just use it in the function call. Now your method looks like this

void Start()
{
    for (var y = 0; y < 50; y++)
    {
        for (var x = 0; x < 10; x++)
        {
            Instantiate(GetRandomCube(), new Vector3(x, y, 0), Quaternion.identity);
        }
    }
}


This is not very much different from your solution. It does not rely on the header being hardcoded though. Depends on GNU awk for the use of PROCINFO to control array traversal.

gawk -F, '
    {count[$2,$4]++; code[$2]; val[$4]}
    END {
        PROCINFO["sorted_in"] = "@ind_num_asc"
        printf "Code\t"
        dashes = "--------"
        for (v in val) {
            printf "%8d", v
            dashes = dashes "--------"
        }
        printf " =%8s\n", "Total"
        dashes = dashes "-----------"
        print dashes

        for (c in code) {
            sum_code = 0
            printf "%d\t", c
            for (v in val) {
                sum_code += count[c,v]
                sum_val[v] += count[c,v]
                printf "%8d", count[c,v]
            }
            printf " =%8d\n", sum_code
        }
        print dashes

        printf "Total\t"
        sum = 0
        for (v in val) {
            sum += sum_val[v]
            printf "%8d", sum_val[v]
        }
        printf " =%8d\n", sum
        print dashes

        printf "PCT\t"
        for (v in val) {
            printf "%8.1f", 100*sum_val[v]/sum
        }
        print "\n" dashes
    }
' file

Code          10      20      30      40 =   Total
---------------------------------------------------
2910           3       0       0       0 =       3
2911           0       2       0       0 =       2
2912           0       2       0       0 =       2
2914           2       2       1       0 =       5
2915           2       0       3       0 =       5
2916           0       0       0       5 =       5
2917           2       0       0       0 =       2
---------------------------------------------------
Total          9       6       4       5 =      24
---------------------------------------------------
PCT         37.5    25.0    16.7    20.8
---------------------------------------------------

I'm not a fan of ALL_CAPS_VARNAMES


Javascript - Replace lots of if statements

One option is to have a map from key -> value

for example:

var var2 = radioResults[1].toString();
var gender = {'7707330': 'boy',
               '7707333': 'girl',
               '7707336': 'both'}[var2];

You could even put functions as the values. For example:

var var1 = radioResults[0].toString()
{'7707341': maori,
 '7707344': pasifika,
 '7707347': all}[var1](gender);


indentation

The most obvious weirdness about your code is the inconsistent indentation. Indeed I was convinced that there was a missing } at the end until I scanned the whole thing much more carefully. Indent everything within a function one level and add additional levels at each new nested statement. (user1118321 has generously provided a version with corrected indentation)

long lines

Very long lines are hard to read. This one, requires me to scroll to read the whole thing. So I can't even see the whole function call all-at-once.

    printf("Id\tName\tS1\tS2\tS3\tTotal\n\n%d\t%s\%d\t%d\t%d\t%d\n",p[i]->id,p[i]->name,p[i]->sub[0],p[i]->sub[1],p[i]->sub[2],p[i]->total);

You can fold this nicely over multiple lines.

    printf("Id\tName\tS1\tS2\tS3\tTotal\n\n%d\t%s\%d\t%d\t%d\t%d\n",
           p[i]->id,p[i]->name,
           p[i]->sub[0],p[i]->sub[1],p[i]->sub[2],
           p[i]->total);

You can even break-up long strings and let the compiler concatenate them for you.

    printf("Id\tName\t" "S1\tS2\tS3\t" "Total\n\n"
           "%d\t%s\t"   "%d\t%d\t%d\t" "%d\n",
           p[i]->id,p[i]->name,
           p[i]->sub[0],p[i]->sub[1],p[i]->sub[2],
           p[i]->total);

Incidentally, I found a missing "t" in there while doing this.

index origin

For output you add 1 to the index, but for input you do not subtract 1. This is bizarre. It would be more natural in a C program to use 0 throughout. The first element is element 0. If you need to, you can document it for your users or even announce it at program startup.

interactive/batch

A more useful program would be one that operates on data-files and accepts command-line arguments as instructions. This saves you lots of typing as you test your program. You can type all the data just once and run your program many times. You can test different options by writing a shell-script or batch-file which runs the program different ways.

You could define a text-representation of your data. A common way is to use : as a separator

Student,Lastname:25:37:44:55
Student,Noname:0:0:0:99
Studentka,Foxy:101:110:150:1000

Then your program could accept the filename and a code or option as an argument.

int main(int argc, char **argv){
    if (argc < 3) {
        printf("too few arguments\n"
               "usage: %s filename option\n"
               "where option is 0 1 2 or 3\n");
    }

    struct student *data = loadfile(argv[1]);
    perform_sort(data, strtol(argv[2],NULL,10));
    print_data(data);
}

It would be good to separate the different parts into different functions, but this is easier to see when you try to make it work with files. You could also accept - as a special file-name that means stdin, and still run your program
interactively. You can trigger an End-Of-File condition with ctrl-D (Unix, OSX) or ctrl-Z (Windows) to tell your program where the data ends. This is a common behavior for command-line utilities.

dynamically resizing arrays

In order to approach what I'm describing here, it would be good to build the student database dynamically.

student *data = NULL;
int data_n = 0;

data = malloc((data_n=10) * sizeof *data);

A couple of things to note. I assign the size and allocate the array in the same statement. I don't know if everybody does this, but it helps me make sure that the two variables always change together. It would be good to check the result of malloc for a NULL and do something sensible such as exit(1), but for very simple programs you can usually get away with just assuming malloc will return the memory. This is a fragile behavior and the program is not correct per se, but memory-management is a complicated subject to learn, so it's also good to keep things simple until there is a need to make them complicated.

So what happens if you're reading line number 11? Every time the loadfile function will read a line, it will first check that i < data_n and if not,
then it must first

data = realloc(data, (data_n *= 2) * sizeof *data);

to make more room. When you finish reading data, you should make sure there is still some room (i < data_n) and then add a sentinel record to indicate the end of data for the other functions. This could be a student with the name "\0" perhaps.

char ... pointer?

char name;

//...

scanf("%s",&s[i].name);

Unless the name is 0 characters long, that's not enough memory for a name. You could set a maximum size, which is perhaps the easiest way.

char name[100];

Or you could use a pointer to a string, but you must allocate memory for it, and for that it is still easiest to use a fixed-size buffer and then use the POSIX function strdup to make a dynamic copy of the string.


Here are some things that may help you improve your code.

Use the required #includes

The code uses std::vector which means that it should #include <vector>.  It was not difficult to infer, but it helps reviewers if the code is complete.

Use <cmath> instead of <math.h>

I infer that you've used <math.h> instead of <cmath> because you're invoking sqrt(i) rather than std::sqrt(i).  The difference between the two include forms is that the former defines things within the std:: namespace versus into the global namespace.  Language lawyers have lots of fun with this, but for daily use I'd recommend using <cmath>.  See this SO question for details.

Use the appropriate constructor

There's not really any reason to push the value of 2 after the stack is created when it could be done all at the same time.  In fact, I'd write this:

std::vector<int> primes{2, 3};

Seeding the vector with the first two primes for reasons that will be very clear in the next suggestion.

Use a more efficient algorithm

Of all even numbers, only 2, which is already in the vector, is prime, so thereafter all even numbers may be safely skipped.  Further, there's little reason to attempt to divide by 2 if you've skipped all other even numbers.  For that reason, I'd write it like this:

for(int i = 3; i < primeCap; i+=2) {
    bool isPrime = true;
    int lim = std::sqrt(i);
    for(int j = 1; primes[j] <= lim; j++){
        if(i % primes[j] == 0){
            isPrime = false;
            break;
        }
    }
    if(isPrime)
        primes.push_back(i);
}

Doing this reduces the time by about half.

Use const where practical

Since primeCap doesn't seem to change within this program, it would make sense to me to declare it as const or even constexpr:

constexpr long int primeCap = 1e8;

Maximize the available numerical range

Assuming we're not hunting for negative prime numbers, wouldn't unsigned numbers make more sense?  It's also logical to try to assure that primeCap and the values in the std::vector are of the same type -- either unsigned or unsigned long.

Avoid memory reallocations

It would save some reallocations and moves if the code were to preallocate the required size.  One quick and relatively accurate approximation for the number of prime numbers less than a particular number \$n\$ is \$\frac{n}{\log{n}-1}\$.  We can use that to reserve approximately the right amount of memory:

primes.reserve(primeCap / (std::log(primeCap) - 1));

Avoid breaking out of loops

It's generally better to put loop exit conditions at the top rather than forcing the reader to hunt for a break buried somewhere inside the loop.  It also often simplifies the code.  The for loop could be rewritten as:

for(unsigned j = 1; isPrime && operator[](j) <= lim; j++){
    isPrime = i % operator[](j);
}

Consider a custom class

If we need a std::vector of prime numbers, there's little use in it until it's actually created and populated.  For that reason, one way to make sure that it's useful immediately after construction is to create a class with a constructor:

Result

Here's the code with all of these suggestions.  It runs about twice as fast as the original for any given range.

#include <vector>
#include <cmath>
#include <iostream>

class Primes : public std::vector<unsigned>
{
public:
    Primes(unsigned primeCap)
        : std::vector<unsigned>{2,3}
     {
        reserve(primeCap / (std::log(primeCap) - 1));
        for(unsigned i = back()+2; i < primeCap; i+=2) {
            bool isPrime = true;
            unsigned lim = std::sqrt(i);
            for(unsigned j = 1; isPrime && operator[](j) <= lim; j++){
                isPrime = i % operator[](j);
            }
            if(isPrime)
                push_back(i);
        }
    }
};

int main() {
    Primes primes(1e8);
    std::cout << "prime[" << primes.size() << "] = " << primes.back() << "\n";
}


Taking the sum and average of the keyboard inputs

A few things:

The application should do 2 things.

  Collect up to 10 different integers, or until the entered value is -99
  Sum and Average the values

# so lets start by creating a list and fill it with all the numbers we need
numbers = list()
for i in range(0, 10):
    inputNr = int(input("Enter a number: "))
    if(inputNr == -99):
        break;

    numbers.append(inputNr)

#Then we take all of the numbers and calculate the sum and avg on them
sum = 0
for j, val in enumerate(numbers):
    sum += val

print("The total sum is: " + str(sum))
print("The avg is: " + str(sum / len(numbers)))

A few pointers about your code:

Use a whitespace (a single space) between variable declaration and assignment. Where you did a=1 you want to do a = 1
You usually iterate an array (or in Pythons case a list) from 0 to N, and not 1 to N
Create variables which you can reuse. As you can see in my example I create a inputNr variable which holds the input. I later reuse this to check if it's -99 and I reuse it by adding it to my list
variable names, function names, and everything else should have a descriptive and concise name. Where you named your input variable to a I named mine to inputNr. This means that when we later reuse this variable in the code it will be clear to us what it is and what it holds.


There are two algorithmic aspects to your code which concern me. The most significant problem is that you read the entire file in to memory before you start processing the data:

filelist = a.readlines()

This is an inefficient way to do things with large input files.

You should instead be reading the data 1 line at a time and processing each line as you get it. This allows you to have a much smaller memory 'footprint', and it allows you to discard data that you do not need.... instead of your while loop while count < leng consider the approach:

for line in a:
    ....

This should reduce your memory significantly.

(Asker updated question....)

The second issue you should consider changing is using numpy arrays for the vectorr method as well. This array is about the same size as the final array and you are incrementally allocating memory for it. Doing it with a single initializer (perhaps vect = empty((I*J*K, 3)) ) would be worth considering.


JavaScript - Given a list of integers, return the first two values that adds up to form sum. sum = x + y

Bug

The implementation doesn't work well with duplicate numbers:

console.log(sum_pairs([10, 5, 5, 3, 7, 4], 10));
[ 3, 7 ]

That output should be [ 5, 5 ].

Also,
for sum_pairs([10, 5, 2, 3, 7, 5], 8) I would have expected [ 5, 3 ] instead of [ 3, 5 ] as the output.
You didn't mention that results should be sorted.

The slowness

I see several reasons for the slowness:

The implementation is quadratic, using a nested loop
The implementation uses several expensive operations, such as slice and splice of arrays

Also, the implementation is extremely complicated and hard to follow,
so there might be other causes too.

A simpler solution is possible if you track the elements seen so far in an object, and check if target - current was seen or not.

var sum_pairs = function(ints, s) {
  var seen = {};

  for (let i = 0; i < ints.length; i++) {
    let num = ints[i];
    if (seen[s - num]) {
      return [s - num, num];
    }
    seen[num] = true;
  }
}


Polymorphism with overrides and base calls simulating an employee

There is one thing I don't line about Employee: you are leaking memory.

Person super; should be a pointer, not the object. You are creating the
object with malloc, by doing

    employee->super = *Person_new(first, last);

you are leaking memory because you lose the reference of the pointer returned
by malloc and you cannot free it when you destroy the object. And you are not
checking if malloc is returning 0. So I'd change it to:

typedef struct Employee Employee;
struct Employee {
    Person super;
    char* company;
    int salary;
    Person *super_ref;
};

Person* Employee_new(char* first, char* last, char* company, int salary) {
    Employee* employee = malloc(sizeof(Employee));
    if(employee == NULL)
        return NULL;

    employee->super_ref = *Person_new(first, last);
    if(employee->super_ref == NULL)
    {
        free(employee);
        return NULL;
    }

    employee->super = *employee->super_ref;
    employee->super.display = display; // override

    employee->company = company;
    employee->salary = salary;

    return (Person *)employee;
}

so now the destroy method can do free(obj->super_ref); to free the memory of
the base object.

edit

An alternative is that you create a init function for Person objects that gets
an object as an argument and does not allocate memory by itself. I'd do:

int Person_init(Person *self, char* first, char* last))
{
    if(self == NULL || first == NULL || last == NULL)
        return NULL;

    self->first = first;
    self->last = last;
    self->display = display;

    self->base = self; // assigning reference to self to retain original functions in case they get overriden

    return 1;
}

Person* Person_new(char* first, char* last) {
    Person* self = malloc(sizeof *self);

    if(self == NULL)
        return NULL;

    if(Person_init(self, first, last) == 0)
    {
        free(self);
        return NULL;
    }

    return self;
}

and for the Employee class

Person* Employee_new(char* first, char* last, char* company, int salary) {
    if(first == NULL || last == NULL || company == NULL)
        return NULL;

    Employee* employee = malloc(sizeof *employee);
    if(employee == NULL)
        return NULL;

    if(Person_init(&employee->super, first, last) == 0)
    {
        free(employee);
        return NULL;
    }
    employee->super.display = display; // override

    employee->company = company;
    employee->salary = salary;

    return (Person *)employee;
}

Then you don't have to worry about freeing the base object.

edit2

*OP said in the comments**

  I'm wondering what's wrong with the freeing the base pointer, I'm assigning it right away to the new value free(&employee->super); employee->super = *super;

Sorry, it seem to me you don't have a real understanding of memory managment and
what the * dereferencing operator does.

First of all, you have no guarantee that after free(ptr) you can access
the contents of ptr. After the free, ptr points to an invalid location and
accessing/dereferencing it is undefined behaviour.

Secondly

employee->super = *Person_new(first, last);

is the same as doing

Person *tmp = Person_new(first, last);
employee->super = *tmp;

*tmp is dereferencing tmp, the type is Person not Person*. In C when you
do an assigment with struct objects (not pointers) you are copying bit by bit
the bit pattern into a new object. That means that the bit pattern of
employee->super is the same as the bit pattern of *tmp, but they are not
the sam object, the reside at different places in memory.

You can only call free(ptr) when ptr stores the address returned by either
malloc or realloc. If you do free(&employee->super) you are passing a
completely different address to that one that malloc returned in Person_new,
this is undefined behaviour, you cannot do that.

There is no other way for you, you have to store the original pointer in the
struct, that's the reason why I added the Person *super_ref in the struct, so
that the original pointer is not lost.

  We have a major problem, this implementation is causing recursion at

I made small changes to your code, I don't have this problem:

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

typedef struct Person Person;
typedef struct Person {
    Person *base; // reference to itself to retain reference to original function
    char* first;
    char* last;
    void (*display)(const Person *self);
    void (*destroy)(Person *self);
} Person;
Person* Person_new(char* first, char* last);

static void display(const Person *self) {
    printf("First: %s\n", self->first);
    printf("Last: %s\n", self->last);
}

static void destroy_person(Person *self)
{
    if(self == NULL)
        return;

    free(self);
}

Person* Person_new(char* first, char* last) {
    Person* self = malloc(sizeof(Person));
    self->first = first;
    self->last = last;
    self->display = display;
    self->destroy = destroy_person;

    self->base = self; // assigning reference to self to retain original functions in case they get overriden

    return self;
}

typedef struct Employee Employee;
struct Employee {
    Person super;
    char* company;
    int salary;
};
Person* Employee_new(char* first, char* last, char* company, int salary);

static void display2(const Person* self) {
    self->base->display(self->base);

    Employee *e = (Employee*) self;

    printf("Company: %s\n", e->company);
    printf("Salary: %d\n", e->salary);
}

static void destroy_employee(Person *self)
{
    if(self == NULL)
        return;

    if(self->base)
        self->base->destroy(self->base);

    free(self);
}

Person* Employee_new(char* first, char* last, char* company, int salary) {
    Employee* employee = malloc(sizeof(Employee));

    employee->super = *Person_new(first, last);
    employee->super.display = display2; // override
    employee->super.destroy = destroy_employee; // override

    employee->company = company;
    employee->salary = salary;

    return (Person*) employee;
}

int main(void)
{
    Person* person = Person_new("John", "Doe");
    Person* employee = Employee_new("Jane", "Doe", "Acme", 40000);
    person->display(person);
    puts("---");
    employee->display(employee);

    person->destroy(person);
    employee->destroy(employee);

}

It prints

$ ./b
First: John
Last: Doe
---
First: Jane
Last: Doe
Company: Acme
Salary: 40000

edit3

The fact that my little changes do not have the problem of endless recursion in
display2 kept me thinking about it and I've been running the code with the
debugger to see why I didn't have the problem as well. And now I understand why
my code does not have that problem, and your's shouldn't have that as well. In
fact, I realized that there is a way of freeing the memory correctly without
have a separate member like super_ref.

Let me explain:

In Employee_new you do:

employee->super = *Person_new(first, last);
employee->super.display = display2; // override

I told you that you would be leaking memory because you lose the original
pointer that malloc returns. And that is true, however I failed to realize
that you have in fact a pointer pointing to the original address that malloc
returns: the base member of the Person struct. In Person_new you do

self->base = self;

and this solves the problem with the overloading and the freeing, even though we
both didn't realize it at the time.

So again, when you do

employee->super = *Person_new(first, last);

you are dereferencing the pointer returned by malloc and making a copy of the
object into another object. But I failed to realize is that
employee->super->base points to the original location returned by malloc.
So when you do

employee->super.display = display2; // override

you are indeed setting a new value to employee->super.display, but because
employee->super is just a copy, the original does not change and with
employee->super->base you get the orginal object.

That's why

static void display2(const Person* self) {
    self->base->display(self->base);
    ...
}

shouldn't do end in a recursion, because self->display points to display2,
but self->base->display is still unchanged and points to display.

And now you can use the same behaviour for destroying the Employee object.
Let's say you have destroy function pointer in Person which points to the
destroy function:

void destroy_person(Person *person)
{
    if(person == NULL)
        return NULL;

    free(person);
}

and in Person_new you add:

self->destroy = destroy_person;

Now you can destroy a person object by doing person->destroy(person);.

The destroy for Employee will look similar to display2:

void destroy_employee(Person *self)
{
    if(self == NULL)
        return;

    if(self->base)
        self->base->destroy(self->base);

    free(self);
}

because self->base is still pointing to the original object,
self->base->destroy points to destroy_person. Now in
Employee_new you have to add

employee->super.display = display2; // override
employee->super.destroy = destroy_employee; // override

and in main you just do person->destroy(person) and
employee->destroy(employee);. I've checked the code above (I've updated with
the destroy functions) with valgrind and it told me that everything was freed
correctly.


Generating a random string of 6 characters long in Python 3.6.2

Simplicity + improvements:

chars list. Instead of hardcoding all lowercase, uppercase and digit chars - string module provides a convenient constants string.ascii_letters and string.digits
random.randint(0,61). Instead of generating random index for further search on chars sequence - random.choice already allows getting a random element from a specified sequence
for ... loop is easily replaced with generator expression

The final version:

import random
import string

def random_alnum(size=6):
    """Generate random 6 character alphanumeric string"""
    # List of characters [a-zA-Z0-9]
    chars = string.ascii_letters + string.digits
    code = ''.join(random.choice(chars) for _ in range(size))
    return code

if __name__ == "__main__":
    print(random_alnum())
    print(random_alnum())
    print(random_alnum())

Sample output:

g7CZ2G
bczX5e
KPS7vt


Please help and improve this script for displaying search results

A couple of small things...

I would replace this:

if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) ||
    strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])

with something like:

foreach($keyword in $keywords) {
    if (strstr($lines[$i]) {
       $j++;
       $line .= trim($lines[$i])."...";
       break;
    }
 }

Also, this line:

       $line .= trim($lines[$i])."...";

will result in an extra trailing "..." when $j gets to 2.  I'm presuming you want something like "line1...lineN", but instead you'll get "line1...lineN...".  You probably want to chop off those extra dots, or only add them when needed.


Determining if a product is taxable or imported

Your is_taxable? function code does not seem to work. The issue is that taxable is never going to be true, so you'll never assign a new value. You want to write if !taxable instead. Your code becomes:

def is_taxable?
    taxable = false
    NON_TAXABLE.each { |x| taxable = x.match(@product_name) if !taxable }
    !taxable
end

It's still possible to make it simpler using Ruby functions on arrays.

def is_taxable?
  NON_TAXABLE.none? { |x| x.match(@product_name) }
end

This means: if my product is not among the tax-free products, then it is taxable.


One thing which immediately jumped out to me is this:

LastNameFather string,
LastNameMother string,
FatherName string,
MotherName string,
FatherContact string,
MotherContact string,
FatherPlaceOfWork string,
MotherPlaceOfWork string,

Your design assumes that every student will have exactly 1 mother and exactly 1 father. I can tell you now that will not be the case. Students with divorced parents may have two mothers and two fathers, all of whom will want to have their contact info listed. Some students may have gay or lesbian parents, and thus two fathers or two mothers. Some students may have neither, and instead may have a legal guardian who is neither their father nor mother.

One solution to this would be to have a table for a "person", and link people to each student. Identify whether that person is a father or mother (or non-parental guardian). This will also simplify having siblings: you can have the same mother, father, etc. for multiple students.

For the majority of students, this won't be an issue, but for more than you might think, it will. Do those families and your management a favor by making it easy to handle various family scenarios!


1. Review

The code in the post does not always compute the highest profit. For example, suppose that I have these orders:

sell = [Order(price=1, amount=1, min_amount=np.nan)]
buy = [Order(price=1, amount=1, min_amount=1),
       Order(price=2, amount=1, min_amount=1)]
max_n = 2

Then the code computes:

buyprices = [0, 1]
profits = [0, 0]

In other words, the code sells to the first buyer, ignoring the second buyer who is prepared to pay more.
You clarified in comments that it's a requirement that the buyers be sorted by price. It would be more reliable if the code did any necessary sorting:

buy = buy[np.argsort(buy[:,0])]

Then you wouldn't have to worry about the order of the input.
Even if the input is sorted by price, the algorithm in the post still does not always compute the highest profit. For example, suppose that I have the following orders:

sell = [Order(price=1, amount=4, min_amount=np.nan)]
buy = [Order(price=6, amount=3, min_amount=3),
       Order(price=5, amount=2, min_amount=2),
       Order(price=5, amount=2, min_amount=2)]
max_n = 5

In this case, the code computes:

buyprices = [0, 0, 10, 18, 18]
profits = [0, -1, 8, 15, 14]

The highest profit it can find is 15, by selling three units to the first buyer. But if I sell two units to each of the second and third buyers, then I get a profit of 16.
Even with the orders given in the post, the code computes the wrong prices for some amounts. For example, you can see from the graph that the code thinks that it can sell 40 units for a price of 200. But there is no way to sell 40 units — you can sell 20 units to the third buyer, but no more than that, and the second buyer has a minimum order of 50.

Similarly, the code determines that it can sell 140 units for a price of 3200. But there is no way to make such a sale: if you sell 100 to the first buyer, then that leaves 40, and there is no way to sell 40 units (as discussed above). So you have to sell to the second buyer, in which case the best price you can get is 2100.

I believe that the correct graph looks like this, with a gap between 20 and 50, and lower profits betwen 120 and 150:

2. Correct algorithm

Before trying to speed up the code, it's important to implement a correct algorithm (even if it is slow), otherwise it will be hard to check that the faster algorithm is correct.

In the general case, the problem of finding the highest profit is NP-hard, by an easy reduction from SUBSET SUM. But this isn't a disaster, because problems like subset sum often have pseudo-polynomial algorithms using the tabular method (aka "dynamic programming").

So let's try the tabular method by building up a table of prices, using \$−∞\$ for impossible amounts:

def buy_prices(buy_orders, limit):
    """Return array containing the best price for each amount below limit,
    given an array of buy orders. The result is -inf for any amount
    that cannot be sold to any combination of buy orders.

    """
    prices = np.full((limit,), -np.inf)
    prices[0] = 0
    for price, amount, min_amount in buy_orders:
        p = prices.copy()
        for a in range(int(min_amount), int(amount) + 1):
            for i in range(a, limit):
                prices[i] = max(prices[i], p[i-a] + a * price)
    return prices

This has runtime \$Θ(mn^2)\$, where \$m\$ is the number of buy orders and \$n\$ is the maximum amount that can be traded.

We can speed this up by vectorizing the inner loop:

def buy_prices(buy_orders, limit):
    """Return array containing the best price for each amount below limit,
    given an array of buy orders. The result is -inf for any amount
    that cannot be sold to any combination of buy orders.

    """
    prices = np.full((limit,), -np.inf)
    prices[0] = 0
    for price, amount, min_amount in buy_orders:
        p = prices.copy()
        for a in range(int(min_amount), min(limit, int(amount) + 1)):
            q = p[:limit-a] + a * price
            prices[a:limit] = np.maximum(prices[a:limit], q)
    return prices

However, the runtime is still \$Θ(mn^2)\$ and so it will be unacceptable when \$n\$ is large.


Making the same amount from different combinations of coins (top-down approach)

Simpler base case

I suggest returning 0 as the base case to avoid the if c check di as x += 0 does not change it.

Iterate at a higher level

Use for item in collection not range(len. The index can be obtained with enumerate.

Avoid repetition

You repeat _get_num_of_changes(amount - coin, denominations, twice, use a ternary conditional expression to avoid it.

Avoid manual summing

Starting at \$0\$ and writing += is too manual in Python, I suggest using sum.


How to use recursion to turn object into string?

I agree that JSON.stringify isn't the most appropriate for this problem, not just because it's slower, but also because it's a bit harder to understand. And you're also right in assuming that reduce() isn't the best tool for the job. Using a .map() reads in a much more natural way.

const convert = obj => (
  Object.entries(obj)
    .map(([key, value]) => (
      typeof value === 'string'
        ? `${key}:${value};`
        : `${key}{${convert(value)}}`
    ))
    .join('')
)

console.log(convert({
  a: {
    b: 'c',
    d: 'e'
  },
}))

When optimizing this, think about the use case. While tail-call recursion may or may not be possible, it will make the code much more difficult to read, and it really won't help. The main advantage to tail-call recursion is to save memory on the call stack, and to let a recursive function call into itself an unlimited amount of times while still using just one call-frame worth of memory on the stack. There's no practical chunk of extremely nested CSS that can be written to make tail-call optimization worth it.
In your question, speed seems to be one of your primary concerns, but I'll play a bit of devil's advocate here and ask if it really should be for this use case. How much CSS-in-JS would you need to write before any of these micro-performance improvements even become noticeable? Tens of thousands of lines? Hundreds of thousands? I would suggest just building out the library first, run some benchmarks afterwards, and find out what parts of it actually run slow. Then only worry about fixing the slower areas.


Converting a wrapper object to a value object

Since both classes have the same getters and setters this can most easily be achieved using apache commons beanutils:

Channel channel = new Channel();
BeanUtils.copyProperties(channel, channelWrapper);

if you have more complex requirements (e.g. different property names or types), I would recommend dozer.


Mixing GUI code and database code violates the single responsibility principle. One class (here your form) should have at the best one responsibility. One method (here Suggestion()) should have at best one responsibility. Your method is retrieving items from the GUI and is storing them into the database.

Based on the naming guidelines

method names should be made out of verbs or verb phrases.
variables should be named (also it is not mentioned explicitly for variables which are local to a method) using camelCase casing. You shouldn't use any type of snake_Case casing.

At least if you have choosen a style, also this style isn't following the guidelines you should stick to the choosen style. Right now you are mixing the casing styles.

Calling Convert.ToDouble() on a double or calling ToString() on a String is redundant.

Your loops are starting at 1 and you are accessing the items by [iterator -1]. You should start at 0 as every array in NET.

The starting at 1 and  the ending condition of < thegrid.RowCount will let you miss one row.

You should retrieve Cells["PUR LT"] only if partNumber == material.

Both OleDbConnection and OleDbCommand are implementing IDisposable so enclosing the usage in a using block will automatically call Dispose() on the objects and therefor also close the connection.

Instead of iterating over the rows of the datagridviews you should consider to use linq to do the job.

You should always assume that a cell of the datagridview can be DBNull.Value. So a checking for DBNull should be done.

Refactoring the former method with implementing the mentioned points will lead to a new class for which I have choosen the name RowContent

public class RowContent
{
    public bool IsValid { get; private set; }
    public DateTime RequestedDate { get; private set; }
    public String Material { get; private set; }
    public String Quantity { get; private set; }
    public DateTime SuggestedDate { get; private set; }

    public RowContent(string requestedDate, string material, string quantity)
    {
        RequestedDate = Convert.ToDateTime(requestedDate);
        Material = material;
        Quantity = quantity;
    }

    public void SetPureLeadTime(String leadTime)
    {
        SuggestedDate = GetWorkDays.AddWorkdays(RequestedDate, Convert.ToDouble(leadTime));
        IsValid = true;
    }
}

next we add a method for checking if the givven DataGridViewCell's value is DBNull.

private bool IsNotDBNull(DataGridViewCell cell)
{
    return !cell.Value.Equals(DBNull.Value);
}

No we extract the retrieving of the datagridviews values to a separate method.

private IEnumerable<RowContent> GetSuggestedContents(DataGridView firstGrid, DataGridView secondGrid)
{
    IEnumerable<RowContent> contents =
        firstGrid.Rows
                        .Cast<DataGridViewRow>()
                        .Where(r=> IsNotDBNull(r.Cells["Requested_Date"]) &&
                                   IsNotDBNull(r.Cells["Material"]) &&
                                   IsNotDBNull(r.Cells["Requierd_Qty"]))
                        .Select(r => new RowContent(r.Cells["Requested_Date"].Value.ToString(),
                                                    r.Cells["Material"].Value.ToString(),
                                                    r.Cells["Requierd_Qty"].Value.ToString()));

    foreach (var rowContent in contents)
    {
        String leadTime =
            secondGrid.Rows
                            .Cast<DataGridViewRow>()
                            .Where(r => IsNotDBNull(r.Cells["PartNumber"]) &&
                                r.Cells["PartNumber"].Value.ToString() == rowContent.Material)
                            .Select(r => r.Cells["PUR LT"].Value.ToString()).FirstOrDefault();

        if (String.IsNullOrEmpty(leadTime)) { continue; }

        rowContent.SetPureLeadTime(leadTime);

    }
    return contents.Where(c => c.IsValid);
}

which can be called like

IEnumerable<RowContent> contents = GetSuggestedContents(dataGridView9, dataGridView10);

And last but not least the database manipulating code which returns an IList<string> containing the Message property of any occured OleDbException

private IList<string> UpdateSuggestedContents(IEnumerable<RowContent> contents)
{
    IList<string> errorMessages = new List<string>();

    using (OleDbConnection connection = new OleDbConnection("your connection string here"))
    using (OleDbCommand oleDbCmd = new OleDbCommand("InsertSuggested", connection))
    {
        oleDbCmd.CommandType = CommandType.StoredProcedure;

        OleDbParameter partNumberParameter = oleDbCmd.Parameters.Add("@PartNumber", OleDbType.VarChar, 30);
        OleDbParameter adjustedDateParameter = oleDbCmd.Parameters.Add("@AdjustedDate", OleDbType.Date, 50);
        OleDbParameter suggestedDateParameter = oleDbCmd.Parameters.Add("@SuggestedDate", OleDbType.Date, 50);
        OleDbParameter quantityParameter = oleDbCmd.Parameters.Add("@Qty", OleDbType.VarChar, 30);

        connection.Open();

        foreach (RowContent content in contents)
        {
            partNumberParameter.Value = content.Material;
            adjustedDateParameter.Value = content.RequestedDate;
            suggestedDateParameter.Value = content.SuggestedDate;
            quantityParameter.Value = content.Quantity;
            try
            {
                oleDbCmd.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                errorMessages.Add(ex.Message);
            }
        }
    }
    return errorMessages;
}


Checking a board to see if a player has three in a row

We really need to know more about the game to help you properly. Also, why is your program spending so much time in this function? (Are you doing some kind of lookahead, with this function being part of the evaluation?)

If this is a game like gomoku, where players take turns, and in each turn a player places one piece on the board, and the first player to get n in a line wins, then the only way that the board can have a winning line is if that line includes the piece that was just played. Hence there's no point looking at other points in the board.

So in this case you'd write something like this:

DIRECTIONS = [(1,0),(1,1),(0,1),(-1,1)]

def legal_position(i, j, board):
    """Return True if position (i, j) is a legal position on 'board'."""
    return 0 <= i < len(board) and 0 <= j < len(board[0])

def winning_move(player, move, board, n = 3):
    """Return True if 'move' is part of a line of length 'n' or longer for 'player'."""
    for di, dj in DIRECTIONS:
        line = 0
        for sign in (-1, 1):
            i, j = move
            while legal_position(i, j, board) and board[i][j] == player:
                i += sign * di
                j += sign * dj
                line += 1
        if line > n: # move was counted twice
            return True
    return False

But without understanding the rules of your game, it's impossible for me to know if this approach makes any sense.


Run length encoding of an input string (Coderbyte 'Run Length' challenge)

You could just make a new list rather than use list.insert and list.append.

indexes.insert(0, 0)
indexes.append(len(s))

indexes = [0] + indexes + [len(s)]

For your "slice string" part, I'd make a function called pairwise. As this is a rather well know recipe in Python.

def pairwise(iterable):
    return (
        (iterable[i], iterable[i+1])
        for i in range(len(iterable) - 1)
    )

You could combine slices and compressed_str into one comprehension. If you do you don't need to use len as indexes[i+1] - indexes[i] is the length of the string.

return "".join(
    f"{b - a}{s[a]}"
    for a, b in pairwise(indexes)
)

def pairwise(iterable):
    return (
        (iterable[i], iterable[i+1])
        for i in range(len(iterable) - 1)
    )

def compress_string(s: str) -> str:
    if s == "":
        return ""

    indexes = [
        i+1
        for i in range(len(s) - 1)
        if s[i+1] != s[i]
    ]
    indexes = [0] + indexes + [len(s)]
    return "".join(
        f"{b - a}{s[a]}"
        for a, b in pairwise(indexes)
    )

Itertools

The pairwise function could be better described using the pairwise recipe.
If you utilize itertools.groupby the challenge is super easy, as it makes slices for you.

def compress_string(s: str) -> str:
    if s == "":
        return ""
    return "".join(
        f"{sum(1 for _ in g)}{k}"
        for k, g in itertools.groupby(s)
    )


Since position is a number, you can simplify your columnSorter function. It becomes a one-liner, so you could even do:

columnArray.sort(function(a, b) { return a.position - b.position; });

Note though that some people consider this less readable. It's definitely less explicit in what it does, so you may wish to explain it in a comment.
You're using a for..in construct. This will give unexpected results if I extend Array.prototype. Either use a regular for loop, or check for columnArray.hasOwnProperty(col) in each iteration.
Why add an empty <tfoot>?
You're closing your <thead> in the wrong spot. <tbody> and <tfoot> should be children of <table>, not children of <thead>, so close your <thead> earlier.
It doesn't make much sense to return x += y;. Either return x + y;, or do x += y; return x;.


C++ Generic Callback class with removable listeners by unique id

I think this makes sense in terms of STL use.  Storing a std::shared_ptr<std::function> is not usually necessary since std::function may own heap allocations internally, but since you return the shared_ptr from addListener it could be passed around.  If you never use the returned shared_ptr, you could just store a std::vector<std::function> and return a handle for removal (maybe the handle could contain the index of the function in the vector?).
I can't say whether a vector of functions makes sense for your use case.  If you can avoid callbacks and call functions directly, that's definitely preferable -- makes optimization much easier for the compiler.

Other stuff:
class Callback
{
    using Function = std::function<void(Arguments ...)>;

These typedefs are nice, but could be better.  They should be public since they are used in the public API.  And perhaps the names could be clearer (e.g. VecPtrFunc instead of Functions)?
_functions.erase(std::find(_functions.begin(), _functions.end(), fp));

This seems OK, but if you call this a lot or if functions is big, this will be slow. You might prefer to use a data structure with sub linear lookup/delete like std::map or std::unordered_map.  Or you could use the index-handle idea above and remove from a vector more efficiently.
void operator()(Arguments ... args) const

If you were just calling one callee, this would be Arguments&& and you'd std::forward the args.  Since you use the args... in a loop, I guess this is fine.  Maybe Arguments const& is better in case folks pass in big types and don't want to copy?


k-combinations in lexicographic order (using given algorithm)

combination_find() takes \$O(K^2)\$ time and space because of the pass by value. This is unnecessary overhead and can cause trouble when K is large. Instead we can easily find the position iteratively.

int combination_find(const std::vector<int> &combination, int max_val) {
  for (int i = combination.size() - 1; i >= 0; --i, --max_val) {
    if (combination[i] != max_val)
      return i;
  }
  return -1;
}

This also allows us to pass the vector by reference.

A few more minor points

combination_inc() does not need max_val as a parameter
The push_back()s in the beginning can be replaced with std::iota in C++ 11
Perhaps it is better to combine the find and inc into a single next_combination which returns true if the combination has been updated, similar to the behaviour of std::next_permutation. The behaviour of combination_inc to require pos as an argument and modifying it through main() is strange to say the least.


Re-arrange a string into a { consonant, vowel, consonant, vowel ... } sequence

You have tagged this question with algorithm, and I like algorithm problems. In the spirit of the original question, the solution should not be using any additional space, which means your char vector suggestion at the end is not really relevant. I would agree with your analysis, that the problem is reduced to \$O(n)\$ by storing the vowels and consonants in different vectors, and then merging them again... but that relies on an \$O(n)\$ space complexity too.

I think the solution that the original problem (with no additional storage) is looking for, is a three-pointer option.... a 3-point turn, to make a bad pun.

Consider the following algorithm, which contains three pointers. Each pointer advances sequentially from the beginning to the end of the char array. There is a 'rotate' operation that makes a temp copy of the last char in an array slice, it then shifts all previous chars forward one, and then inserts what was the last char, at the front.

The three pointers consitute an \$O(n)\$ sequence through the data, and the rotate is another \$O(n)\$ operation, but worst-case is n/2, and the worst case will reduce significantly as the pointers advance, and the gap tightens up.... Technically, though, the time complexity combined worst case is \$O(n^2)\$ though.

So, in pseudocode:

set three pointers all to the first char

vowel pointer will, when set, point to the next available vowel - initialize to 0
consonant pointer will, when set, point to the next abailable consonant - initialize to 0
insert pointer - initialize to 0

loop while the insert pointer is valid

advance the vowel pointer to the next vowel (inclusive of the current char)
advance the consonant pointer to the next consonant (inclusive of the current char)
rotate the consonant to the insert pointer.
if the consonant was after the next vowel, indicate that the vowel has advanced 1 char
advance the insert pointer
rotate the vowel to the insert point.
if the vowel was after the consonant, indicate the consonant advanced 1 char
advance the insert pointer
advance the vowel pointer
advance the consonant pointer

So, working off this, and using beginner-level C++ (I am a Java person), I put together the following functions:

bool isVowel( const char ch )
{
  return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

void rotate(char *from, char *to)
{
    char c = *to;

    while (--to >= from)
    {
        *(to + 1) = *to;
    }
    *from = c;
}

void rearange( char *str )
{

  char *vowel, *consonant;
  vowel = str;
  consonant = str;

  while ( *str )
  {
    while (*consonant && isVowel(*consonant))
    {
        consonant++;
    }
    while (*vowel && !isVowel(*vowel))
    {
        vowel++;
    }

    rotate (str, consonant);
    if (consonant > vowel)
    {
        vowel++;
    }
    str++;

    rotate (str, vowel);
    if (vowel > consonant)
    {
        consonant++;
    }
    str++;

    consonant++;
    vowel++;
  }

}

This is in an Ideone here;

The advantages here are that the logic for the boolean on_consonant is removed. Additionally, the pointers only ever advance, and never have to be re-located (if you ignore the rotate...)


Unnecessary optimization

You can safely remove this block of code without changing the behavior of the program:

if sd.l.Len() == 0 {
    sd.Append(updated)
    additions = make([]string, len(updated))
    copy(additions, updated)
    return additions, make([]string, 0)
}

Possible optimization

When you append to additions and deletions,
reallocation might occur.
If you don't mind spending a little extra space,
you could ensure that these slices have enough capacity to avoid reallocation.
You know that the maximum number of additions is the size of the input,
and the maximum number of deletions is the size of the current content:

additions = make([]string, 0, len(updated))
deletions = make([]string, 0, sd.l.Len())

Shorter format declaration

Instead of this:

func (sd *SliceDiff) SortedDiff(updated []string) (additions []string, deletions []string) {

You can use this shorter form:

func (sd *SliceDiff) SortedDiff(updated []string) (additions, deletions []string) {

Naming

Short names are very popular and encouraged in Go.
But l is really the worst of all single-letter variable names.
In addition to the usual badness of these variables,
depending on the viewer program,
l might be indistinguishable from 1 or I or |.
I suggest to never use l as a symbol name.

Alternative implementation

It seems to me that the use of container/List doesn't really buy you much.
It would be simpler and clearer to implement without it.
Consider this alternative implementation using only slices:

// Package slicediff is a utility to determine the additions and deletions that happened to a sorted slice after each update.
//
// All the slices are assumed to be sorted!
package slicediff

// SliceDiff stores the current state of the sorted slice
type SliceDiff struct {
    content []string
}

// New creates a new SliceDiff
func New() *SliceDiff {
    return &SliceDiff{}
}

// Append appends a slice at the end of the SliceDiff
//
// sa is assumed to be sorted
func (sd *SliceDiff) Append(sa []string) {
    sd.content = append(sd.content, sa...)
}

func diff(s1, s2 []string) (added, deleted []string) {
    len1, len2 := len(s1), len(s2)

    added = make([]string, 0, len2)
    deleted = make([]string, 0, len1)

    for i1, i2 := 0, 0; i1 < len1 || i2 < len2; {
        if i1 == len1 {
            added = append(added, s2[i2:]...)
            return
        } else if i2 == len2 {
            deleted = append(deleted, s1[i1:]...)
            return
        }

        if s1[i1] < s2[i2] {
            deleted = append(deleted, s1[i1])
            i1++
        } else if s1[i1] > s2[i2] {
            added = append(added, s2[i2])
            i2++
        } else {
            i1++
            i2++
        }
    }
    return
}

// SortedDiff compares the updated slice with l and returns the additions and deletions performed
//
// updated is assumed to be sorted
func (sd *SliceDiff) SortedDiff(updated []string) (additions, deletions []string) {
    additions, deletions = diff(sd.content, updated)
    sd.content = updated
    return
}


For example,

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func padWithRandomBytes(b []byte) []byte {
    s := 5 + rand.Intn(5+1)
    e := 5 + rand.Intn(5+1)
    r := make([]byte, s+len(b)+e)
    copy(r[s:], b)
    return r
}

func main() {
    rand.Seed(time.Now().UnixNano())
    b := []byte{1, 2, 3}
    fmt.Println(len(b), b)
    r := padWithRandomBytes(b)
    fmt.Println(len(r), r)
}

Output (random):

3 [1 2 3]
20 [0 0 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 0 0 0]

3 [1 2 3]
15 [0 0 0 0 0 0 1 2 3 0 0 0 0 0 0]


General coding style

avoid using var because it obscures the datatypes.
use meaningful variable names.
when comparing ranges, put the thing being tested in the middle and keep both comparison operators the same.
always use the same value for UtcNow, because the clock is ticking.
document every function you write (1 or 2 lines of comments above each function)

Example:

// Returns true if this key value came from GetKey(), false otherwise.
public static bool IsKeyValid(long testKey)
{
    long k = GetKey();

    double allowedVariance = 0.00000000004;   // say what this is ...

    // You use of 'var' obscured the differing datatypes: k and testKey are long.
    double variance = k * allowedVariance;

    return (k - variance <= testKey && testKey <= k + variance);
}

// Returns a key based on the current time.
public static long GetKey()
{
    DateTime now = DateTime.UtcNow;

    // Explanation is called for here...
    long i = now.Ticks * 5;
    long d = (long)Math.Sqrt(Math.Ceiling(400 - (now.Day * Math.PI)));
    long k = (long)((Math.Round((Math.Sqrt(i) * Math.Pow(Math.PI + d, 3)) * Math.E - d)) * d) + now.Minute;

    return k;
}

I know nothing about encryption so cannot say whether there are built-in .NET functions which perform the same task, but there probably are.


Hello World Node application with error handling

If you're going to continue using raw, low level, http then you've done good enough (although you should probably return a 500 response code back to the client). In reality though, you're unlikely to continue working with Node at such a low level. Most Node applications are going to use a framework like Express, which has the concept of Middleware. Typically, you'd use some middleware to handle runtime errors.

RisingStack has a great tutorial for creating a simple Express server with middleware error handling.


Find next occurring Friday (or any dayOfWeek)

Since you say "Given a particular Date" and "next occurring Friday (or any dayOfWeek)" I think both should be parameters to your function. As it is written, it will only return November 15 always.

function dates(date, dayOfWeek)

But then you should check that dayOfWeek is in range (0-6, thanks SridharVenkat) and probably that date is a valid Date object.

If you do this, you also have to consider not modifying the date parameter and copy it instead.

The names on the variables are clear enough, but not of the function, dates is too broad. getNextDayOfWeek says a lot about what this function does.

function getNextDayOfWeek(date, dayOfWeek)

The logic is correct, I think, I only tested it with a few numbers. But you instead of + ((-1) * diff)) you could simply do - diff.

Finally, you're always outputting the result to the console. If this is more than an exercise, you should return the result, and let the user of the function do with it whatever he/she needs.

Edit: As SridharVenkat said, the range should be 0-6 not 1-7.

Also, using modulo like AlexAtNet suggested you can reduce the code with
resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7)

My (edited) proposal:

function getNextDayOfWeek(date, dayOfWeek) {
    // Code to check that date and dayOfWeek are valid left as an exercise ;)

    var resultDate = new Date(date.getTime());

    resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);

    return resultDate;
}

PS: Please correct me if I said something wrong of if there's more to improve.


Couple of minor simplifications:

nums =[]
...
nums.append(random.sample(...))
nums = nums[0]

could be replaced with:

nums = random.sample(...)

The add/jugglenum loop calculation could be done with:

jugglenum = abs(sum(nums[::2]) - sum(nums[1::2]))

This code:

for i, x in enumerate(rand):
    rand[i] = ''.join(random.sample(str(x), len(str(x))))

could be replaced with:

rand = [ ''.join(random.sample(s, len(s)) for s in (str(x) for x in rand)]

which eliminates the enumeration and avoids turning x into a str(x) twice.

I don’t see strs being used anywhere, so the code that calculates it can be removed.


Here's what I did

var theMatrix = (function (containerId, lines, columns) {
    // We wrap everything in a closure, and expose only a single
    // global. Avoids global pollution, and keeps everything in
    // one place.

    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    // We break functionality into functions, naming verbosely
    function randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function randomGreen() {
        return "#00" + randomInt(0, 255).toString(16) + "00";
    }

    function randomLetter() {
        return characters.charAt(Math.floor(Math.random() * characters.length));
    }

    function generateLine(columns) {
        var line = document.createElement('div');
        while (columns--) {
            var letter = document.createElement('span');
            letter.style.color = randomGreen();
            letter.innerHTML += randomLetter();
            line.appendChild(letter);
        }
        return line;
    }

    function writeLines(container, lines, columns) {
        for (var i = 0; i < lines; i++) {
            container.appendChild(generateLine(columns));
        }
    }

    function startMatrix(container,columns) {
        setInterval(function loop() {
            // Instead of rebuilding the DOM all at once, we change
            // by line, by removing the top line, and appending
            // at the bottom.
            var firstLine = container.firstChild;
            container.removeChild(firstLine);
            container.appendChild(generateLine(columns));

            // Also, used doesn't care, you can replace the line
            // before this with the following line to cycle the
            // lines instead of regenerating the last line
            //container.appendChild(firstLine);
        }, 50);
    }

    // The exposed function. The only function that "keeps state"
    // (knows instance settings). All other function are reusable
    // and are not bound to a single call
    return function (containerId, lines, columns) {
        var container = document.getElementById(containerId);

        // we write the initial lines
        var textNodes = writeLines(container, lines, columns);

        // start the matrix
        startMatrix(container,columns);
    };
}());

theMatrix('mat', 50, 80);


'coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = true OR (? AND purchases.user_id = ?)',
LOWEST_VOTE,
!user.id.nil?,
(if user.id.nil? then -1 else user.id end)

This is semantically equivalent to both, but the AND in the third clause prevents it from having an effect when there is no user.id.


Long cache refresh with guaranteed response

How do I use this?

I don't understand how to use this.  It took me some time to understand the reason for the getter, and I can't see how to retrieve anything from this cache.

Why do I need to Add the value when I have the delegate?

In the Add method, it doesn't make sense to add provide both a value and a method that calculates the value; it is very likely that someone will pass in inconsistent arguments and get unexpected results.  It should suffice to simply pass in the delegate, and let the value calculate itself.

Why is this static?

It is very dangerous to have one global cache holding every different type.  You should allow for multiple caches for different purposes, and then you can...

Make this cache generic

Nobody likes to cast from Object.  Your interface should be Cacheable<T>, so that we can check at compile time that the type to be returned is what we expect.

Your response is not guaranteed

Your callback is only called after the item has been removed from the cache.  Even if you add the previous value back straight away, a poorly-timed interrupt could have another thread searching for a key in that split-millisecond it's not there.


I am assuming you have the correct target to transform (the input array is filtered).

If you are using es6:

const input = [
    {
        "setId": "setA",
        "prodId": "A",
        "price": 5,
        "deliveryCost": 1,
        "name": "Set_Prod01"
    },
    {
        "setId": "setA",
        "prodId": "B",
        "price": 5,
        "deliveryCost": 2,
        "name": "Set_Prod01"
    }
];

const output = {
    "setId": "setA",
    "prodId": "A,B",
    "price": 5,
    "deliveryCost": 3,
    "name": "Set_Prod01"
};

const groupBy = (input) => (
    Object.assign(
        input[0],
        {
            prodId: input.map(set => set.prodId).join(','),
            deliveryCost: input.map(set => set.deliveryCost).reduce( (cur, next) => cur + next)
        }
    )
);

console.log(output);
console.log(groupBy(input));

If you are using es6 and stage-2 object spread operator, change the function to:

const groupBy = (input) => (
    {
        ...input[0],
        prodId: input.map(set => set.prodId).join(','),
        delivertCost: input.map(set => set.deliveryCost).reduce( (cur, next) => cur + next)
    }
);

If you are not using es6, simplest method is use it, and use babel to convert it into es5 compatible code. It's less code, more readable and easier to maintain.

EDIT:
The function above simply take an array of objects and assign them into another object. Note that in Object.assign, the latter's value will overwrite the former's value with the same key, so you can easily implement the overwriting rule you mentioned. The value are simply some functional programming, one join the array of string, and the other sum up the values.


Bug

This line seems wrong:

double result1 = (Math.Pow(2, exp1) % i)*C;

It seems like you are implying that:

\$x^y \mod m = ((x \mod m)*y) \mod m\$

But I believe the actual relationship is:

\$x^y \mod m = (x \mod m)^y \mod m\$

This probably explains why your program thinks the known Mersenne prime is divisible by 7.

Loop termination, or lack of it

Your loop is like this:

for (long i = 3; i <= (big/i); i+=2)//***comment below

But big is \$2^{74207281} - 1\$.  Therefore, you intend your loop to run until i reaches \$\sqrt {2^{74207281}-1}\$, meaning i needs to reach about \$2^{37103640}\$.  Unfortunately, your loop index is a long and not a BigInteger, so it can't even represent the numbers you need to represent.  But even if you made i a BigInteger, the loop would run virtually forever because you would need to reach that huge number before you could stop.


Toggling the background color of a page using JavaScript closures

This is a partial answer, that only addresses style, but I prefer something like this for the changeColor function.

I'm not thrilled with activateColorButton, but it works.

This is much more readable and maintainable to me:

const changeColor = e => {
    const lightOrange = "rgb(221, 238, 255)"
    const lightBlue = "rgb(255, 238, 221)"
    const {style} = document.body
    style.backgroundColor = style.backgroundColor === lightOrange
        ? lightBlue
        : lightOrange
}

const activateColorButton = e => {
    const btnColor = document.querySelector('#color');
    btnColor.removeEventListener('click', changeColor);
    btnColor.addEventListener('click', changeColor);
}

Some Explanation:

TLDR

Use good variable names
Avoid duplication
Use whitespace effectively
Prepare assignments for future abstraction

/TLDR

In changeColor, I have eliminated as much duplication as possible by assigning variables with names that are deliberately chosen to help the code to describe what it does without additional comments.

Moving the variable names to the top of the function allows them to be extended, changed, or even abstracted out to another function or data structure entirely.

The repeated reference to document.body.style.backgroundColor takes up half of a line of code, is very distracting, hard to read, hard to reason about, and unnecessary. style.backgroundColor could not be reduced to simply backgroundColor. This was as far down as it would go without losing functionality.

I personally find the compactness of the tertiary if statement to be more readable than the explicit if statement and especially prefer it when either assigning or returning one of 2 choices.

I renamed activateButton2 to activateColorButton b/c it more clearly expresses its purpose.

In activateColorButton, I chose to remove the click handler if it's already there and reassign it, rather than have confusing 'flag' variables lying around. I'm not thrilled with it b/c, ideally, it would check to see if the click handler was already assigned via the DOM directly, but I was too lazy to implement that here, which seems ok in this case.


Optimize Recursive Function to traverse nested DOM nodes

Note that when you do document.querySelectorAll you are getting not a single node but a list of nodes. This seems to be causing confusion because your function refers to node.length - but a single node does not have any length property. Your original function also does not seem to behave exactly as you want it to in that it excludes the parent node (a in your example).

If you ensure that you are passing the function a single node, then it can indeed be simplified a lot:

function getTree(node) {
    var r = {tag: node.nodeName}, a, i;
    if (node.childElementCount) {
        r.children = [];
        for (i = 0; a = node.children[i]; i++) {
            r.children.push(getTree(a));
        }
    }
    for (i = 0; a = node.attributes[i]; i++) {
        r[a.nodeName] = a.nodeValue;
    }
    return r;
}
var links = document.querySelectorAll('a');
console.log(getTree(links[0])); // only pass the first node to the function

(JSfiddle here)


Is there a better way to retrieve variables from class method

Instead of

list1 = []
for element in test:
    list1.append(element)
for x in list1:
    A,B,C,D,E,F,G,H,I = list1

you could simply write

A,B,C,D,E,F,G,H,I = test

Regardless, here's a slightly different approach.

Assuming that the input json structure is { 'country': [{ }, ..., { }] },
I'd slightly modify self.data:

 self.data = {country['Cname'].lower(): country
              for country in json.loads(r.text)['country']}

then access this dictionary whenever required. Possibly by overwriting __getitem__:

def __getitem__(self, key):
    return self.data[key.lower()]

Then you can access the inner dictionary using [ ]:

GlobalDataLoader(API_KEY,PROJECT_TOKEN)['china']
GlobalDataLoader(API_KEY,PROJECT_TOKEN)['china']['population']

Here I've renamed the Data class: I don't expect the constructor of a class named Data to access the internet, and the data seems to be global.
Still, I'd remove the self.get_data() call from __init__.

On the other hand, if you are not planning to reuse the (API_KEY, PROJECT_TOKEN) for a specific GlobalDataLoader instance, then I wouldn't store these in the instances. Instead do something like

data = GlobalDataLoader(project_secrets)

where

class GlobalDataLoader:
    def __init__(self, project_secrets):
        self.load_data(project_secrets)

    def load_data(self, project_secrets):
        url = f"https://www.parsehub.com/api/v2/projects/{project_secrets['project_token']}/last_ready_run/data"
        r = requests.get(url, params={"api_key": project_secrets['api_key']})
        self.data = {country['Cname'].lower(): country
                     for country in json.loads(r.text)['country']}

    def __getitem__(self, key):
        return self.data[key.lower()]

That being said, don't hard-code secrets into the source code.

API_KEY = "XXX"
PROJECT_TOKEN = "XXX"
RUN_TOKEN = "XXX"

You don't want this as a habit when you start using version control systems. Store these in a separate file. If you have to store that in a VCS, then encrypt it (e.g. use gitcrypt).

To reuse the idea of a wrapped dictionary, you could write a

class ProjectSecretsLoader:
    def __init__(self, config_file_path):
        self.load_config(config_file_path)

    def load_config(self, config_file_path):
        self.config_data = dict() # TODO

    def __getitem__(self, key):
        return self.config_data[key]

then do

config_file_path = "..."
project_secrets = ProjectSecretsLoader(config_file_path)
data = GlobalDataLoader(project_secrets)

Last, but not least requests.get might fail, json.loads might fail. The result of json.loads might not have the structure you expect, or might be missing the country you will eventually try to look up, etc. In these cases specific exceptions will be raised, which ideally should be handled, otherwise the program will crash.


Personally I prefer avoiding such nested if-else constructs, simply by reversing the logic, e.g.:

if(!cond1)
    return value;
if(!cond2)
    return value2;
// etc.

instead of:

 if (cond1)
     if(!cond2)
         return value2;
 else
     return value;


There are no docstrings. What is the purpose of each of your classes and methods, and how am I supposed to call them?
If you click outside the button, and then slide the pointer over the button, it becomes active. Normal GUI buttons require the initial click to be on the button in order to be able to activate it.
The class name Surface runs the risk of confusion with pygame.Surface. Or in some applications, of shadowing it.
The GUIElement class is a Surface with an id. But none of the code uses the id, so this class is useless. (No doubt you have some purpose in mind, but what is it?)
Calling sys.exit() makes it awkward to test your program from the interactive interpreter.
If you care about portability to Python 2, you should make Surface inherit from object so that it is a new-style class. On the other hand, if you don't care about portability to Python 2, just call super() instead of super(GUIElement, self) or whatever.
Surface takes arguments x, y, w, h. Why not use a pygame.Rect? Then you could just call Rect.colliderect instead of writing your own version.
Surface.draw does nothing. Is this because Surface is an abstract base class? If so, you should use metaclass = ABCMeta and decorate the draw method with @abstractmethod to make this clear.
In order to create a coloured button, you have to create the Button object and then call its decorate method to set its colours. Why not allow the caller to set the colours when they create the button? (Via optional keyword arguments.) Similarly for the font.
Since you can deduce a button's color from its state, you don't need a separate color attribute (or do you?). By having two attributes you run the risk of them getting out of sync. Why not have a map from state to colour?
up, down, middle are misleading variable names: the values returned by pygame.mouse.get_pressed() are actually the state of the three mouse buttons. Use names like button1, button2, button3.
pygame.mouse.get_pos() returns the mouse coordinates (x, y) so it's not clear why you write if len(mouseCoords) < 4. Won't this always be true? And why do you need to make a rectangle here anyway?


Find and report all occurrences of duplicate lines in a text file

I don't know about Awk, but for this section of code:

END {
# If the file contains no lines to process, that is, it's empty,
# return an exit status code of 1 to indicate the fact.
if (!(NR > 0)) {
    exit 1;
}

You should print out an appropriate message to the terminal instead of just exiting with exit code 1. This, in my opinion, provides users with better feedback.


No algorithmic improvement, just some cosmetics...

import System.Environment
import Data.Ord
import Data.List

-- The number of items we keeps to only search
-- from bests local results
nbToKeep :: Int
nbToKeep = 10

type Match = (Int,Int)
type MatchSequence = [Match]

-- gives a different order, but I think this is okay
all_matches :: Int -> MatchSequence
all_matches n = [ (x,y) | y <- [2..n], x <- [1..(y-1)]]

-- A price function for sequence of matches
-- 0 if no team make a match just after finishing one
-- Possible with 5 teams not for 3 and 4
price :: MatchSequence -> Int
price xs =  sum $ zipWith comp xs $ tail xs where
   comp (x,y) (z,t) = fromEnum $ x==z || x==t || y==z || y==t

-- Simple adjoin the price to a MatchSequence
addPrices :: MatchSequence -> (Int,MatchSequence)
addPrices xs = (price xs, xs)

-- Instead of listing _all_ permutations
-- Just keep the one such that its subsequece price
-- is under the threshold
myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              ((<= threshold).price)
                              (myPerm (delete x xs) threshold)]

-- Keep the best one under some threshold
find_best_under n threshold = take nbToKeep $
                                sortBy (comparing fst) $
                                    map addPrices ( myPerm (all_matches n) threshold)

-- Try to test with the minimal threshold (0)
-- Then repeat until a solution is found for some threshold
find_best n = head $ filter (not.null) $ map (find_best_under n) [0..]

showMatchSequence :: MatchSequence -> String
showMatchSequence [] = []
showMatchSequence ((team1,team2):[]) = show team1 ++ "-" ++ show team2 --is this case needed?
showMatchSequence ((team1,team2):xs) = show team1 ++ "-" ++ show team2 ++ "   " ++ showMatchSequence xs

showResult :: (Int,MatchSequence) -> String
showResult (score,xs) = show score ++ " collisions: " ++ showMatchSequence xs

main = do
    args <- getArgs
    mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int)


Comments about your current code first:

Closing the Stream

The method Files.lines(path) returns a Stream<String> over the lines of the file. This stream should be closed because it encapsulates a Reader of the file. The documentation mentions that:

  If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

Therefore, the method populateWordMap should be using a try-with-resources:

try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
    // ...
}

Allocating unused objects

You currently allocate the wordMap with a new hash map, and then store the result of invoking populateWordMap in it.

Map<String, Long> wordMap = new HashMap<>();
try {
    wordMap = populateWordMap("C:\\Outils\\eclipse-mars\\workspace\\test\\text.txt");

The consequence is that the first hash map that was created for nothing: it is unused and will be garbage collected. Best not to create it in the first place.

Empty catch blocks

try {
    // something
} catch(IOException e) { }

is generally not a good idea: you are completely swallowing the exception that could be thrown and giving no information. You could log the exception to tell what went wrong; you could also rethrow it; or you could even let the main method throw it, since there is really nothing you can do at this level when something wrong happens.

Handling empty Optional

Your findMostPopularWord method is searching for the word appearing the most times. It works by correctly using the max operation. But then, you have:

.max(Map.Entry.comparingByValue()).get().getKey();

To get the key of the entry having the max value. The problem is that when the Stream is empty, max will return an empty Optional and the explicit call to .get() will throw an exception. This raises the more general question of what you want to happen where the scanned file is empty (and contains no words). Among the possible solutions: just return null or throw a custom exception. For those two solutions, you can use .orElse(null) or orElseThrow(...), instead of get.

Looping over all files in a directory

I'll note that your current solution only works by counting word occurences in a single file when the original task was to do it for all files in a directory. For that enhancement, you can use Files.list(path) which returns a Stream<Path> of all the files under the given path.

The current flow of your code is:

Loop over each line of the file
Split each line in an array of words
Replace each array of words with a map containing the occurrences of each word
Replace each of those map with another map containing the occurrences of each entry's value.

This is not very efficient: you are converting each line into a map, only to disregard them later and create another map out of all those maps.

The problem is that you're thinking in terms of "line in a file" when the actual task is to count space separated words. For this task, you can use a Scanner:

private static Map<String, Long> populateWordMap(String filePath) throws IOException {
    try (Scanner scanner = new Scanner(Paths.get(filePath))) {
        Iterable<String> iterable = () -> scanner;
        return StreamSupport.stream(iterable.spliterator(), false)
                     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}

A scanner tokenize by default around single spaces. We can then convert the scanner (which is an Iterator) to a Stream and group by each word while counting their occurences.


pop() function
For this review, I'll only look at the pop() function, as it is representative of the whole program:

int pop(struct Stack **top,char str)
{
        char op,ret;
        struct Stack *temp=*top;
        if(*top==NULL)
                return 0;

        else if(*top!=NULL)
        {
                // Pop the element and then call comapre function
                op=(*top)->data;
                free(temp);
                *top=(*top)->next;
                return(ret=compare(str,op));
        }
return 1;
}

Purpose of the function
The first thing is that the function doing more than what its name says.  Not only is it popping an element off the stack, it is also trying to determine the correctness of the close brace with the open brace.  Ideally, your pop function should just pop an element off the stack and let the caller do the rest.  It's not a good idea to combine multiple unrelated tasks into single functions.
Naming
I don't particularly like top as the name of your stack but I can live with it.  But str is a terrible name for a character.  Anyone who reads your code will think that str is a string.  Especially because in main you have a string named str.  I don't really like op either.  What does it mean?
Useless variable
The variable ret is useless and can be removed.
Useless statements
The else condition is always true and can be removed.  The return 1 at the end can never be reached and can be removed.
Use of freed variable
You call free() before you set the stack to the next element, which is a mistake.  You are actually reading the next pointer from memory that is already freed.  You should reverse the order of those two statements.
Indentation
Your indentation is a bit strange with the return 1 unindented.
Rewrite
If you want to keep it in one function:
int popAndCompare(struct Stack **pStack, char closeBrace)
{
    struct Stack *top = *pStack;
    char openBrace;

    if (top == NULL)
        return 0;

    // Pop the element and then call compare function
    *pStack   = top->next;
    openBrace = top->data;
    free(top);
    return compare(closeBrace, openBrace);
}

Otherwise, separate the tasks:
char pop(struct Stack **pStack)
{
    struct Stack *top = *pStack;
    char ret;

    if (top == NULL)
        return '\0';

    *pStack = top->next;
    ret     = top->data;
    free(top);
    return ret;
}

int main(void)
{
    // ...
            char openBrace = pop(&stack);
            if (!compare(str[i], openBrace)
            {
                printf("\n Unbalanced Expression ");
                flag=1;
            }
    // ...
}


I have to question whether this makes any sense in your application:

Assume the server is sending data to our app at regular intervals, at least once per second

Have you done any testing/metrics that indicate that the current system you have is actually a problem? I would be very surprised if it is.
If the server is sending data as infrequently as that, there does not seem to be any reason to 'pool' the objects at all. The overhead of 'cleaning' an instance, storing it, recycling it, repopulating it, and repeating with it is probably just as overwhelming as simply creating a new instance and GC'ing the old one.
Unless you can already identify 'specifically' that object creation is a significant part of an existing performance problem, I would suggest that you are looking in the wrong places for performance improvements.
EDIT - hypothetically...
Answering hypothetically: no, I don't believe your solution is enough...

by the time you get to the frequency where object creation/reuse is a problem, you will be needing multiple concurrent threads to do the work anyway, and your solution is not synchronized (by the way, new and GarbageCollection are thread-safe)
You have created an artificial latency in your program flow - see Ahmdahl's law .. by adding to the critical path instead of taking work off the path (parallelizing things). As your system gets busier, you are making the problem worse and not better.

Bottom line, is that, at low volumes your current solution is not going to make a difference, and that at high frequencies, your solution is only going to make things worse.
One other thing to consider, and Android performance is not my strength, but on 'full' computers (I often work with systems with more than 128 cores in highly-threaded systems), the cost of having to bring the stack in to your system cache, and then replace it with the cache of your object is probably going to be more than just creating a new object would... Again, the more busy your system, the more this sort of issue 'hurts'.