Delete duplicates from unsorted linked list

I also am not a fan of the code organization. I think a better way to approach this would be to implement the List interface around an ordered set like a LinkedHashSet as something like a SetList. Many of the methods could simply be delegated to the internal set, and only a few would really be left to implement.

Your code has a separate method, eliminateDuplicates, to filter out the duplicates, rather than filtering them as they are added. This means that, if that method is not called, the list is not consistent with its requirements. I would still get all the duplicates. A better strategy is to remove the duplicates as they are added to keep the list always consistent with its advertised behavior.

Lastly, the names of your test methods could use a little work. Names like test1 and test2 don't tell much of what the tests are or what they are testing.

Here's an example of such an implementation. It implements both List<T> and Set<T>, and so can be used in either place. I used two internal structures for simplicity.

public final class LinkedHashSetList<E> implements Set<E>, List<E>
{
    private Set<E> set;
    private List<E> list;

    public LinkedHashSetList() {
        set = new HashSet<>();
        list = new LinkedList<>();
    }

    public LinkedHashSetList(Collection<? extends E> c) {
        // LinkedHashSet so I don't have to track uniqueness and order
        set = new LinkedHashSet<>(c);
        list = new LinkedList<>(set);
    }

    @Override
    public boolean add(E el) {
        if(set.contains(el)) {
            return false;
        }

        list.add(el);
        set.add(el);
        return true;
    }

    // Optional method not implemented
    @Override
    public void add(int index, E element) {
        throw new UnsupportedOperationException("LinkedHashSetList#add(int, E) not implemented!");
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean isChanged = false;

        for(E el: c) {
            isChanged = isChanged || add(el);
        }

        return isChanged;
    }

    // Optional method not implemented
    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        throw new UnsupportedOperationException("LinkedHashSetList#addAll(int, Collection<? extends E> c) not implemented!");
    }

    // Optional method not implemented
    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException("LinkedHashSetList#retainAll(Collection<?> c) not implemented!");
    }

    @Override
    public E remove(int index) {
        E el = list.remove(index);
        set.remove(el);
        return el;
    }

    @Override
    public boolean remove(Object el) {
        list.remove(el);
        return set.remove(el);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        list.removeAll(c);
        return set.removeAll(c);
    }

    @Override
    public void clear() {
        list.clear();
        set.clear();
    }

    // Optional method not implemented
    @Override
    public E set(int index, E el) {
        throw new UnsupportedOperationException("LinkedHashSetList#set(int, E) not implemented!");
    }

    @Override
    public E get(int index) {
        return list.get(index);
    }

    @Override
    public boolean contains(Object el) {
        return set.contains(el);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    @Override
    public int indexOf(Object el) {
        return list.indexOf(el);
    }

    @Override
    public int lastIndexOf(Object el) {
        return list.indexOf(el);
    }

    // WARNING: Changes to sublist can affect this list in undefined ways
    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        return list.subList(fromIndex, toIndex);
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public int size() {
        return list.size();
    }

    // Not safe if remove is called on iterator
    @Override
    public Iterator<E> iterator() {
        return list.iterator();
    }

    // Not safe if remove is called on iterator
    @Override
    public ListIterator<E> listIterator() {
        return list.listIterator();
    }

    // Not safe if remove is called on iterator
    @Override
    public ListIterator<E> listIterator(int index) {
        return list.listIterator(index);
    }

    @Override
    public Object[] toArray() {
        return list.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Unit Tests:

public class LinkedHashSetListTest
{
    @Test
    public void testRemovesDuplicates() {
        LinkedHashSetList<Integer> lhsl = new LinkedHashSetList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 1, 7, 4, 6, 6));
        Integer[] expected = { 1, 2, 3, 7, 4, 6 };
        assertArrayEquals(expected, lhsl.toArray(new Integer[expected.length]));
    }

    @Test
    public void testRemovesNothingWhenNoDuplicates() {
        LinkedHashSetList<Integer> lhsl = new LinkedHashSetList<>(Arrays.asList(1, 2, 3, 7, 4, 6));
        Integer[] expected = { 1, 2, 3, 7, 4, 6 };
        assertArrayEquals(expected, lhsl.toArray(new Integer[expected.length]));
    }

    @Test
    public void testEmptyList() {
        LinkedHashSetList<Integer> lhsl = new LinkedHashSetList<>(new LinkedList<Integer>());
        Integer[] expected = {};
        assertArrayEquals(expected, lhsl.toArray(new Integer[expected.length]));
    }
}

Caveats regarding sublists and iterators are noted. The solution to the iterators would be to create a new Iterator specifically for this class. Sublisting is a bit more complicated to solve, since the sublist is backed by the original list.


Create an array of categories from comma-seperated text input

That same operation can be streamlined into:

var categoriesJoined = event.target.category.value
  .split(',')
  .map(function(category){ return category.trim(); })
  .filter(function(category){ return !!category; })
  .concat(['Inbox']);

or Inbox first:

var categoriesJoined = ['Inbox'].concat(event.target.category.value
  .split(',')
  .map(function(category){ return category.trim(); })
  .filter(function(category){ return !!category; }))

We split first by , giving us access to an array.
We clean up each item using map by returning a cleaned value using trim
Then filter out those who are totally whitespace (they end up as blanks when trimmed).
Add in "Inbox".


For a beginner this is pretty good.
But, there are three glaring problems with it.

You should use a 'main' function.
You should use a dictionary.
operators

Starting with (2), a dictionary holds a key value pair.
If you've come across lists/arrays, it's like them,
apart from that you can use a lot of different types,
not just integers.

Defining one is pretty easy,
and using it will reduce your amount of code.

operators = {
    "+": add,
    "-": sub,
    "*": mul,
    "/": div,
    "pow": pow
}

This will define an object to hold all the operators that you can use.
Now all we need to do is use it.
Using operators.get it's easy.

func = operators.get(operator, None)
if func is None:
    print("Invalid operator!")
    continue

Lovely and simple.

The main function is simple, just move everything in if __name__ == '__main__':
into a function.
With the operator addition you shouldn't really need to make smaller functions,
but it may be a good idea, making a function to get user input, could be a good idea.
But it's up to you.
If you did want to do both of these, you'd do something like:

def main():
    while True:
        number1, number2, operator = get_user_input()
        func = operators.get(operator, None)
        if func is None:
            print("Invalid operator!")
            continue

        print(func(number1, number2))

if __name__ == '__main__':
    main()

Just to note, you may not want to make get_user_input.

Something that you may not know is you can use the builtin operators library.
This will allow you to remove all your definitions of add, sub, etc.
And will allow you to change operators to:

import operator

operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
    "pow": operator.pow
}

There's some history about Python's division, and that's why it's called truediv, but if you haven't and won't use Python2, then you don't really need to know.


Calling a copy constructor in Presenter to prepare a list of Models

At first glance, there seems to be something off in the structure.

You wish to display a list of IAttendance objects on the screen. To me, this means that the Model is a list of IAttendance objects but the code shows only a single IAttendance instance being passed into the constructor.  How do you get more than one item into the presenter?

It has been a long while since I used MVX under WinForms, so some of what I remember may be off, but I would have a Model consisting of a list of IAttendance objects (not a single object) and just add them to a BindingList.  There should be no need to copy the objects. (If you want to edit them, make them implement IEditableObject).

Bottom Line
There should be no need to copy the objects just to show them in a list.
If you want the screen to display a list of objects then the Model should consist of a list of objects, not a single one
If you want to edit the objects, implementing IEditableObject is a better path than copying/saving and restoring on cancel.


Short answer: no.

But you'll probably need some explanation to believe me.

The whole Node thing you got there should be internal information to the Tree class, not part of the type. Let's look at the following example method to show why it's a bad idea:

private static void addARandomNumber(Tree<Node<Number>> tree) {
    int randomNumber = generateRandomNumber();
    Node<Number> = new ... ???
    tree.addNode(node);
}

What class should we use to create a new Node here?

Had the Node been completely internal to the Tree implementation then the interface would look like this:

interface Tree<T> {
    boolean add(T node);

    boolean remove(T node);

    String toString();
}

And now we can also write the add random number method easily:

private static void addARandomNumber(Tree<Number> tree) {
    int randomNumber = generateRandomNumber();
    tree.add(randomNumber);
}

I also got a feeling that forcing some ordering on T, as required in most search trees, will be rather hard in your current design. But that might just be because I didn't really try it myself yet.

Defining the type of the search tree correctly would probably work, but I expect some type erasure issues with the addNode and removeNode methods.


Reduce time taken for VBA loop when copying multiple sets of input values, performing Excel formula calculations and recording results

Use descriptive variable names. r as a variable name tells you nothing and makes your code harder to read. rowOffset tells you what it's used for. This goes a long way to make your code readable.

Declare your variables just before you use them. You only have 2 currently but its easy for variables to increase. Instead of having a wall of declarations at the top of a Function/Sub, like below:

dim r as long
Dim i as long
dim p as range
dim sv as range

Have them declared just before they get used.

dim lastRow as long
lastRow = Worksheets("MCInput").Cells(Rows.Count,"B").End(xlUp).Row

dim rowOffset as long
For rowOffset = 0 to (lastRow - 2)
    `Code that does what you want
Next

This ultimately aids you in refactoring (restructuring) your code when you need to. It also becomes easier to tell when a variable is no longer needed. No code using the variable just after it's declared? Delete it. With a wall of declarations you have to laboriously check for usage. There are tools like Rubberduck, which I'm a contributor to, than can tell you if a variable is used.

You're using a string literal populated with a worksheets name to access the worksheet through the hidden Global object's Worksheets property IE Global.Worksheets("Calcs"). This returns an Object variable which is late-bound and doesn't give you intellisense when you use . (period) after the collection. It's preferred to use the Worksheet.CodeName. You can see this in the Project Explorer window. The CodeName of the worksheet is Sheet1 while the Name (What is shown in the tab) is Calcs.

Sheet1 isn't a helpful name, this ties into using descriptive names above, so we'll change it by double clicking on it in the Project Explorer to display the code behind for the worksheet, then pressing F4 to display the Properties Window (also found under the menu at the top View>Properties. At the top where it says (Name) change it to something more descriptive.

Now instead of using Worksheets("Calcs") use CalculationSheet to access the worksheet object. The same thing can be done to. Two added benefits:

You're no longer dependent on the literal string "Calcs" which stops working if the worksheet is renamed.
You get intellisense. Type CalculationSheet. (note the period) to show a list of accessible members.

There's more that can and probably should be done with your code. Things like worksheet properties would help to clean up and shorten the code which then leads to the realization you'd benefit from creating a proxy for accessing your data. I was nerd-sniped by this already and that can be for another review.


Find the no of pairs whose sum divides the product from 0 - 1000000000

These kind of puzzles have to be solved by first analyzing the problem.
If you look at the samples that you have already found you will notice that in all samples the two numbers share a rather large common factor. This makes sense, since if a and b have a common factor then both a+b and a*b are divisible by this common factor, which increases the probability that a+b divides a*b. So let's try to find out more formally when (a,b) is a good pair:

Let g=gcd(a,b). Then there exist integers r,s with

a = r * g
b = s * g

Then

a + b = (r+s)*g
a * b = r*s*g^2

Thus a+b divides a*b if (r+s)*g divides r*s*g^2 and hence if r+s divides r*s*g.
Also since g is the greatest common divisor it follows that r and s have no divisor in common (i.e. gcd(r,s)=1). From Euclid's algorithm follows that gcd(r+s,r) = 1 and
gcd(r+s, s) = 1 and hence also gcd(r+s, r*s) = 1. Thus if r+s divides  r*s*g then
r+s must divide g.

Thus all the good pairs below a bound N can be described as follows:
If r,s,k are integers such that 1 < r < s < N^0.5, gcd(r,s)=1 and s * (r + s) * k <= N then (a,b) = (r * (r + s) * k, s * (r + s) * k) is a good pair.

Implementing this isn't hard. Running the algorithm up to 10^9 takes a few minutes (depending on the programming language).

One big question remains: Why on earth has the problem been migrated to "Code review"?


New features for Processing game/desk accessory

How about something where if you change the background to a particular color, something cool happens?

Like if it turns full black,(0,0,0), it causes an image to pop up on screen.


First of all, this kind of manipulation is done using CSS. E.g. http://blog.teamtreehouse.com/css-sprite-sheet-animations-steps

Nevertheless, let's see what can be improved:

Instead of nth-child selectors, use classes instead

It provides some meaning to the images, and you can replace the src easily afterwards:

Refactor the code into a general function that handles the styling

var style_switcher = function(first, second, third) {
    document.querySelector(first).style.display = "initial";
    document.querySelector(second).style.display = "none";
    document.querySelector(third).style.display = "none";
};

Use named constants

var TIMEOUT = 300;
var INTERVAL = 600;

This will make things easier when you want to change the values.

Put everything together

window.setInterval(function(){
    if(animation_hovered == false){
        style_switcher('.first-frame', '.second-frame-glow', '.second-frame');
    }else{
        style_switcher('.first-frame-glow', '.second-frame-glow', '.second-frame');
    }
    window.setTimeout(function(){
        if(animation_hovered == false){
            style_switcher('.second-frame', '.first-frame', '.first-frame-glow');
        }else{
            style_switcher('.second-frame-glow', '.first-frame', '.first-frame-glow');
        }
    }, TIMEOUT);
}, INTERVAL);

If there is more common behavior, you can abstract that into a function.

Good luck!


How to simplify these delegate functions?

You can use the generic delegate Func<>:

static private T TryThis<T>(Func<T> MyAction) {
    try {
        return MyAction();
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        return default(T);
    }
}


Looking at each of the tables, there are a few design problems that stand out.
Country
Depending on the target countries and language, some country names could be longer than 50 characters. For example, "Separate Customs Territory of Taiwan, Penghu, Kinmen, and Matsu (Chinese Taipei)", the longest English country name, is 80 characters long, meaning you would get an error from the SQL database in [Name] [nvarchar](50) if you tried to insert this value.
For the [Code] [nchar](10) there is already some official lists of country codes (reference) which could only be a [nchar](2) field for ISO codes, or a [nchar](3) field for UN codes. Using a standard country code would also make it more standards-compliant.
Error
The [Message] [nvarchar](max) and [Stacktrace] [nvarchar](max) are problematic. You should avoid using the MAX types unless you actually need to store up to 2 GB of text in a field (or just over 1 billion 2-byte characters - source). See Using MAX text or more specific, smaller type from Database Administrators site. The reasoning is in large part because the MAX types are stored outside of the table, only a reference to the field is stored in the table, and as such they are optimized differently.
[CreatedDate] [nvarchar](max) should instead be a [datetime2] or similar type like you are using in other places, and not a character field. Never store dates and/or times in a text field (and especially not in a MAX text field), as it makes it much more difficult to manipulate the data.
The only exception to this is if you are storing/receiving data from a system where date/time values are stored in a non-standard text format like Wed 06-Jul-16 10:31 AM but even in that case it would be better to try to convert it to a compatible format before storing it in the database as a date/time field.
Postcard
This table contains mostly IDs from what looks to be other tables, however I don't see any foreign key references to the other tables, which defeats the primary purpose of have keys for rows in the first place. Here is some useful information on MSDN.
Also make sure to set a PRIMARY KEY constraint on the main ID field of each table. The syntax for keys is like this:
CREATE TABLE [dbo].[Postcard](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK_Postcard] PRIMARY KEY NONCLUSTERED ([Id]),
    [CountryFromId] [int] NOT NULL,
    CONSTRAINT [FK_Postcard_CountryFromId] FOREIGN KEY ([[CountryFromId])
        REFERENCES [dbo].[Country]([Id]),
    [CountryToId] [int] NOT NULL,
    CONSTRAINT [FK_Postcard_CountryToId] FOREIGN KEY ([[CountryToId])
        REFERENCES [dbo].[Country]([Id]),
    -- etc.

Using an 8-byte [bigint] type for your Postcard.Id seems like an overly large type. According to MSDN the range for [bigint] is "-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)". If you really plan on having that many postcard records then fine, but otherwise just an [int] type would be OK.
For consistency your [Status] [int] should probably be instead named [StatusId].


what you have posted is orthogonal to MVC. MVC deals with user interfaces. It has later been reshaped many times to fit various platforms such as the web but the original ideas came out of Xerox some forty years ago and tryed to bridge the gap between the user and the model in the computer (the M) though it's known as MVC it actually MVC-U where the U is for user and the U is there to stress the relationship between the system (MVC) and the User (U).

There's no interface in the code you've posted and hence at best it can be viewed as a mechnism to start some (sub)system that's build on MVC.
The Model is suppossed to represent piece of the users mental model. How they see the world and it has been shown that if there's a 1:1 relation ship between the real life model and the one in the system Users are better at using the system. The view is what the user sees. You can say it's a visual representation of the model and the controller is coordinating user inputs and model updates (which in turn are reflected by an update of the view)

So the short answer would be "no" but the longer is more down the line of "MVC is something unrelated to the problem you are solving with the above code"


Jquery improvement of this script - Adding and removing items from list

What's good here:

It's fairly simple
Using prop over attr

What I did not like

Using HTML strings in code makes code very hard to modify later on. It's hard to debug and might cause potential issues (like making XSS easy for example).
No separation of concerns. You're treating your HTML like your source of knowledge instead of backing up your data with a model in the background. This is very harmful and I personally consider it a big design flaw. Your business logic (in this case the list items) and your presentational layer (the DOM nodes) is the same here. Every time you want to operate on the list you have to query the DOM. This is not only slow, but it becomes very nasty very fast as your code logic begins to expand.

There are frameworks like KnockoutJS that do data binding making this trivial to accomplish in just a few lines of code. However since you wanted a solution that has no 'magic' (Which I totally appreciate by the way) let's see what would be a simple JavaScript solution would look like.

Short note, I'm doing JavaScript with function constructors here since a lot of people find it easier, personally I'd use object initializers.

Here is a working fiddle

First, we'll have a data model for a responsibility.

//This is our element in the view model.
function Responsibility(text){
    this.text=text;
}

Next, we'll need to store all our responsibilities. We'll use an array:

// a list of our responsibilities, an actual view model to back our data
var responsibilities = [];

Now, we'll want a render function, that'll take our elements, and turn them into actual DOM objects. We'll spit it into two. First, we'll render the list item:

function renderResponsibility(rep,deleteClick){
    var el = document.createElement("li");
    var rem = document.createElement("a");
    rem.textContent = " Remove";
    rem.onclick = deleteClick;
    var cont = document.createElement("span");
    cont.textContent = rep.text;
    el.appendChild(cont);
    el.appendChild(rem);
    return el;
}

On renderResponsibility another alternative would be to use a templating engine, but you said no extra libraries so I'm keeping my word :)

Now, our general render:

//render our actual elements
function render(){
    respList.innerHTML = "";
    // note, foreach needs a modern browser but can easily be shimmed
    responsibilities.forEach(function(responsibility,i){
        var el = renderResponsibility(responsibility,function(){
            responsibilities.splice(i,1);//remove the element
            render();//re-render
        });
        respList.appendChild(el);
    });
    //update the text area;
    respTextArea.textContent = responsibilities.map(function(elem){
       return elem.text;//get the text.
    }).join("\n");
}

Finally, let's add the functionality to the Add button:

//events
addButton.onclick = function(e){
    var text = newResp.value;
    var resp = new Responsibility(text);
    responsibilities.push(resp);
    render();
    newResp.value = "";
}

And we're done :)

Just to tease:

Here is a solution in KnockoutJS
Here is a shorter solution in KnockoutJS without using an object for responsibility
Here is a solution in AngularJS

Also here is a more 'jQuery' version of the vanilla solution. As you can see a DOM manipulation library isn't very useful when building an application.


Partitions of an integer and filtering by number of elements

First a technical note.  In mathematics, 2+3 is the same partition as 3+2.  The right name for what you are looking for are combinations.

That said, you are spending most of your time coming up with answers that you will throw away.  Don't.  Spend it coming up with answers that you won't throw away.  Like this:

def compositions(n, size):
    if n == 0 and size == 0:
        yield []
    elif 0 < size:
        for i in range(1, n-size+2):
            for c in compositions(n-i, size-1):
                yield c + [i]

for c in compositions(25, 2):
    print(c)

Update

Since you actually do want partitions, here is an equivalent approach for partitions.

def partitions(n, size, limit=None):
    if limit is None:
        limit = n
    if n == 0 and size == 0:
        yield []
    elif size * limit < n:
        # No solutions possible.
        pass
    elif 0 < size:
        for i in range(1, min(limit, n-size+1)+1):
            for c in partitions(n-i, size-1, i):
                yield [i] + [c]


The FizzBuzz challenge in Java 8 written in a short, readable and interesting way

A guideline that I use for deciding on a StringBuilder or not is that it depends on whether I know beforehand how many times it will be used or not. I believe I've come across this recommendation on some MSDN page once but I'm not entirely sure.

In your case, you know that there are only two possible uses of your StringBuilder, and that there are no values added inside a loop, so I would use normal string concatenation:

Now you can also change your code a little to what I consider more easily interpretable:

private static String fizzBuzzify(final int value) {
   String result = "";

   if (value % 3 == 0) {
       result += "Fizz";
   }
   if (value % 5 == 0) {
       result += "Buzz";
   }
   return result.length() > 0 ? result : Integer.toString(value);
}


Extract routine logic into methods.

Your evaluation process should be its own method. This is something you'd want to repeat and it would make it easy to test multiple cases.

Your main method could just be:

public static void main(String[] args) {
    System.out.println(isPalindromic("racecar"));
}

Use JUnit tests

On the topic of tests, get into the habit of writing them, a good framework for testing is JUnit. You generally want to test something for edge cases and ensure that it works before sharing.

Example test case:

@Test
public void validPalindromes() {
    assertTrue(isPalindromic("racecar"));
    assertTrue(isPalindromic("mom"));
    assertTrue(isPalindromic("avid diva"));
}

Semantic considerations of palindrome

One decision you should make is how you want to account for letter case, and punctuation. The sentence, "A car, a man, a maraca." is a palindrome by English standards, but whether it is or not will be up to your implementation.

A better way to check for palindrome.

What you want to do is just reverse a string and test it against the string, fortunately StringBuilder has a reverse method.

public static String reverse(String str) {
    return new StringBuilder(str).reverse().toString();
}

So to check if a word is a valid string, you can simply have:

public static boolean isPalindromic(String str) {
    return str.equals(reverse(str));
}

If you want to account for letter case you can use equalsIgnoreCase and for punctuation you should use a Regex.

Adding these factors in would give us:

public static boolean isPalindromic(String str) {
  String potentialPalindrome = str.replaceAll("[^a-zA-Z]", "");
  return potentialPalindrome.equalsIgnoreCase(reverse(potentialPalindrome));
}

Simplest implementation

If you don't want the overhead of using StringBuilder, you can always use a loop:

public static boolean isPalindromic(String s) {
    for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
        if (s.charAt(i) != s.charAt(j)) {
            return false;
        }
    }
    return true;
}


Your third approach is the most pythonic, in the sense that you create a function for each specific purpose, avoiding repetition and giving the user more options (process the users, only the days, etc...) and the option to save or not to save the processed data to the database.

It is also the fastest. If you benchmark it, that kind of approach (separating things into functions) will almost always be the faster one with Python.

Using your first approach it took roughly 0.00027 seconds to process a list of 100 events for each day, having two days for each user and two users.

Using the second approach it takes roughly 0.00018 seconds.

Using the third approach it takes roughly 0.00012 seconds.

Here are all the approaches and their output:
http://pastebin.com/vU12HaQW

Notice your third approach yields a list of list of lists, whereas the first and the second return a list.


The grammar itself is pretty unreadable "as is". A rule like:

statement : stopUsingNamespaceStm|usingNamespaceStm|namespaceDefineStm|functionStm|defineStm|assignStm|funcDefineStm|ifStm|whileStm|returnStm|breakStm|eventDefStm|eventCallStm|linkStm|classDefStm|exitStm|importStm|importOnceStm|directive;

would be far more readable when declared like this:

statement
  :  stopUsingNamespaceStm
  |  usingNamespaceStm
  |  namespaceDefineStm
  |  functionStm
  |  defineStm
  |  assignStm
  |  funcDefineStm
  |  ifStm
  |  whileStm
  |  returnStm
  |  breakStm
  |  eventDefStm
  |  eventCallStm
  |  linkStm
  |  classDefStm
  |  exitStm
  |  importStm
  |  importOnceStm
  |  directive
  ;

You'll want to explicitly end the entry point of your parser, the rule program, with the end-of-file token, otherwise your parser might stop parsing prematurely. With EOF, you force the parser to read the entire tokens stream.

program
  :  statement* EOF
  ;

Make explicit tokens for keywords, don't mix them inside your parser rules.

Instead of:

importStm
  :  'import' expression ';'
  ;

it's better to do:

importStm
  :   Import expression ';'
  ;

Import
  :  'import'
  ;

This will make your life easier at a later (tree walking) stage. Without explicit lexer tokens, it is unclear for you when debugging what tokens there actually are in your tree.
Your lexer rules:

STRING_DOUBLE : '"' .* '"';
STRING_SINGLE : '\'' .* '\'';

can never contain either double- or single quotes. So, it's impossible to have a string literal with a double- and single quote in it.

Better to do something like this:

STRING_DOUBLE
  :  '"' ('\\' ('\\' | '"') | ~('\\' | '"'))* '"'
  ;

which will allow a double quoted string to contain double quotes as well.

That's all I saw at a first glance. I didn't look real close, so there might be more that can be improved.


Although the approach is 'peculiar in choice of tools', doing what you do should work just fine. The only part that I would definitely want to change is the loading of the results. Currently you are BULK INSERTing a file into a temp-table, then copy all that data into a table-variable, followed by deleting everything from the freshly (and the old!) copied data where it does not match a given criteria.

I would propose the following changes:

do not use Table-variables for this. They're fine for (very) small data-sets that don't require a lot of manipulation but will confuse the Query Optimizer when you do lots of inserts and deletes on them
do not use the TEXT datatype, rather use varchar(max)
use IDENITITY instead of RowNumber(). RownNumber works great, but it requires sorting the data. Also be very careful with this: doing RowNumber() ordered over a 'constant' might return different results than you originally anticipated and most certainly does not guarantee that you'll get things in the order they were originally in the file !!!!!
variable naming: @filename is much more readable than @ID

Doing some cleaning I ended up with below which in my tests on a couple of 100 small files ran slightly faster than the original. There might be a nicer way than the tempdb..stagingTable approach which will cause issues when the script is run in parallel, but I didn't see an easier way out to be able to use LineNum as an identity which in my opinion is must for what you're trying to achieve!

--Drop temp table if it already exists
IF OBJECT_ID('tempdb..tempdb..stagingTable') IS NOT NULL
    DROP TABLE tempdb..stagingTable

IF OBJECT_ID('tempdb..#files') IS NOT NULL
    DROP TABLE #files

IF OBJECT_ID('tempdb..#foundText') IS NOT NULL
    DROP TABLE #foundText

----------------------
----------------------
GO
--Crete temp table to store output lines from text file
CREATE TABLE tempdb..stagingTable
(
    LineNum int IDENTITY(1, 1) PRIMARY KEY,
    LineText varchar(max),
)

GO
-- since we can't tell BULK-insert to skip the LineNum column, we create a view without it
CREATE VIEW vtempFileContents AS SELECT LineText FROM tempdb..stagingTable
GO

--Create declared table to store found file names in the directory
CREATE TABLE #files
(
    filename VARCHAR(255)
    ,depth INTEGER
    ,files BIT
)

--Create declared table to store the text the string ws found in along with the filpath of the file.
CREATE TABLE #foundText
(
    LineNum int
    ,foundText TEXT
    ,filename VARCHAR(255),
    PRIMARY KEY (filename, LineNum)
)

GO

DECLARE @FindText AS VARCHAR(255)
DECLARE @FileDir AS VARCHAR(255)

--Directory to search
SET @FileDir = 'C:\temp\test\'
--Text to search
SET @FindText = 'common'

--Create table of files in the directory
INSERT INTO #files
EXEC xp_dirtree @FileDir, 10, 1

--Varchar used to store the derived SQL string
DECLARE @sql NVARCHAR(1000);

--Create cursor for file searching
DECLARE @text VARCHAR(255)
DECLARE @filename VARCHAR(255)

DECLARE files_loop CURSOR LOCAL FAST_FORWARD FOR SELECT @FileDir + filename FROM #files

--Open cursor
OPEN files_loop
FETCH NEXT FROM files_loop into @filename
WHILE @@FETCH_STATUS = 0
BEGIN
    --Truncate temp table prior to searching a file
    TRUNCATE TABLE tempdb..stagingTable
    SET @sql = 'BULK INSERT vtempFileContents FROM "' + @filename + '"'
    EXEC(@sql);

    --Insert matching records in results table
    INSERT INTO #foundText (LineNum, foundText, filename)
    SELECT LineNum, LineText, @filename
      FROM tempdb..stagingTable
     WHERE LineText IS NOT NULL
       AND LineText LIKE '%' + @FindText + '%'

    FETCH NEXT FROM files_loop into @filename
END

--Close off and dispose of unneeded resources
CLOSE files_loop
DEALLOCATE files_loop

--Display results
SELECT * FROM #foundText

GO
-- cleanup
DROP VIEW vtempFileContents
DROP TABLE tempdb..stagingTable
DROP TABLE #foundText
DROP TABLE #files


First let's mention a bug / issue:

Your passwords variable is accessed (read and modified) from multiple goroutines without any syncronization: this is a race condition!

Primary problem

Your memory problem arises from launching a tremendous amount of goroutines. For example when you call compute() with n = 6 (to try passwords with a length of 6), it will create:

36^5 = pow(36, 5) = 60466176

(36 is the length of your alphabet; 5 is the prefix value for the condition prefix == n-1 when compute() stops spawning new goroutines)

60 million goroutines!

Goroutines are lightweight, but not that lightweight! Even if managing 1 goroutine would cost only 1 KB memory (it has its own stack etc.), this would require 60 GB memory! Understandable you run out of it. Your code spawns goroutines at a much quicker rate than they complete. (It should be noted that nothing in your code prevents spawning these new goroutines before any would be completed, so this is kind of worst case but still...)

An easy fix!

But the good news is that there is a really easy fix to this tremendous number of goroutines: simply do not spawn many goroutines.

A trivial way to limit spawning goroutines is that when you would spawn them, bind it to a condition to keep them at bay. For example launch 36 goroutines to process passwords starting with the different letters, but after that let 1 goroutine try all the combinations with that starting letter.

We can test this "first letter" condition by comparing prefix to 0:

for i := range alfabeto {
    wgFather.Add(1)
    if prefix == 0 {
        go compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
    } else {
        compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
    }
}

By inserting this condition and the else branch just calling compute() on the same goroutine, you keep your goroutine number and memory usage at bay! But still, you utilize multiple goroutines and multiple CPU cores.

There is a minor "downside": you have no control how these 36 goroutines finish compared to each other, there may be a "relaxed" period when only 1 or 2 goroutines are running and others are finished, in this relaxed period CPU utilization will not be 100%. More formally CPU utilization will be < 100% if # of goroutines is less than # of CPU cores.

Optimization tips

Here are some optimization tips:

You do unnecessary round-trips: you build potential passwords as string, then when your searchPassword() function computes its MD5, it has to convert it to []byte. Best would be to build password in a []byte. Go stores strings as UTF-8 encoded sequences (see blog post Strings, bytes, runes and characters in Go for details), and all your alphabet letters map to bytes one-to-one in UTF-8 encoding, so you could just use their byte value for faster building.
In your searchPassword() when you have the MD5 of the potential password, you always iterate over all crackable MD5 strings and you compare to all. This is a waste, you could sort the crackable MD5 values and use binary search to find if the potential is in it (sorting and binary search is implemented in the sort package). Or even better: you could build a map from the crackable MD5 strings, and just check if the candidate is in the map (now this check would be O(1) complexity instead of O(log n) of the binary search).
It is also an unnecessary round-trip to convert a calculated MD5 to string in order to check if it is a crackable one. Best would be to convert the crackable MD5 values to a byte array (note: array and not slice), and when you have the MD5 of a potential password as an array, you can check if it is a crackable one without converting it to string. Arrays are comparable in Go (unlike slices!), so you could also build a map from the MD5 arrays to check if a potential MD5 is in the map.
Also note that your algorithm generates passwords multiple times. For example if you want to check passwords with a length of 3, these 3-letter passwords are essentially all the 2-letter passwords +1. But you don't make use of this, you always generate all passwords with a given length from "scratch".

Utilizing these tips would speed up your algorithm big time; not just because we got rid of lots of needless computation / conversion, but also because much less "garbage" will be generated for the GC.

Alternative

An alternative way of implementing this brute-force cracker would be to use the producer-consumer pattern. You could have a designated producer goroutine that would generate the possible passwords, and send them on a channel. You could have a fixed pool of consumer goroutines (e.g. 5 of them) which would loop over the channel on which generated passwords are delivered, and each would do the same: receive passwords, hash them (MD5) and check if it matches a crackable one.

The producer goroutine could simply close the channel when all combinations were generated, properly signalling producers that no more passwords will be coming. The for ... range construct on a channel handles the "close" event and terminates properly.

This would result in a clean design, would result in fixed number of goroutines, and it would always utilize 100% CPU. It also has the advantage that it can be "throttled" with the proper selection of the channel capacity (buffered channel) and the number of consumer goroutines.

Here is how this producer-consumer could look like in Go if someone wants to play with it (also note that I elaborated this with full examples and much deeper explanation in StackOverflow question Is this an idiomatic worker thread pool in Go?):

var wg sync.WaitGroup

func produce(ch chan<- []byte) {
    // Now generate all passwords:
    for {
        if noMore { // If no more passwords
            close(ch)
            break
        }
        pass := ...   // Here generate next password
        ch <- pass    // send it for processing
    }
}

func consume(ch <-chan []byte) {
    defer wg.Done()
    for pass := range ch {
        // Hash, check
    }
}

func main() {
    ch := make(chan []byte, 100) // Buffered channel

    // Start consumers:
    for i := 0; i < 5; i++ { // 5 consumers
        wg.Add(1)
        go consume(ch)
    }

    // Start producing: we can run this in the main goroutine
    produce(ch)

    wg.Wait() // Wait all consumers to finish processing passwords
}

This blog post is an excellent introduction to parallel computation in Go using goroutines and channels:

Go Concurrency Patterns: Pipelines and cancellation

Further optimization tip

Now if you go with this producer-consumer goroutine model, another optimization becomes available.

The md5.Sum() function (which takes a []byte and returns the MD5 checksum of its content) always creates a new, internal md5.digest value which is used to do the MD5 hashing. Then it is discarded.

Now if we have a small, fixed pool of consumer goroutines, we can now create and it is profitable to create a designated MD5 hasher for each with the md5.New() function. To what end? We can use the returned hasher (which is of type hash.Hash) to compute MD5 hashes, but what's cool is that we can reuse it to compute hashes of multiple byte slices.

hash.Hash implements io.Writer so we can write any []byte into it of which we want to compute the MD5 hash, and it also has a Hash.Sum() method which returns the MD5 hash, giving the option to not create a new array return value which will hold the calculated MD5, but we can pass our slice to it in which we want the result. We can also create prepared arrays ([16]byte) and slice them to obtain a slice []byte, and do this for all of the consumer goroutines. As a result, we can further suppress "memory-garbage" generation and reduce GC work. Once we queried the MD5 sum of a password, we can simply call Hash.Reset() to re-initiaze the hasher for the next password.


You're spending a lot of time in item_value converting numbers to a binary string back to an int to get the sum. It would be a lot more expedient to just use str.count to get the number of 1s in the string. That saves you a lot of type conversions as well as a call to sum with a generator.

def item_value(e1, e2):
    c = bin(int(e1, 2) | int(e2, 2))
    return c[2:].count('1')

My results from this caused a reduction from 58.9s to 0.91s.


K&R 2-7 - Invert a bitfield from a number

Just a few notes, since the code is so short:

Put your main after all of your other function declarations so you don't have to declare the function prototypes at the top.
You don't have to return 0 at the end of main(). The C standard  knows how frequently this is used, and lets us omit it.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Move your comment to the top of the function and explicitly say what the parameters are and what the output will be.
Your function parameter names could be better:

unsigned invert(unsigned num, int position, int num_bits)

Those parameters to your function could be declared const
Does your function perform as is supposed to with negative numbers?  Zeros?  Other edge cases?  You should have more tests in your code to make sure you get the expected behavior, and if not handle those edge cases more appropriately.  Use assert from the standard library header <assert.h> to help with this.


Modeling a Triangle, with a utility method to classify it

You need to pick a model, and stick with it. You have duplicated much of your logic at the static level and the instance level. Specific cases are the classify() instance method, and the classify(int,int,int) static method. There is no need for both.

Additionally, the logic split between the two validation methods isSaneArguments and isTriangle should all be in one method (I recommend isTriangle). There is no place you call them separately, so there is no reason to split them. isSaneArguments is a poor name anyway.... Finally, it's not exactly 'yoda conditions', but I prefer to do calculations on the left-side of a comparison operator like < or >. Bracing them makes it more readable in a chain of arguments...:

isTriangle(final int a, final int b, final int c) {
    // positive lengths, and sides that can meet
    return a > 0 && b > 0 && c > 0  && (a + b) > c && (a + c) > b && (b + c) > a;
}

The way your class is laid out lends itself to having static calls to get the properties of the triangles. It appears that the class is designed to regularly encounter invalid triangles, (hence Type.INVALID), so having a constructor throw an exception is unpleasant. I would make the constructor private, and do the validation outside the constructor, and would keep the methods static...

Note, classifyValidTriangle is public, but does no validation, (like the name says), this is odd.... to trust the caller that much. I would still expect validation of arguments, and an IllegalArgumentException if they are not met.

The classify method would also be better if written as an early-return mechanism, instead of holding the type variable....

Note that the actual Triangle instance does not do much, and there is no apparent purpose for it.

Neither your class, nor the embedded enum are public, this seems odd.

Finally, I rearranged the code to put the enum at the top, the static methods next, then the fields, and constructor:

public class Triangle {

    public enum Type {
        EQUILATERAL, INVALID, ISOSCELES, SCALENE
    }

    public static Triangle buildTriangle(int a, int b, int c) {
        if (isTriangle(a, b, c)) {
            return new Triangle(a, b, c);
        }
        throw new IllegalArgumentException("input values are not able to make a triangle");
    }

    public static Type classify(int a, int b, int c) {
        if (!isTriangle(a, b, c)) {
            return Type.INVALID;
        }
        if (a == b && b == c) {
            return Type.EQUILATERAL;
        }
        if (b == c || a == b || c == a) {
            return Type.ISOSCELES;
        }
        return Type.SCALENE;
    }

    private static boolean isTriangle(int a, int b, int c) {
        // positive lengths, and sides that can meet
        return a > 0 && b > 0 && c > 0  && (a + b) > c && (a + c) > b && (b + c) > a;
    }

    private final int a;
    private final int b;
    private final int c;

    private Triangle(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

}


uplifitng return value error reporting to Exception based error reporting

Yes, the refactoring "Replace error codes with exceptions" work perfectly here.
As a first step you need to create an exception type that suits your need, something like

public class UpdateException : Exception
{
    //your custom properties, fields etc.
}

and then use it in your method (an example below)

public void Update(CaseStep oCaseStepIn)
{
    //Update the master object with the passed in object

    if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED)
        throw new UpdateException(); //pass in constructor useful messages

    CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey);
    if (oCaseStep == null)
        throw new UpdateException(); //pass in constructor useful messages

    if (oCaseStep.Update(oCaseStepIn) != UCommonIndep.gnUPDATE_SUCCESSFUL)
        throw new UpdateException(); //pass in constructor useful messages

    //*******************************
    //FYI - Insert code here to update any Key values that might have changed.
}

You can create different Exception subclasses for each type of error. It's even better.


Finding all simple (without internal cycles) paths in a directed graph with total >1.0 weight

An empty container like a list or deque is False, so it isn't necessary to use len() on them.  This is more "pythonic"

while queue:
    ...

    if not adjacency_nodes:
        ...

It seems wasteful to add a path to the queue only to discard it because it is too long.  It would be better to check the length before making a copy of the path and adding it to the queue.  Moreover, if len(path) == is cutoff - 1 the only possible solution is if target_node is in adjacency_nodes.  So, something like this might be faster:

from collections import deque

def algorithm(G, source_node, target_node, pusher, cutoff=5):

    if source_node not in G:
        return

    queue = deque([[source_node]])

    while queue:
        path = queue.popleft()

        adjacency_nodes = G[path[-1]]

        if not adjacency_nodes:
            continue

        if len(path) == cutoff - 1:
            if target_node in adjacency_nodes:
                pusher(path[:] + [target_node])

        elif len(path) < cutoff - 1:
            queue.extend(path[:] + [node] for node in adjacency_nodes)

If you are trying to optimize for speed, use the profiler in the standard library to see where the algorithm is spending time.

The algorithm is basically a breadth first search of the graph.  Because there is a depth cutoff, a depth first search might be faster because there isn't the overhead of copying the path and keeping the queue of paths to search.  But the only way to know is to implement it and see.

Lastly, the networkx library provides all_simple_paths(G, source, target, cutoff=None) which is a generator of all simple paths from source to target with a maximum length cuttoff. FYI, networkx uses a DFS search (source code).


Verifying that all form fields are filled in

Couple of suggestions from my end.

1 > There is a better way to check null or empty in javascript,this can be done more efficiently with this

 if (document.getElementById('fname').value)
 {
   //value exists.
 }

Above condition evaluates to true if value is not equal to any of the following:

null
undefined
NaN
empty string ("")
0
false

2 > Try to use switch case instead of so many if else.It will make your code more elegant and readable.

3 > Take care of indentation currently it's not very good.

4 > Instead of writing ewForm.checkbox[0].checked == false you can use

if(!ewForm.checkbox[0].checked)
{
//not checked
}


Represent number N (N>1) as N = x + y, where x * y is the maximum possible value

$$\frac{\text{d}}{\text{d}x} x(N-x) = N - 2x$$
At a maximum, \$\frac{\text{d}f}{\text{d}x} = 0\$, so the maximum occurs when \$x = \frac{N}{2}\$. (Left as an exercise: show that it's a maximum and not a minimum).

Therefore you can skip the loop: desiredNumber = N / 2; is all you need. Note that if N is odd this gives the pair \$\left\lfloor \frac{N}{2} \right\rfloor, \left\lceil \frac{N}{2} \right\rceil\$, which is the correct solution in integers.


You can get the value for ASCII_POS_OF_0 easily by using '0'.

Your code doesn't deal with malformed strings well.

If the string is only "123" it will attempt to read beyond the contents of the string. You can fix this by checking for '\0' at the correct places.

It also doesn't handle any type of whitespace in the string at all.


You don't need the ||= you can use ||:

def connect_to_oracle( opts = {} )
  host_name = opts[:host_name] ||'a_default_host_name'
  db_name = opts[:db_name] || 'a_default_db_name'
  userid = opts[:userid] || 'a_default_userid'
  password = opts[:password] ||'a_default_password'

  url = "jdbc:oracle:thin:#{userid}/#{password}@#{host_name}:1521:#{db_name}"
  $db = Sequel.connect(url)
end

Another approach is Hash.merge:

DEFAULT = {
  host_name: 'a_default_host_name',
  db_name:  'a_default_db_name',
  userid: 'a_default_userid',
  password: 'a_default_password',
}

def connect_to_oracle( opts = {} )
  opts = DEFAULT.merge(opts)

  host_name = opts[:host_name]
  db_name = opts[:db_name]
  userid = opts[:userid]
  password = opts[:password]

  url = "jdbc:oracle:thin:#{userid}/#{password}@#{host_name}:1521:#{db_name}"
  $db = Sequel.connect(url)
end

or:

DEFAULT = {
  host_name: 'a_default_host_name',
  db_name:  'a_default_db_name',
  userid: 'a_default_userid',
  password: 'a_default_password',
}

def connect_to_oracle( interface_opts = {} )
  opts = DEFAULT.merge(interface_opts )

  url = "jdbc:oracle:thin:%s/%s@%s:1521:%s" % [
    opts[:userid],
    opts[:password],
    opts[:host_name],
    opts[:db_name],
    ]
  $db = Sequel.connect(url)
end
connect_to_oracle()
connect_to_oracle(:host_name => :xxxxxxxx)

I prefer the version with merge. So I get a constant with all default parameters in my documentation.

Another advantage: I can easily add checks if my interface contains correct keys.

Example:

DEFAULT = {
  host_name: 'a_default_host_name',
  db_name:  'a_default_db_name',
  userid: 'a_default_userid',
  password: 'a_default_password',
}

def connect_to_oracle( myopts = {} )
  (myopts.keys - DEFAULT.keys).each{|key|
    puts "Undefined key #{key.inspect}"
  }
  opts = DEFAULT.merge(myopts)

  url = "jdbc:oracle:thin:%s/%s@%s:1521:%s" % [
    opts[:userid],
    opts[:password],
    opts[:host_name],
    opts[:db_name],
    ]
  #~ $db = Sequel.connect(url)
end
connect_to_oracle(:host_nam => :xxxxxxxx)

My method call contains an error (forgotten 'e'), but when you call it, you get a warning Undefined key host_nam. This often helps to detect errors. (in a real scenario I replace the puts with a logger-warning/error).


Could this also cause problems for me?

As with most CSS questions, the answer is maybe. It really depends on the rest of your CSS. Personally, I try to stay away from !important but I can certainly understand your usage. As long as it isn't causing additional issues, I don't see a problem with it.

  Is this correct and efficient or is there a better way of writing this?

I would recommend wrapping your code in an IIFE so as not to pollute the global scope and give yourself a "safe" private scope.  This also allows you to use $ for jQuery with no conflicts:

(function( $ ) {
  //code here
})( jQuery );

Next, if you see where you use the same jQuery selection more than once, you should just go ahead and cache it:

var logModal = $('#loginmodal');

I would also recommend that you use K&R style braces instead of Allman style.  This can help prevent issues you might encounter with JS.

$(".hidelogopenreg").click( function() {  // opening on same line K&R style
  $('#loginmodal').modal('hide')
  $('#registermodal').modal('show')
}

Lastly, you need to end your lines of code with a semicolon. You can get away with this in some situations but can cause issues later on. More information here and here.

  $('#loginmodal').modal('hide');  //end of line
  $('#registermodal').modal('show');  //end of line

Here is the code with these changes:

(function( $ ) {

  var $logModal = $('#loginmodal');
  var $regModal = $('#registermodal');
  var $hideLogin = $(".hidelogopenreg");

  function swapModals() {
    $logModal.modal('hide');
    $regModal.modal('show');
  }

  $(document).ready( function() {
    $logModal.modal( 'show');
    $hideLogin.on( 'click', swapModals );
  });

})( jQuery );

Hope that helps.  Let me know if you have questions, comments or need clarification.


I'm still trying to wrap my head around what exactly is happening in that apply/call mass :-)

But that may be a hint, that those three lines aren't really well readable. I'm aware you want to keep it small, but unless the code needs to be really, really fast (which I doubt it does) I would prefer readability over shortness.

In that line, I would prefer to have long, more expressive variable names. It be better to use complete words instead of Q, t, n, a etc.

If in the end, shortness is still important, then use a JavaScript compressor.

BTW, you should keep JavaScript naming conventions in mind, too. Constructor functions ("classes") should be named with capital letters (Q instead of q) and fields should use small letters (q instead of Q).

Just out of interest: Can you give a concrete use case for this kind of queue?


Here is my proposal. It is shorter than OP's solution, specially to compute the length of each word to be used in the format procedure while printing.

In a single line, we obtain a 1D array with maximal lengths.

import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
    for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""

Output

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose


Unique everlasting session with low collision rate and is set across sub-domains

Since nobody else has chimed in here, I figured I would elaborate on my comments above.  If your stated goal is to:

have sessions that last indefinitely
have sessions that are more secure than default settings
have sessions that have have less chance of collision than default settings

Then this is the wrong approach.  You are actually not meeting any of these goals, and in fact are making security and chance of collision worse.

First,  these sessions will not be indefinite.  You are setting session cookie lifetime with value of 0 which means that, if the browser is compliant with this setting, the cookie will only last as long as the browser is open.  If that user closes their browser and then opens it back up 10 minutes later, they will get a new session.  There is no setting that will make a session last forever, as sessions are not really designed to last forever.  If you need data to persist between what truly are "sessions" then you need to look for another solution.  I am not suggesting you change this setting at all, as for most use cases when using sessions as intended, a value of 0 for cookie lifetime is a reasonable setting.

So, now that we have established that you are not truly getting "everlasting" sessions, let's get into the security aspects.

Here are a few PHP documentation links I will refer to:

Securing session INI
PHP Session Management Basics

We will start with garbage collection. Since you are not getting long-lasting sessions, that fact that you want to collect session data files (or database records if one were to use a database to store the data) indefinitely, means that you are, in essence, accumulating attack vectors against your application.  Ideally you should use an appropriate session lifetime and an aggressive approach to invalidating and pruning old records to minimize security risk.  One comment from the session.gc_maxlifetime section of the securing INI link above seems very pertinent here:

  If auto login feature is required, implement your own secure auto
  login feature. Never use long life session ID for it.

Long sessions should not be purposed for long-term data persistence or used for  authentication/authorization as it seems you are trying to do.

As I mentioned earlier accumulating these session files is like accumulating attack vectors, as you increase the opportunity for someone to execute a session hijacking or session fixation attack against your application.  This coupled with the fact that you open the application to using session cookies over non-secure (HTTP) connection, means it would be trivial for a packet sniffer or man in the middle to grab a session ID from a legitimate user's request and use it FOREVER.

And while destroying/regenerating session id's across IP change boundaries is a reasonable security measure, it is by no means enough.  That attacker could be sitting in a Starbucks along with the legitimate user using a wifi network which has the same exact IP address.  A sophisticated attacker can also easily spoof their IP address.

Also, keep in mind that there are some legitimate use cases where a user might change IP address during a session (a user on a mobile device for example), so while, IP address can be used as one of the triggers for session invalidation, if you use some of the other takeaways about handling session securely, you might decide that it's importance as a criteria for session invalidation might not be worth a potentially bad user experiences if you had a high number of mobile users.

Accumulating these session files also does increase your risk of a session collision.  Now that may be a pretty minute risk on a website with low traffic level anyway, but you are certainly making the probability of it happening worse, not better, with your approach.  And the IP check has nothing to do with mitigating against session id collision as mentioned in your comments.  That IP value is stored inside the session data and in no way helps mitigate a collision on the session id itself.

Let's talk about the session file save path.  I know there was some back and forth on this in the comments, with me suggesting that putting these files in a web directory is a bad security practice.  You are right that one could limit access to this directory in other ways, but why would you want to introduce a security vulnerability that you need an additional security measure to mitigate?  You are making your application security more complex and more fragile to someone not setting things up properly than it has to be.

Additionally, it just makes no practical sense to be putting this data into your application web directory anyway, just from a straight separation of concerns/access standpoint.  One doesn't typically configure database files, application logging, or other similar functionality that might read-write system files to do so into the application space, so why would you do this with session data?

Ideally, you write session data into a directory only available to the root user or user under which your application is running under to access and you don't let administrators working with the production system have root/sudo access in production unless absolutely necessary.

You should be using session.use_strict_mode if not specified as such in your ini file (this is not shown here obviously,so I am not sure what your current approach is).  This will help mitigate against session fixation, but will not help if an attacker uses one of the sessions id's you are collecting as cruft.

If you are using PHP 7.1, consider using session_create_id() to establish better connection between indvidual user and their session id.  This allows allows better usage of prefix index for database lookups if ever using a relational database as session storage medium.

Even for a case of using long sessions (or true browser-controlled session lengths as you are doing), you should regenerate session id at regular intervals to mitigate against session fixation/hijacking.  This means you have to start managing a timestamp in the session data.  There really is no way around this in PHP sessions.  I know one of your stated goals was to not have to get into this, but there really is no alternative if you want your sessions to be secure.  Please read the "Session ID Regeneration" section of the second link given above.

There is a pertinent quote there:

  Developer must NOT rely on session ID expiration by
  session.gc_maxlifetime. Attackers may access victim's session ID
  periodically to prevent expiration and keep exploiting victim's
  session ID including authenticated sessions.

  Instead, you must implement time-stamp based session data management by yourself.

So a bad system would rely on garbage collection alone to provide mitigation against session fixation.  A really bad system would not use garbage collection at all.

Again... you have to use timestamps if you want secure sessions.

Additionally, session_regenerate_id() combined with session_destroy() in PHP doesn't magically work by itself.  See the warning note in the session_regenerate_id() documentation:

  You should not destroy old session data immediately, but should use
  destroy time-stamp and control access to old session ID. Otherwise,
  concurrent access to page may result in inconsistent state, or you may
  have lost session, or it may cause client(browser) side race condition
  and may create many session ID needlessly. Immediate session data
  deletion disables session hijack attack detection and prevention also.

Again... you have to use timestamps if you want secure sessions.

Continuing in the area of session data management. Let's talk data deletion.  Please heed this text from the "Session Data Deletion" section of the second link above:

  Obsolete session data is better to be removed as soon as possible.
  However, active sessions MUST NOT be removed immediately. To satisfy
  these requirements, you MUST implement time-stamp based session data
  management by yourself.

  Set and manage expiration time-stamp in $_SESSION. Prohibit access to
  obsolete session data. When obsolete session data access is detected,
  it is advised to remove all authenticated status from the user's
  sessions and force them to re-authenticated. Obsolete session data
  access could be an attack. To do this, you must keep track active
  sessions per user.

  In short, do not destroy session data by session_regenerate_id() nor
  session_destroy(), but use time-stamp to control access to session
  data. Let session_gc() to remove obsolete data from session data
  storage.

Again... you have to use timestamps if you want secure sessions.

session_name('session');// now make sure that the same session will not be regenerated across sub-domains and stay the same!

This doesn't really do what the comment says it does.  This function simply determines that name of the session cookie to be used.  This doesn't guarantee any cross-domain interactivity of the cookie unless this same name is used for the cookie in all those sub-domains.  I think naming your sessions is totally fine, but this is really not necessary to achieve this effect. For example, if every subdomain was a PHP app with the same INI setting for this, this line would be unneccessary.  Similarly, if you had other subdomains that were not PHP apps, this code here does nothing to help you, as you would need to use whatever means the language in use on that subdomain uses to set this cookie name.

If all of this seems overly complex to manage in a secure manner, that is understandable.  As I said in my comments to the post above, PHP does not make secure session management easy in an out of the box manner. It requires work on the part of the developer.

You might consider using a good session management library if you want to simply drop some functionality into your application and not worry so more about the minutiae of managing the sessions.


Decision tree node split by Gini coefficient (used in RandomFerns/RandomForest algorithm)

Assuming that the groupby function comes from the itertools library, the list should be sorted before this function is called. For instance,
[len(list(group)) for key, group in groupby(right)] should be
[len(list(group)) for key, group in groupby(sorted(right))]. It doesn't work properly if the input is not sorted according to the documentation.
After you make the split, you compute exactly the same function for the left and the right part. It might be a good idea to create a separate function for it (something like get_gini_index(values), that takes a list of labels and return the gini index).
# to do here: what happens if len(right) or len(left) is zero. This one looks sort of weird to me. I'd recommend to figure out whether it's actually a special case. If it is, it should be handled properly (namely, this split should be ignored). If it's possible to prove that it's not a special case, this comment needs to be removed to prevent confusion. I would agree that sometimes todo's can be left in the code, but in this case it looks important and easy to fix.


My own getline function for reading strings from files

Free the Functions!

First, as others have pointed out, this gains nothing from being a class--it probably makes more sense as a free function.

Good Inheritors Would Rather Switch than Fight!

Second, this specifies that its argument must be an fstream. This seems rather pointless. One of the major points of streams is that most functions can (and do) handle various kinds of streams by working with the base classes--usually std::istream and std::ostream. This lets your code work with any stream that provides the interface you need (in this case, just the ability to read, so an istream suffices).

Return Status

With those changed, the big shortcoming I see in this getline compared to std::getline is that it fails to return anything that can be interpreted as the status of the attempt at reading.

For example, in a typical case I might read and process all the lines of text from a file using a loop something like this:

std::ifstream input("input.txt");
std::string line;

while (std::getline(input, line))
    process(line);

If I want to read all the lines from a file with this getline, I guess I can do something like this:

while (getline(input, line), input.good())
    process(line);

That should work, but it's a bit clumsy at best, and sufficiently strange that most people would probably find it more difficult to understand. I think it would be better to do like most I/O routines, and return a reference to the stream you read from:

std::istream &getline(std::istream& in, string& word, char delimeter ='\n'){
    char ch;

    word = "";
    while(in.get(ch)){
        word += ch;
        if(ch==delimeter)
            break;
    }
    return in;
}

Spelling

The word you're spelling as "delimeter" is actually spelled "delimiter".

Delimiter Usage

Your code has behavior that differs from std::getline in a way I think reduces its utility. std::getline normally reads the delimiter from the stream, but does not include that delimiter in the output string (where your code does include the closing delimiter in the output string). At least when I've used it, including that delimiter wouldn't be very useful--I'd usually have to delete it if I read a string with this code. I'd probably omit it, and (if necessary) provide an overload that saved it (but still probably separately from the string it read).

Delimiter Specification

Probably the single biggest problem I have with std::getline is that you can only specify one specific character as the delimiter. If I were going to write one, I think I'd allow the user to pass something like a string, so they could (for example) pass "\t\r\n\v" as the delimiter, to have the function read to the next white-space.

Although it's more advanced, you could go even further, and let the user specify the delimiter as a regular expression, so they could specify arbitrarily complex patterns instead of just a few specific characters.


Python script to extract text from PDF with images

I don't see a good reason why this should be a class. You only have two things in your state, self.text, which you could pass as an argument, and self.path, self.output_path, which I would also pass as arguments, maybe with a default value.

Also, you are probably using classes wrong if your class has a main method that needs to instantiate new instances of the class on the fly.

Your algorithm is not very efficient. You need to run over the whole text twice for each keyword. Once to check if it is in there and then again to count it. The former is obviously redundant, since str.count will just return 0 if the value is not present.

However, what would be a better algorithm is to first extract all the words (for example using a regex filtering only letters) and then count the number of times each word occurs using a collections.Counter, optionally filtering it down to only those words which are keywords. It even has a most_common method, so your file will be ordered by number of occurrences, descending.

Instead of mucking around with os.getcwd() and os.listdir, I would recommend to use the (Python 3) pathlib.Path object. It supports globbing (to get all files matching a pattern), chaining them to get a new path and even replacing the extension with a different one.

When reading the keywords, you can use a simple list comprehension. Or, even better, a set comprehension to get in calls for free.

line.strip() and line.strip("\n") are probably doing the same thing, unless you really want to preserve the spaces at the end of words.

At the same time, doing self.filename.strip('.pdf') is a bit dangerous. It removes all characters given, until none of the characters is found anymore. For example, "some_file_name_fdp.pdf" will be reduced to "some_file_name_".

The csv.writer has a writerows method that takes an iterable of rows. This way you can avoid a for loop.

I would ensure to run only over PDF files, otherwise you will get some errors if a non-PDF file manages to sneak into your folder.

I have done all of this in the following code (not tested, since I don't have textract installed ATM):

from collections import Counter
import csv
from pathlib import Path
import re
import textract

def extract_text(file_name):
    return textract.process(file_name, method='tesseract', language='eng',
                            encoding='utf-8').decode('utf-8')

def extract_words(text):
    return re.findall(r'([a-zA-Z]+)', text)

def count_keywords(words, keywords):
    return Counter(word for word in words if word in keywords)

def read_keywords(file_name):
    with open(file_name) as f:
        return {line.strip() for line in f}

def save_keywords(file_name, keywords):
    with open(file_name, "w", newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        writer.writerow(['keyword', 'keyword_count'])
        writer.writerows(keywords.most_common())

def main():
    output_folder = Path("output_results")
    keywords = read_keywords('keywords.txt')

    for f in Path("folderForPdf").glob("*.pdf"):
        words = extract_words(extract_text(f))
        keyword_counts = count_keywords(words, keywords)
        save_keywords(output_folder / f.with_suffix(".csv"), keyword_counts)

if __name__ == "__main__":
    main()


Cross Thread Access to Object in ViewModel

The TPL is unfortunately verbose at times. The only way I can think of to make it look "nicer" is to point ConsoleOutputCallback to a named method and delegate the creation of the Task to another method:

public static void MyMethod()
{
    Callbacks.ConsoleOutputCallback = ConsoleOutputCallback;
}

public static void ConsoleOutputCallback(string message)
{
    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

    Dispatch(
        msg => console.Document.Text += msg,
        message,
        scheduler
    );

    Dispatch(
        msg => someOtherNonControl.Text += msg,
        message,
        scheduler
    );
}

public static void Dispatch<T>(Action<T> action, T parameter, TaskScheduler scheduler)
{
    Task.Factory.StartNew(
        () => action(parameter),
        CancellationToken.None,
        TaskCreationOptions.None,
        scheduler
    );
}


As a followup to your "selfie" answer :D

new Date().getTime()

// to

Date.now()

The effect is the same, but the difference is that you avoid generating a new Date object for the operation. Date.now() just returns the current timestamp.

$galleryItem.innerHTML = $gridItems[i].innerHTML

One problem with innerHTML is that it carries the state of whatever it was you fetched it from. This means if something happens to add the attribute data-foo="bar" into the element or its descendants, this gets copied over. You don't know what data-foo="bar" entails, and there might be side-effects.

An actual case is jQuery using an internal cache mapping of element references. It uses key of that mapping as a custom attribute on the element referenced. Using innerHTML would carry over this attribute to the new stuff, when it should not.


Build embedded XML based on string containment

Because you have the overall root node, (a bit confusing that it changes name from root to paths between the two versions) there shouldn't actually be any inherent difference between nodes of the form "1/" and nodes of the form "1/2/" or longer. It should be possible to completely remove the first loop, and just have a special case definition of parent_path to point it to the actual root.

If you do that, questions about whether dicts or sets are faster for deleting the length one paths, or suitably order preserving, or anything else, become a moot point. There's nothing left that you can't just do directly on lists/arrays, and for single pass iteration they are almost certainly the fastest option.

Memory consumption is something that I can't helpfully speculate about. It will depend on the particulars of your xml library and data. It's a problem if you're running out of memory, in which case profile it to check the usage is where you expect.
If you're allowed to mutate the input array, and are worried about memory, you'd get some small savings and possibly a small efficiency boost for doing the sort in place rather than using sorted. However, you'd need a streaming XML writer (and some moderately knotty logic about when things can be committed) to make a significant difference. As far as I can see from the docs, xml.etree.ElementTree does not have inbuilt support for such streaming.

In terms of runtime, I wouldn't want to speculate about efficiency without measuring it. It might be that you could speed up the regex search, for example, by using re.compile ahead of time. That's unlikely to harm, but it can't help much if parsing the regex is taking an insignificant amount of time to begin with.

Code style, it would be nice to use more descriptive names, and in particular to avoid single letter variables. The comments, especially the comment on the sorting explaining the subtle bug in the naive version, are very helpful.


strToHex ( string to its hex representation as string)

Bug

As Carsten points out, you need to allocate \$(\text{length}\cdot 2)+1\$ bytes, rather than \$(\text{length}\cdot2)\$ to account for the null terminator sprintf() adds.

Formatting

Most C formatting guides do not include spaces around the arguments to function calls, nor the expressions within an if-statement. For an example of a C style most C programmers would find acceptable, see OpenBSD's style(9) manual.

I choose to associate * with the variable name, rather than floating between the type and name. This disambiguates the following example:

int *a, b;

Here, a is a pointer to an integer, but b is only an integer. By moving the asterisk next to the name, it makes this clearer.

int length = strlen ( str );
char * newStr = malloc (length * 2 );
if ( !newStr) shutDown ( "can't allocate memory" ) ;

Becomes:

int const len = strlen(str);
char *const new_str = malloc(1 + len * 2);

if (new_str == NULL) {
    shutDown("can't allocate memory");
}

Error checking

Rather than calling shutDown() and exit()ing the program, you should instead return an error value which can be checked by the caller of str_to_hex(). Because you return a pointer, you can return NULL to indicate an error occurred and the caller should check errno.

Likewise, on some systems your program can incorrectly exit when length == 0. If we look at the manual page for malloc(3):

  Return Value

  The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL. NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero.

So by returning NULL we account for the case where malloc(3) returns NULL on success.

if (new_str == NULL) {
    shutDown("can't alloc memory");
}

Becomes:

if (new_str == NULL) {
    return NULL;
}

If you choose, you can also check if str is NULL before calling strlen(). This is up to you, and it's not uncommon in C to ignore this case and leave it as user error.

Looping

Use the size_t type in your loop rather than int. size_t is guaranteed be wide enough to hold any array index, while int is not.

Using i rather than x is more common for looping variables.

The y variable isn't needed. You can simply use str[i] in its place.

In terms of performance there's likely a faster option than using sprintf(). You should look into strtol(3).

Conclusion

Here is the code I ended up with:

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

char *
str_to_hex(char const *const str)
{
    size_t const len = strlen(str);

    char *const new_str = malloc(1 + len * 2);

    if (new_str == NULL) {
        return NULL;
    }

    for (size_t i = 0; i < len; ++i) {
        sprintf(new_str + i * 2, "%02X", str[i]);
    }

    return new_str;
}

int
main(void)
{
    char *str = "abz";
    char *hex = str_to_hex(str);

    if (hex == NULL && strlen(str) != 0) {
        /* error ... */
    }

    printf("%s\n",hex);

    free(hex);
}

Hope this helps!


Here are some things that may help you improve your program.
C++ version
Use all of the required #includes
The type std::vector<size_t> is used in the definition of calculate_distance() in the header file, but #include <vector> is missing from the list of includes there.  Also, std::max() is used, but #include <algorithm> is missing from the .cpp file.
Minimize the interface
The .h file is a declaration of the interface to your software.  The .cpp is the implementation of that interface.  It is good design practice to minimize the interface to just that which is needed by outside programs.  For that reason, I would remove the calculate_distance() function from the header.
Make local functions static
With the smaller interface as advocated above, the calculate_distance function becomes an implementation detail used only within the .cpp file.  For that reason, it should be made static so the compiler knows that it's safe to inline the function.
Use a switch rather than a series of if statements
The code currently contains this:
for (size_t i = 0; i < s.size(); ++i) {
    auto ss = s[i];
    if (ss == ')') {
        if (!opened.empty()) {
            closed.push_back({opened.back()});
            closed.push_back(i);
            opened.pop_back();
        }
    }
    if (ss == '(') {
        opened.push_back(i);
    }
}

It would be a little faster and a little easier to read if it were instead written like this:
for (size_t i = 0; i < s.size(); ++i) {
    switch(s[i]) {
        case ')':
            if (!opened.empty()) {
                closed.push_back({opened.back()});
                closed.push_back(i);
                opened.pop_back();
            }
            break;
        case '(':
            opened.push_back(i);
            break;
    }
}

Be careful with signed vs. unsigned
What would it mean if calculate_distance return a negative number?  It probably has no sensible interpretation, so for that reason, I'd recommend having it return an unsigned quantity versus a signed int.
Write test functions
You have provided some test input in the description of the problem, but it would be good to write a full test script to exercise the function.  For this kind of thing, I tend to like to use a test object.  Here's the one I wrote for this code:
class ParenTest {
public:
    ParenTest(std::string_view input, unsigned longest)
        : input{input}
        , longest{longest}
    {}
    unsigned operator()() const {
        return static_cast<unsigned>(get_longest(input));
    }
    bool test() const {
        return longest == operator()();
    }
    friend std::ostream& operator<<(std::ostream& out, const ParenTest& test) {
        auto calculated = test();
        return out << (calculated == test.longest ? "ok  " : "BAD ")
            << "\"" << test.input << "\", " << test.longest << ", got " << calculated << "\n";
    }
private:
    std::string_view input;
    unsigned longest;
};

Now here are some test vectors and a main routine:
int main(int argc, char* argv[]) {
    static const std::vector<ParenTest> tests{
        { "(()", 2 },
        { ")()())", 4 },
        { "", 0 },
        { "(()()()", 6 },
        { "((())((((())))", 8 },
        { "(())(())(()))", 12 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))", 12 },
        { "(())(())(()))(())(())(())(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))"
          "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
    };
    for (const auto &test : tests) {
        std::cout << test;
    }
}

To both assure correctness and also do some timing, I've used my stopwatch template.  The final version of main looks like this:
#include "longest_parentheses.h"
#include "stopwatch.h"
#include <string_view>
#include <iostream>
#include <vector>

// the ParenTest class goes here

int main(int argc, char* argv[]) {
    static const std::vector<ParenTest> tests{
        { "(()", 2 },
        { ")()())", 4 },
        { "", 0 },
        { "(()()()", 6 },
        { "((())((((())))", 8 },
        { "(())(())(()))", 12 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(())(()))", 12 },
        { "(())(())(()))(())(())(())(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
        { "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))"
          "(())(())(()))(())(())(()))(())(())(()))(())(())(()))(())(()((()))(())(())(()))(())(())(()))", 38 },
    };
    for (const auto &test : tests) {
        std::cout << test;
    }
    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " num_trials\n";
        return 1;
    }

    auto iterations = std::stoul(argv[1]);

    Stopwatch<> timer{};
    bool valid{true}

    for (auto i{iterations}; i; --i) {
        valid &= tests.back().test();
    }

    auto elapsed{timer.stop()};
    if (!valid) {
        std::cout << "The program failed!\n";
        return 2;
    }

    std::cout << iterations << " trials took " << elapsed << " microseconds\n"
        " for an average of " << elapsed/iterations << " microseconds/trial\n";
}

Use a better algorithm
The existing code is not so bad, but it's not as efficient as it could be.  On my machine with the code shown above and with one million trials, it takes 5.66 microseconds per invocation of get_longest() on the longest test input, which is also the last of the set.  We can do better.  Here is an alternative routine that uses a std::vector to keep track of each of the starting ( as they occur, but also does the calculation of span length as it encounters each closing ).  Here's how I did it:
unsigned get_longest(const std::string_view& in) {
    struct Span {
        std::size_t begin;
        std::size_t end;
        Span(std::size_t begin, std::size_t end)
            : begin{begin}
            , end{end}
        {}
        std::size_t len() const {
            return end - begin + 1;
        }
        bool is_strictly_enclosing(const Span& other) const {
            return other.begin - begin == 1 &&
                      end - other.end == 1;
        }
        bool is_contiguous_with(const Span& other) const {
            return begin - other.end == 1;
        }
    };
    std::vector<std::size_t> parenmatch;
    std::vector<Span> spans;
    std::size_t longest{0};
    for (std::size_t i{0}; i < in.size(); ++i) {
        switch(in[i]) {
            case '(':
                parenmatch.push_back(i);
                break;
            case ')':
                if (!parenmatch.empty()) {
                    Span curr_span{parenmatch.back(), i};
                    parenmatch.pop_back();
                    if (!spans.empty() && curr_span.is_strictly_enclosing(spans.back())) {
                        // destroy the last one
                        spans.pop_back();
                    }
                    if (!spans.empty() && curr_span.is_contiguous_with(spans.back())) {
                        // merge the contiguous spans
                        spans.back().end = curr_span.end;
                    } else {
                        spans.push_back(curr_span);
                    }
                    longest = std::max(longest, spans.back().len());
                }
                break;
            default:
                parenmatch.clear();
                spans.clear();
        }
    }
    return longest;
}

There is probably still room for improvement, but here's how this works.  First, it keeps track of each Span of matching and nested parentheses.  So () would be correspond to such a span, as would (()).  The code uses is_strictly_enclosing to test for these.  As an example, in (()), the inner pair is found first and would have a span of {1,2}.  The outer pair is found last and has a span of {0,3}.  If we examine the logic, it's now clear what this code is looking for:
bool is_strictly_enclosing(const Span& other) const {
    return other.begin - begin == 1 &&
              end - other.end == 1;
}

Secondly, there is the case of matching but non-nested parentheses such as ()() or (())().  Here again, we use a member function of Span:
bool is_contiguous_with(const Span& other) const {
    return begin - other.end == 1;
}

Using this code, we get the following timing report:

1000000 trials took 562299 microseconds for an average of 0.562299 microseconds/trial

So this version of the code is about 10x faster.  Note too, that it correctly handles malformed input such as ((*)) by reporting 0 for such a string.
Python version
Use elif for mutually exclusive conditions
The check for the opening ( uses if but it would make more sense to use elif here because the two cases (either ( or )) are the only ones considered.  Making just this one change drops each iteration (using the same very long string as in the C++ code) from 74.167 microseconds to 72.444 microseconds.
Don't update values that are unchanged
The code currently has this sequence:
for j in range(len(s)):
    if j in closed:
        cum_distance += 1
    else:
        cum_distance = 0
    max_distance = max(max_distance, cum_distance)

A quick look at the code will verify that max_distance can only get a new value if the if statement is true, so let's move the line there.  This drops the time down to 71.680 microseconds.
Use a faster algorithm
Once again, what works in the C++ version also works in Python.  Here's a Python version of the algorithm above:
def get_longest(s):
    parenmatch = []
    spans = []
    longest = 0
    for i, ss in enumerate(s):
        if ss == '(':
            parenmatch.append(i)
        elif ss == ')':
            if parenmatch:
                curr_span = (parenmatch.pop(), i)
                if spans and spans[-1][0] - curr_span[0] == 1 and curr_span[1] - spans[-1][1] == 1:
                    spans.pop()
                if spans and curr_span[0] - spans[-1][1] == 1:
                    spans[-1] = (spans[-1][0], curr_span[1])
                else:
                    spans.append(curr_span)
                longest = max(longest, spans[-1][1] - spans[-1][0] + 1)
    return longest

This time, the difference is not as dramatic, and the time for this function is 64.562 microseconds.