Kruskals MST Algorithm This code computes the Minimum Spanning Tree of a given graph using Kruskals Algorithm.

It works successfully and I have provided test cases within the code.

I would like feedback on code efficiency (Choice of ds and functions/function size) and anything else to improve the code (Aside from pep 8 compliance, that is something I will be working to fix soon)

Thank you

class Graph:

  def __init__(self):

    self.graph = []
    self.edges = []
    self.parents = {}
    self.size = {}

  def addnode(self, key1, key2, edge=0):

    if key1 not in self.graph:
      self.graph.append(key1)
    if key2 not in self.graph:
      self.graph.append(key2)

    self.edges.append([key1, key2, edge])

  def getparent(self, vertex):

    while self.parents[vertex] != -1:
      vertex = self.parents[vertex]

    return vertex

  def union(self, vertex, neighbour):

    x_par = self.getparent(vertex)
    y_par = self.getparent(neighbour)
    if self.size[x_par] <= self.size[y_par]:
      self.parents[x_par] = y_par
      self.size[y_par] += self.size[x_par]
    else:
      self.parents[y_par] = x_par
      self.size[x_par] += self.size[y_par]

  def kruskal(self):

    mst = []
    total = 0

    for key in self.graph:
      self.parents[key] = -1
      self.size[key] = 1

    self.edges.sort(key = lambda x:x[2])

    for edge in self.edges:
        vertex, neighbour, weight_edge = edge
        x_par = self.getparent(vertex)
        y_par = self.getparent(neighbour)
        if x_par != y_par:
          self.union(x_par, y_par)
          mst.append(edge)
          total += weight_edge

    print(mst)
    print('mst of weight:', total)

if __name__ == '__main__':
  g = Graph()
  g.addnode(0, 1, 10)
  g.addnode(0, 2, 6)
  g.addnode(0, 3, 5)
  g.addnode(1, 3, 15)
  g.addnode(2, 3, 4)
  g.kruskal()

Performance

The main cost of your implementation is in two areas, the sorting and the set memebership test.

When you do check for parents, it is generally advisable to update each of the parent of each of the ones you looked at, such that they would only be one step away from their parent the next time. Here is how it could look:

  def shortcut(self, vertex, parent):
    while self.parents[vertex] != -1:
      next = self.parents[vertex]
      self.parents[vertex] = parent
      vertex = next

  def getparent(self, vertex):
    start = vertex
    while self.parents[vertex] != -1:
      vertex = self.parents[vertex]

    self.shortcut(start, vertex)
    return vertex

It can be shown that this assymtotically reduces the cost of the set membership test in this kind of union based data-structure.

You can also cut these comparisons short when you have found the full minimal spanning tree, which would save you all the extra parent lookups for all the edges following in the sorted sequence. You can do this by checking whether you are done after adding an edge with len(mst) == len(self.graph) - 1, and then do a break or return the result, so the code (the loop in the kruskal function) would look like this:

    for edge in self.edges:
        vertex, neighbour, weight_edge = edge
        x_par = self.getparent(vertex)
        y_par = self.getparent(neighbour)
        if x_par != y_par:
          self.union(x_par, y_par)
          mst.append(edge)
          total += weight_edge
          if len(mst) == len(self.graph) - 1:
            break

For sorting you have two problems:

You specify a key function manually, which means the algorithm will have to call that key function.
You sort more of the problem than you really need to.

The first part comes from that sort may be implemented in a faster language (it looks to be so in my installation), which means that it generally runs faster if it never have to enter python code, which the manual key function breaks. If you however changes the order of attributes in how you store your edges, such that the weight is first, then you can use the default comparison, which will do lexiographic ordering, which in turn means you get it sorted primarily on the edge weights.

For the second part, the main problem is that you only need to search until you get the n-1 edges needed to finish the minimum spanning tree, so you only need this amount sorted. It would therefore be advisable to use a sorting scheme, such as heapsort, where you can stop half-way through and only need to effectively pay in performance for the amount you needed. The downside is that the heapq python module looks to be mainly implemented in python, which means its actual performance might be slower unless you really only need a very small subset (this would typically depend on the graph).

Convenience

There are a few areas in the code, which with some improvement would be more convinient/better future-proofed.

The main one here is the need for a simpler way to add several edges to a graph, or even construct a graph with edges already in it. Here is how I would do it:

  def __init__(self, edges=None):

    self.graph = []
    self.edges = []
    self.parents = {}
    self.size = {}
    self.add_edges(edges)

  def add_edges(self, edges=None):
    if edges is not None:
      for edge in edges:
        self.add_node(*edge)

The construction of your graph would then be this simple:

  g = Graph([
    (0, 1, 10)
    (0, 2, 6)
    (0, 3, 5)
    (1, 3, 15)
    (2, 3, 4) ])

In the union fuction, we could parameterize the if statement as follows:

    child, parent = (x_par, y_par) if self.size[x_par] <= self.size[y_par] else (y_par, x_par)
    self.parents[child] = parent
    self.size[parent] += self.size[child]

This would also seperate the orthogonal parts of the logic, which would make it easier to maintain.

Lastly it would be a good idea to have the kruskal method just return mts, total and then print outside, as this would allow actual use of the class in code outside of problems where this is the final solution.


Check if IP address list has subnet or is supernet I need to iterate over a list of IP addresses, to check if the elements inside are subnets/supernets between them, for this I use the  IP-address library.
Currently I have the following problem: my second iterator (which I use to iterate over the rest of the list) always starts at 0 and therefore compares each element of the list twice (which I think can be avoided).
Here is part of the txt file from which I create the list:
Name
10.104.181.0/23
10.104.180.0/24
10.132.83.112/32
10.104.183.0/24
10.104.185.0/24
10.104.185.32/24
174.28.164.30/24
178.38.233.0/24
10.104.186.0/24
10.132.208.0/24
10.104.185.42/24
10.130.217.88/32
10.104.24.108/24
10.134.213.84/32
10.134.205.18/32
10.104.182.145/32
10.123.232.95/32
10.130.236.0/24
10.105.26.245/32
10.134.65.250/32
10.134.222.120/32
10.104.184.62/32
10.104.184.61/32
10.105.121.0/24

And here is my python code:
import ipaddress
import sys

fileobj=open("test.txt")
for line in fileobj:
    lines.append(line.strip())#create the list from the txt file
lines.pop(0)#remove line "name"
for line in lines:
    for j in range(1,len(lines)):
        if(line==lines[j]):#problem here: j start always at 1
            print('comparing same line.... skipping')
            pass
        elif(ipaddress.ip_network(line,False).subnet_of(ipaddress.ip_network(lines[j],False))):#check if subnet
            print(line+' is subnet of network'+lines[j])
        elif(ipaddress.ip_network(line,False).supernet_of(ipaddress.ip_network(lines[j],False))):#check if supernet
            print(line+' is super of network'+lines[j])

What I'm looking for:

How to solve the problem of my second iterator.
Any other improvement (whatever it is, formatting, algorithm,...) is appreciated.

This section:
fileobj=open("test.txt")
for line in fileobj:
    lines.append(line.strip())#create the list from the txt file
lines.pop(0)#remove line "name"

has an alternate representation as an iterator-adjustment to skip one line:
with open('test.txt') as fileobj:
    next(fileobj)
    lines = [line.strip() for line in fileobj]

Also note use of a list comprehension and a context manager.
Your separate supernet/subnet checks are redundant. If A is a subnet of B, B is a supernet of A; so it's not even worth doing the second.
Algorithmically: if your list is very, very long you may want to consider moving away from your current nested loop. Your current loop is O(n^2) in time and I don't immediately see a way to avoid this . Consider doing something like - roughly -

Populate a list of tuples of start and end IP address integers and IP objects; the packed integer representation can be obtained by casting an ipaddress object to int
Sort this list; a naive .sort() should work
On your outer loop, iterate over all entries for subnet selection
Prune away any potential supernets whose end is so low that they will never match again
On your inner loop, iterate from the beginning of the list up to the current entry and then quit.

This sortation and early-bail should improve your performance a little.
Example
Edit: "a little" seems to be a (vast) understatement; comparing the two:
from collections import OrderedDict
from functools import partial
from ipaddress import IPv4Network
from random import randrange, randbytes, seed
from timeit import timeit
from typing import Iterable, Tuple, Sequence

NetRow = Tuple[int, int, str]
IndexRow = Tuple[int, int]

def parse_addresses(filename: str) -> Iterable[NetRow]:
    with open(filename) as f:
        next(f)
        for line in f:
            net_str = line.strip()
            net = IPv4Network(net_str, strict=False)
            yield int(net.network_address), int(net.broadcast_address), net_str

def end_indices(nets: Sequence[NetRow]) -> Iterable[IndexRow]:
    for i, (start, end, net) in enumerate(nets):
        yield end, i

def new(filename: str):
    # Start and end integers and network objects ordered by start
    subnets = sorted(parse_addresses(filename))

    # Supernet dictionary by index from subnets; in same order as subnets
    supernets = OrderedDict(enumerate(subnets))

    # List of tuples of subnet end to subnet index, used for pruning
    ends = sorted(end_indices(subnets))

    for sub_start, sub_end, subnet in subnets:

        # If there are any supernets whose end occurs before the current start,
        # they need to be pruned because they will never match
        for n_to_drop, (end, index) in enumerate(ends):
            if end >= sub_start:
                break
            supernets.pop(index)
        del ends[:n_to_drop]

        for super_start, super_end, supernet in supernets.values():
            # Skip comparison to self
            if subnet is supernet:
                continue

            # If the current supernet start is after the current subnet start,
            # there will not be any more supernets that encompass this subnet
            if super_start > sub_start:
                break

            # The supernet start occurs at or before the current subnet start.
            # If the supernet end occurs at or after the current subnet end,
            # then the supernet encompasses the subnet.
            if super_end >= sub_end:
                # assert subnet.subnet_of(supernet)
                print(f'{subnet} is subnet of {supernet}')

def old(filename: str):
    lines = []
    fileobj = open(filename)
    for line in fileobj:
        lines.append(line.strip())  # create the list from the txt file
    lines.pop(0)  # remove line "name"
    for line in lines:
        for j in range(1, len(lines)):
            if (line == lines[j]):  # problem here: j start always at 1
                # print('comparing same line.... skipping')
                pass
            elif (IPv4Network(line, False).subnet_of(
                    IPv4Network(lines[j], False))):  # check if subnet
                print(line
                      + ' is subnet of network ' + lines[j])
            #elif (IPv4Network(line, False).supernet_of(
            #        IPv4Network(lines[j], False))):  # check if supernet
            #    print(line
            #          + ' is super of network ' + lines[j])

def generate_test(filename: str, min_mask: int, rows: int):
    seed(0)  # for repeatability
    with open(filename, 'w') as f:
        f.write('Name\n')
        for _ in range(rows):
            addr = '.'.join(str(b) for b in randbytes(4))
            mask = randrange(min_mask, 31)
            f.write(f'{addr}/{mask}\n')

if __name__ == '__main__':
    generate_test('bigtest.txt', min_mask=14, rows=1_000)

    for method, title in (
        (new, 'New'),
        (old, 'Old'),
    ):
        print(f'{title} method:')
        t = timeit(partial(method, 'bigtest.txt'), number=1)
        print(f'{t:.3f}s\n')

Output
New method:
50.100.190.198/30 is subnet of 50.100.216.175/16
68.143.197.241/26 is subnet of 68.142.21.93/15
87.88.133.166/17 is subnet of 87.88.222.120/17
87.88.222.120/17 is subnet of 87.88.133.166/17
101.186.112.235/19 is subnet of 101.186.155.104/14
106.183.253.213/22 is subnet of 106.180.121.90/14
110.142.177.23/29 is subnet of 110.140.246.97/14
110.206.109.247/20 is subnet of 110.205.222.149/14
125.43.157.205/28 is subnet of 125.42.59.132/15
138.157.204.243/29 is subnet of 138.157.172.230/14
158.221.173.230/30 is subnet of 158.221.69.71/14
239.186.245.174/18 is subnet of 239.185.216.72/14
243.3.157.156/28 is subnet of 243.3.56.96/16
0.029s

Old method:
87.88.222.120/17 is subnet of network 87.88.133.166/17
125.43.157.205/28 is subnet of network 125.42.59.132/15
106.183.253.213/22 is subnet of network 106.180.121.90/14
101.186.112.235/19 is subnet of network 101.186.155.104/14
158.221.173.230/30 is subnet of network 158.221.69.71/14
243.3.157.156/28 is subnet of network 243.3.56.96/16
87.88.133.166/17 is subnet of network 87.88.222.120/17
50.100.190.198/30 is subnet of network 50.100.216.175/16
110.206.109.247/20 is subnet of network 110.205.222.149/14
138.157.204.243/29 is subnet of network 138.157.172.230/14
110.142.177.23/29 is subnet of network 110.140.246.97/14
68.143.197.241/26 is subnet of network 68.142.21.93/15
239.186.245.174/18 is subnet of network 239.185.216.72/14
33.487s

A more "fair" comparison uses your own algorithm but with a pre-parse step:
def old(filename: str):
    lines = []
    with open(filename) as fileobj:
        next(fileobj)
        for line in fileobj:
            net_str = line.strip()
            lines.append((net_str, IPv4Network(net_str, False)))

    for subnet_str, subnet in lines:
        for supernet_str, supernet in lines:
            if subnet_str is supernet_str:
                continue
            if subnet.subnet_of(supernet):
                print(f'{subnet_str} is subnet of {supernet_str}')

This still took 1.87s on my machine, which is ~58x the time of the 32ms of the new method.
Comparing the new and fair-old methods for min_mask=20, rows=10_000 is more dramatic: 0.362s vs. 249.763s, ~690x faster.


Idiomatic Scala try option code block Basically, this function returns a list of flights for an airline. But if the airline doesn't exist, I want to throw some custom runtime exception. If that airline does exist, I want to return a list of flights (which could potentially be empty).

Is this is the standard way of doing things in Scala, or is there a better way to write this code?

Coming from a Java background, I'm still trying to get to grips with the Scala way of doing things.

def getFlightsForAirline(id:Long):Try[Option[List[Flight]]] = {
     val maybeAirline:Option[Airline] = Airline.getById(id)

     maybeAirline match {
       case Some(airline) => {
          Success(Flight.getFlightsByAirline(airline))
       }
       case None => Failure(new RecordNotFoundException("Couldnt find airline"))
     }
   }

The maybeAirline variable isn't necessary. Note that the type annotation in the declaration is optional, and can easily be inferred by the compiler. So I would change that to:

def getFlightsForAirline(id: Long): Try[Option[List[Flight]]] =
  Airline.getById(id) match {
    case Some(airline) => Success(Flight.getFlightsByAirline(airline))
    case None => Failure(new RecordNotFoundException("Couldnt find airline"))
  }

Notice that the Scala style guide suggests putting a space after the colon in a type annotation – name: Type instead of name:Type.
Every time you destructure an Option with match/case, they kill a puppy because you should have probably used map. Well, almost every time, because the Failure is an important part of this function's behaviour. But this still is somewhat of a code smell.
The return type Try[Option[List[Flight]]] strikes me as rather weird: What is the difference between Success(Some(List())) and Success(None())? I guess the latter might occur if getFlightsByAirline isn't passed a valid airline.

Try, Option and List are essentially the same thing (either you get a result, or there isn't anything there: Failure, None or empty List). Therefore it does not make much sense to nest them, and it would be better to return a Try[List[Flight]]. This could be implemented along the lines of:

def getFlightsForAirline(id: Long): Try[List[Flight]] =
  Airline.getById(id) flatMap { Flight.getFlightsByAirline(_) } match {
    case Some(flights) => Success(flights)
    case None => Failure(new RecordNotFoundException("Couldnt find airline"))
  }

This way, the Failure is returned if either of the getXByY methods returns None.

Interestingly, there is no builtin way to transform an Option to a Try (along the lines of maybe toTry { MyException("Reason") }) while there is a try.toOption method.
Your RecordNotFoundException will have a much more Scala-ish vibe if you use a case class here. This way, you can omit the new to create a new instance, and just write: Failure(RecordNotFoundException("..."))


Binary search for IOI problem: Cave Question

http://www.ioinformatics.org/locations/ioi13/contest/day2/cave/cave.pdf

Code

#include "cave.h"
#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 5001;
int status[MAXN] , door[MAXN] , guess[MAXN];

void exploreCave(int N){
  memset(door , -1 , sizeof(door));
  for(int n = 0 ; n < N ; n++){
    int r = tryCombination(status);
    int low = 0 , high = N - 1;
    while(low != high){
      bool changed = false;
      int a = low , b = (low + high) / 2;
      for(int i = 0 ; i < N ; i++){
        if(i >= a && i <= b){
          if(door[i] != -1){
            guess[i] = status[i];
          }
          else {
            guess[i] = !status[i];
            changed = true;
          }
        }
        else guess[i] = status[i];
      }
      int K = r;
      if(changed) K = tryCombination(guess);
      if(r == n){
        if(K > n || K == -1)
          high = b;
        else low = b + 1;
      }
      else {
        if(K == n) high = b;
        else low = b + 1;
      }
    }
    door[low] = n;
    if(r == n) status[low] = !status[low];
  }
    answer(status , door);
}

Issue

While this is a working and correct code, I runs at O(NlogN) time(I think).  Is there a possible way to further shorten the time complexity?  This code uses binary search.

Prefer Clear Naming over using namespace std

Before I go into why

using namespace std;

is to be avoided, in the case of this program it is not needed since there is no use of any functions that derive from the std namespace in this code.

According to the MSDN website:

  Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

A collision is when 2 different functions have the same name, the same arguement types and a similar functionallity (this is why they have the same name). Someone developing software may want to override a function such as std::cout, std::cin or they may want to override the functionallity of a class such as std::vector or std::stack. Namespaces allow these constructs to be overriden.

The use of the programming statement:

using namespace std;

hides the fact that cin, cout, vector and stack are coming from the namespace std where cin, cout,
vector and stack are used in the code. This can cause confusion of where the code is actually
coming from.

As the software becomes more complex and uses more libraries this becomes a bigger problem.

For a more detailed discussion of why it is a bad idea to use using namespace std; see this stackoverflow question and stackoverflow question.

Use Standard Libraries When Possible

Instead of writing a binary search it might be better to use the one provided by the standard template library. It saves time when writing code, and every effort has been made to make the standard library functions as efficient as possible, which means you won't generally have to optimize it.

To use the standard library binary search you would need to include the  algorithm header

#include <algorithm>

Reduce Complexity, Follow SRP

The Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

  Robert C. Martin expresses the principle as follows:
          A class should have only one reason to change.

While this is primarily targeted at classes in object oriented languages it applies to functions and subroutines well.

The void exploreCave(int N) function could be broken up into at least two functions. This code specifically seems to be a good candidate for a function.

    while (low != high) {
        bool changed = false;
        int a = low;
        int b = (low + high) / 2;
        for (int i = 0; i < N; i++) {
            if (i >= a && i <= b) {
                if (door[i] != -1) {
                    guess[i] = status[i];
                }
                else {
                    guess[i] = !status[i];
                    changed = true;
                }
            }
            else guess[i] = status[i];
        }
    }

The more separate functions there are the easier it is to understand or read the code. This also makes it easier for any programmer to maintain or debug the code.

Use Meaningful Variable Names

The variables r, K and N do not help the reader understand the code. It's not clear at all what the variables r and K are. N is defined only if one reads the problem description, which is not currently included in the question. There are some good variable names such as guess, status, and changed although it might be better to make the array names plural. Variable naming should be consistent. The function name exploreCave is quite clear as well. Using i and j is quite common and understandable, but what is r and K? A second question is why is K needed since r does not change between it's assignment and usage?

Use One Statement to Declare and Initialize a Single Variable

When the arrays status, door and guess are declared as when the variables low and high are declared and initialized it is done so on a single line. This makes the code harder to read and maintain. I initially missed the declaration and initialization of high. To make the code more readable and easier to maintain declare variables on separate lines in new statements.

    int low = 0;
    int high = N - 1;

is much easier to read and maintain than

    int low = 0 , high = N - 1;

You may not be the person maintaining the code, and even if you are it may be multiple years between initially writing the code and modifying it. It is important to make the code as readable as possible.


Iterate dictionary object efficiently in c# with pre defined keys? I have a dictionary that I need to iterate efficiently. I already know about the keys beforehand which I need to extract from values dictionary object.
What's the best way to do that? I have around 20 entries in dictionary object as of now.

Below is how I am doing it but wanted to see if we can optimize it by just getting values of key directly since I already know about what key I need to extract from them instead of using foreach loop here which is not good in terms of performance?

  // predefined keys
  public const string ABC = "header-abc";
  public const string PQR = "header-pqr";
  public const string DEF = "header-def";
  public const string HIP = "header-hip";

  foreach (KeyValuePair<string, StringValues> v in values)
  {
      string key = v.Key;
      StringValues val = v.Value;
      if (val.Count > 0)
      {
          if (!string.IsNullOrWhiteSpace(val[0]))
          {
              switch (key)
              {
                  case ABC:
                      HeadOne = val[0];
                      HeadOneId = HeadOne;
                      break;
                  case PQR:
                      HeadTwo = val[0];
                      HeadTwoId = HeadTwo;
                      break;
                  case DEF:
                      HeadThree = val[0];
                      HeadThreeId = HeadThree;
                      break;
                  case HIP:
                      HeadFour = val[0];
                      HeadFourId = HeadFour;
                      break;
                  //.. bunch of other case block here with similar stuff
              }
          }
      }
  }

As of now it looks redundant to iterate values dictionary object since I already know about all my keys that I need to extract from values dictionary object. What's the best way (in terms of performance) to do this considering keys are already known beforehand?

One option I can think of is instead of foreach loop here can we use keys property of iterating dictionary?

I believe you can do this if you put the header keys inside an array, and then you can loop over the array itself, and use TryGetValue for the dictionary.

This is the simplest form for it :

public readonly string[] HeaderKeys = {
    "header-abc",
    "header-pqr",
    "header-def",
    "header-hip"
}

for(var x = 0; x < HeaderKeys.Length; x++)
{
    var isKeyExist = values.TryGetValue(HeaderKeys[x], var KeyValue);

    // if there is no key defined, just go to the next iteration.
    if(!isKeyExist) { continue; }

    switch (HeaderKeys[x])
    {
      case "header-abc":
          // inline assigning
          HeadOne = HeadOneId = KeyValue;
          break;
      case "header-pqr":
          HeadTwo = HeadTwoId = KeyValue;
          break;
      case "header-def":
          HeadThree = HeadThreeId = KeyValue;
          break;
      case "header-hip":
          HeadFour = HeadFourId = KeyValue;
          break;
      //.. bunch of other case block here with similar stuff
    }
}

You need a readonly string[] this way, it can't be changed once initialized. System.Array is the lightest, and yet the simplest array, so using for loop with it would give you the fastest iteration over any other collection type.

Next, you only want to pass each header key to the TryGetValue and get the value. The TryGetValue would return true if the value has been out, and false if there is none.

Then, you have one line if condition :

    // if there is no key defined, just go to the next iteration.
    if(!isKeyExist) { continue; }

This would skip any iteration if the result of TryGetValue is false.
And I believe that string.IsNullOrWhiteSpace(KeyValue) is an extra unneeded work. So, I got rid of it. because even if the KeyValue is null or empty, the variables would be also null. So, at this stage you're just assigning variables, the other validation would be on other part of the current system where it needs to be critical to have a value.

Now, assigning the variables like this :

HeadOne = KeyValue;
HeadOneId = HeadOne;

can be simplified to this :

HeadOne = HeadOneId = KeyValue;

the difference is that the first one would let the compiler read the value twice. While the second would read it once, and assign it twice.


Udacity Intro to HTML and CSS layout sample I'm going through the Udacity Intro to HTML and CSS course at the moment, and one of the exercises is to convert this mockup to HTML and CSS.

I did the following, and it looks ok-ish:

HTML:

<!DOCTYPE html>

  <title>Jane Doette / Front-end Ninja</title>
  <link rel="stylesheet" href="css/style.css">

Jane Doette

Front-end Ninja

Featured Work

Appify

https://github.com/udacity/Appify/

Sunflower

https://github.com/udacity/Sunflower/

Bokeh

https://github.com/udacity/Bokeh/

CSS:

@import url(http://fonts.googleapis.com/css?family=Lato:100,300);

/* Sample framework supplied with the course */

* {
  /*border: 1px solid red !important;*/
  font-family: Lato, sans-serif;
  color: #1f1f1f;
}

* {
  -ms-box-sizing: border-box;
  box-sizing: border-box;
}

.row {
  margin-bottom: 20px;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

/* End of the sample framework */

div.page-content {
  width: 960px;
  margin: auto;
}

div.main-title {
  margin-left: auto;
  text-align: right;
  text-transform: uppercase;
}

div.main-title h1 {
  font-size: 58px;
  font-weight: 100;
  margin-bottom: 0;
}

div.main-title h2 {
  font-size: 18px;
  font-weight: 300;
  margin-top: 0;
}

header.main-header {
  align-items: center;
  border-bottom: 5px solid silver;
  margin-bottom: 30px;
}

div.hero-image {
  max-height: 400px;
  overflow: hidden;
}

div.hero-image img {
  width: 100%;
}

section.featured-work .row {
  justify-content: space-between;
  margin-left: auto;
  margin-right: auto;
}

div.work-screenshot {
  width: 300px;
  height: 200px;
  overflow: hidden;
  position: relative;
}

.featured-work div {
  text-align: center;
}

.featured-work p {
  margin-top: 0;
}

.featured-work p a {
  color: #bebebe;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

div.work-screenshot img {
  max-width: 300px;
}

h2 {
  font-size: 38px;
  font-weight: 300;
  color: #9e9e9e;
  margin: 30px 5px 10px 5px;
}

h3 {
  font-size: 36px;
  text-transform: uppercase;
  margin: 10px 0;
  color: #6e6e6e;
}

Unnecessary prefixes

Don't add prefixes unless you actually need them.  When in doubt, you can check can i use.  Otherwise, there are various autoprefixers you can use that will do it for you.

* {
  -ms-box-sizing: border-box; /* no browser supports this */
  box-sizing: border-box;
}

Subheadings marked up using hn elements

  h1–h6 elements must not be used to markup subheadings, subtitles, alternative titles and taglines unless intended to be the heading for a new section or subsection.

Source: http://www.w3.org/TR/html5/common-idioms.html#sub-head

Jane Doette

Front-end Ninja

The W3C recommends either of these markup options for the subheading idiom:

HTML 5.1 Nightly

A vocabulary and associated APIs for HTML and XHTML

Editor's Draft 9 May 2013

Or

Ramones

   Hey! Ho! Let's Go

Poor contrast

The link color is extremely washed out and is barely legible on one of my displays.  Links, by their very nature, must stand out.  Blue is the recommended color for usability reasons, but if you need to change it, you need a good reason for it (and making it less visible than the surrounding content is not a good reason).

I get that this is probably a requirement for the exercise, but it is something you need to be aware of.  If a designer gives this to you, you need to push back and tell them that this is not acceptable (get support from your UX department if you have one).

Semantic class names

For the most part, you did a really good job of using semantic class names (eg.
), which is why it kills me to see so many unsemantic class names thrown into the mix (eg ,
, .col-1, etc.).

Semantic markup

You've got the right idea with your markup, but there's a lot of room for improvement here.  For instance, your screenshots use a lot more markup than they really need and it isn't very semantic.  You can slim this down by using lists and taking advantage of descendant selectors.

Appify

https://github.com/udacity/Appify/

Sunflower

https://github.com/udacity/Sunflower/

Bokeh

https://github.com/udacity/Bokeh/

Can be rewritten like this:

http://codepen.io/cimmanon/pen/ZGGMNM

Markup

      Appify

      Appify

      Appify

CSS

ul.projects {
  display: table;
  width: 100%;
  box-sizing: border-box;
  font-size: 1.3em;
}

ul.projects li {
  display: table-cell;
  width: 33%;
  text-align: center;
}

ul.projects img {
  display: block;
  margin: 0 auto .5em;
}

ul.projects a:after {
  display: block;
  content: attr(href);
  font-size: .769em;
  margin-top: .5em;
}

Depending on the content, though, it might be better to use background images instead of the image element (search for css image replacement to learn more).

Use Flexbox responsibly

Unless the effect you're trying to achieve is difficult or impossible to do without Flexbox, don't use Flexbox.  In this case, you can do the same thing with the table/table-cell display properties (as illustrated above) and it usually requires less CSS to do so.


Breadth-first tree traversal using STL list I am writing code for breadth-first search of a tree with C++'s STL.  Please help as I am new to the STL.

#include<iostream>
#include<malloc.h> //on llvm we don't need this
#include<list>
using namespace std;
typedef struct Node{
    int val;
    struct Node* left;
    struct Node* right;
}node;
void push(node** root,int val)
{
    if(!(*root))
    {
        node* temp=(node*)malloc(sizeof(node));
        temp->val=val;
        temp->right=temp->left=NULL;
        *root=temp;
    }
    else if(val<(*root)->val)
        push(&((*root)->left),val);
    else
        push(&((*root)->right),val);
}

void printout(node* head)
{
    node* temp;
    temp=head;
    list<node*>qu;

    //using bfs here
    while(temp!=NULL)
    {
        cout<<temp->val<<endl;
        if(temp->left!=NULL)
            qu.push_back(temp->left);
        if(temp->right!=NULL)
            qu.push_back(temp->right);

        free(temp);
            if (qu.empty())
            {   break;
            }

        temp=qu.front();
        qu.pop_front();
    }
}

int main()
{
    node* root=NULL;
    push(&root,3);
    push(&root,4);
    push(&root,1);
    push(&root,10);
    push(&root,2);
    printout(root);
}

The output is:

3
1
4
2
10

Don't use malloc(). If you do then you will need to track memory that is allocated with new and that allocated with malloc and use the appropriate de-allocation functions. Also using new calls the constructor and makes sure the object is correctly initialized.

#include<malloc.h> //on llvm we don't need this

Don't do this:

using namespace std;

See Why is “using namespace std;” considered bad practice?

In C++ you don't need to typedef structs. struct names are in the same namespace as everything else. Also Add a constructor to make sure things are correctly initialized.

typedef struct Node{
    int val;
    struct Node* left;
    struct Node* right;
}node;

// Prefer
struct Node
{
     int    val;
     Node*  left;
     Node*  right;
     Node(int v):val(v), left(NULL), right(NULL) {}
};

When pushing a value onto a tree or list. Return the new value rather than pass out values.

void push(node** root,int val)

// Your current usage is:
push(&head, 5);

// Easier usage
head = push(head, 5);

Don't use C casts

        node* temp=(node*)malloc(sizeof(node));

If you must cast then use one of the C++ cast's. But any casts are a sign of bad design. Also using new means this is not required.

// Easier implementation of push:
Node* push(Node* current, value)
{
    if (current == NULL)
    {   return new Node(value);
    }

    if (value <= current->value)
        current->left  = push(current->left,  value);
    else
        current->right = push(current->right, value);

    return current;
}

In your breadth first printing of the tree don't treat the head as special. You should just push the head node onto the list. The loop while the list is not empty. Thus you remove the item at the top of the loop not the bottom.

// Code deliberately left out to make you work.

Don't free the nodes as past of the print function. Add a destructor to your node. So that it calls delete on left and right.

~Node()
{    delete left;
     delete right;
}

Then all you need to do is delete the head and all the nodes will be destroyed correctly.

Your design should hide the memory management. You should put the head node inside its own structure. So that it hides all the memory management and you the user of your class does not need to worry about any of that

class Tree
{
    Node*   head;
    Tree(Tree const& copy);
    Tree& operator=(Tree const& rhs);
    public:
        Tree(): head(NULL) {}  // Set up empty tree.
       ~Tree() {delete head;}  // Memory management done.

        void push(int val)
        {
            head = ::push(head, val);
        }
        void printBF()
        {
            ::printout(head);
        }
};

Note the functions you wrote should also made as members of Node.


Infix epression evaluation I'm looking for some feedback on my OCaml implementation of some methods to translate infix expressions to postfix and then evaluate them.

I'm very new to OCaml, coming from C#/Java and JavaScript so pretty much any advice is appreciated, in particular how to make it more idiomatic or "functional".

It seems like I have to reverse my stack at some point because I want to operate on both sides, is this unavoidable? Could I be using better exceptions for my helper functions? Is it good practice to declare helper functions like I did? apply_and_store and str_to_fn could be inside eval_postfix, is it better to have them encapsulated or to keep eval_postfix cleaner?

let explode_to_strings (s : string) : string list =
    Str.split (Str.regexp "[ \t]+") s;;

(* Method from pleac.sourceforge.net *)
let is_Integer (s : string) : bool =
    try ignore (int_of_string s); true with Failure _ -> false;;

let str_to_fn (s : string) : (int -> int -> int) =
    match s with
    | "+" -> (+)
    | "-" -> (-)
    | "*" -> ( * )
    | "/" -> (/)
    | _ -> raise (Invalid_argument "Not an operator");;

let apply_and_store (lst : 'a list) (fn : 'a -> 'a -> 'a) : 'a list =
    match lst with
    | one :: two :: tl -> fn two one :: tl
    | _ -> raise (Invalid_argument "List too short");;

let prec (s : string) : int =
    match s with
    | "+" | "-" -> 1
    | "*" | "/" -> 2
    | _ -> raise (Invalid_argument "Not in operator table");;

let infix_to_postfix (lst : string list) : string list =
    let rec
        push (elem : string) (output : string list) (ops : string list) : (string list * string list) =
            match ops with
            | [] -> (output, elem :: ops)
            | hd :: tl ->   if prec elem <= prec hd
                            then push elem (hd :: output) tl
                            else (output, elem :: ops)
    in
    let rec
        aux (l : string list) (output : string list) (ops : string list) : string list =
            match l with
            | [] -> ops @ output
            | hd :: tl ->   if is_Integer hd
                            then aux tl (hd :: output) ops
                            else let ret = push hd output ops in
                                aux tl (fst ret) (snd ret)
    in
    aux lst [] [];;

let eval_postfix (lst : string list) : int =
    let rec aux (l : string list) (stack : int list) : int =
        match l with
        | [] -> List.nth stack 0
        | hd :: tl ->   if is_Integer hd
                        then aux tl ((int_of_string hd) :: stack)
                        else aux tl (apply_and_store stack (str_to_fn hd)) in
    aux (List.rev lst) [];;

let eval_infix (s : string) : int =
    eval_postfix (infix_to_postfix (explode_to_strings s));;

TL;DR:

Do not write explicit types!  Symbolic processing is easy in OCaml, use it to your advantage instead of mimicking cryptic algorithms which are only useful in languages where symbolic processing is a pain – as C, C++ or Java.

In OCaml, we never write explicitly write types, as they do in C++ or Java. There is usually no point to do that, since the compiler computes the types for you. If you want to see the types inferred, you can use the -i option of the compiler, or better, use merlin to see the types interactively.

When we write larger programs, we write signature files where we specify the signatures of public functions and abstract types, but this more a software engineering technique you should not bother much while you do your very first steps.

If you do not have to handle the typing information by yourself, your code is much easier to edit, take advantage of this freedom instead of binding yourself again with your old ties!

I could let your code run after a few minor modifications and found out it did not work as expected.  When I read your code, I have difficulties to understand what happens, it is probably a bit too clever – and broken.

There is an important object of the problem that does not appear in your code, it is the abstract syntactic tree (AST) associated to your expression.  If you can generate it from infix, it is trivial to generate the prefix or postfix expression out of it.  In languages like C, C++ or Java, working with ASTs is painful, but ML languages were designed to make this easy.

Here is how we define the type of arithmetic expressions:

  type t =
    | Integer of int
    | Binary of binary * t * t
  and binary =
    | Add
    | Sub
    | Mult
    | Div

It is very easy to handle, say if you want to evaluate an expression

  let rec eval = function
  | Integer(k) -> k
  | Binary(op, a, b) ->
     (match op with
      | Add -> ( + )
      | Sub -> ( - )
      | Mult -> ( * )
      | Div -> ( / )) (eval a) (eval b)

or implement algebraic expansion

  let rec expand = function
  | (Integer(_) | Binary((Add | Sub), _, _)) as a -> a
  | Binary(Mult, Binary(Add, a, b), c) -> …

I do not write the full function, but I hope you get the idea.

Now, the best way to solve our problem is to write a parser converting infix expression from their concrete syntax to an AST.  In practical situations, we should use ocamllex and ocamlyacc to generate the lexer and the parser for arithmetic expressions, but let us write everything manually.

The first step is lexing, which you got pretty right, but let me rewrite it this way, defining a type for tokens and using a more capable regular expression:

  type token =
    | INTEGER of int
    | ADD
    | SUB
    | MULT
    | DIV

  let lexer s =
    let open Str in
    split (regexp " +\\|\\b *") s
    |> List.map
      (function
        | "+" -> ADD
        | "-" -> SUB
        | "*" -> MULT
        | "/" -> DIV
        | n -> (try INTEGER(int_of_string n)
                with _ -> ksprintf failwith "lexer: Invalid token: %s" n))

You can see the \b code for word boundary, it allows to process correctly text with fewer spaces:

# lexer "1+41*2-5/ 7";;
- : token list =
[INTEGER 1; ADD; INTEGER 41; MULT; INTEGER 2; SUB; INTEGER 5; DIV; INTEGER 7]

Once we have converted the string to a token list, it is very easy to analyse its structure, using a continuation-passing-style-mutually-recursive-functions which is much easier as the pedantic designation I wrote can suggest it. :)

We first need a help function

  let _binop op a b =
    Binary(op, a, b)

Now the parser itself looks like this:

  let rec parser_entry cont =
    function
    | [] -> failwith "Unexpected end of input"
    | INTEGER(k) :: ADD :: tl -> cont(parser_entry (_binop Add (Integer(k))) tl)
    | INTEGER(k) :: SUB :: tl -> cont(parser_entry (_binop Sub (Integer(k))) tl)
    | INTEGER(k) :: MULT :: tl -> cont(parser_mult (_binop Mult (Integer(k))) tl)
    | INTEGER(k) :: DIV :: tl -> cont(parser_mult (_binop Div (Integer(k))) tl)
    | INTEGER(k) :: [] -> cont (Integer(k))
    | _ -> failwith "Syntax error"
  and parser_mult cont =
    function
    | [] ->  failwith "Unexpected end of input"
    | INTEGER(k) :: ADD :: tl ->
        (_binop Add (cont (Integer(k)))) (parser_entry (fun x -> x) tl)
    | INTEGER(k) :: SUB :: tl ->
        (_binop Sub (cont (Integer(k)))) (parser_entry (fun x -> x) tl)
    | INTEGER(k) :: MULT :: tl ->
        cont (parser_mult (_binop Mult (Integer(k))) tl)
    | INTEGER(k) :: DIV :: tl ->
        cont (parser_mult (_binop Div (Integer(k))) tl)
    | INTEGER(k) :: [] -> cont (Integer(k))
    | _ -> failwith "Syntax error"
  and parser lst =
    parser_entry (fun x -> x) lst

The parser_entry function is the entry point for the parser and parser_mult reads multiplications and divisions.  The functions have two parameters cont the famous continuation and the list of tokens they need to process.  The continuation encodes the current state of the parser, it is reminiscent of the stack found in LALR parsers. As you see, when parsing in the entry point, the continuation is the outermost function called but in when parsing operators with a priority, the continuation is deeply nested, which is how the priority is represented in the program. Let's try our parser:

# parser(lexer("1"));;
- : t = Integer 1
# parser(lexer("1 +2 - 3"));;
- : t =
Binary (Add, Integer 1, Binary (Sub, Integer 2, Integer 3))
# parser(lexer "1+41*2-5/ 7");;
- : t =
Binary (Add, Integer 1,
 Binary (Sub, Binary (Mult, Integer 41, Integer 2),
  Binary (Div, Integer 5, Integer 7)))

Now it is is trivial to convert an abstract expression to prefix notation:

  let rec to_prefix_string = function
    | Integer(k) -> string_of_int k
    | Binary(op, a, b) ->
        String.concat " " [
          (match op with
           | Add -> "+"
           | Sub -> "-"
           | Mult -> "*"
           | Div -> "/");
          to_prefix_string a;
          to_prefix_string b
        ]

The advantage of symbolic processing is that the code is very explicit!  Now we write a convenience function:

  let infix_to_prefix s =
    to_prefix_string(parser(lexer s))

and try it!

# infix_to_prefix "1+41*2-5/ 7";;
- : string = "+ 1 - * 41 2 / 5 7"


Tables for doctor and patients Please check if my tables specs agree with business rules. Also, please explain the differences between CONSTRAINT, FOREIGN KEY and CONSTRAINT FOREIGN KEY.

I have four MySQL tables (USER, NAME, PATIENT and DOCTOR) with the following rules:

A patient must have a name
A patient can be a user
A doctor must have a name
A doctor must be a user
A patient can be a doctor and vice versa...
By 3 & 5, if a patient is a doctor that patient must be a user

CREATE TABLE USER (
userName VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL UNIQUE,
userId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userEmail VARCHAR(100) NOT NULL,
userPassword VARCHAR(64) NOT NULL,
PRIMARY KEY(userId))

CREATE TABLE PATIENT (
patientId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT UNSIGNED,
patientBirthday CHAR(8), # yyyymmdd
patientBirthplace VARCHAR(50),
patientGender TINYINT(1) UNSIGNED, # 0:male 1:female
patientBloodType TINYINT(1) UNSIGNED,
PRIMARY KEY(patientId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
ON DELETE CASCADE ON UPDATE CASCADE)

CREATE TABLE DOCTOR (
doctorId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT NOT NULL UNSIGNED,
nameId MEDIUMINT NOT NULL UNSIGNED,
PRIMARY KEY(patientId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
CONSTRAINT FOREIGN KEY(nameId) REFERENCES USER(nameId)
ON DELETE CASCADE ON UPDATE CASCADE)

CREATE TABLE NAME (
nameId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT UNSIGNED,
lastName VARCHAR(100) NOT NULL,
firstName VARCHAR(100) NOT NULL,
PRIMARY KEY(nameId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
ON DELETE CASCADE ON UPDATE CASCADE)

The CONSTRAINT word used within a CREATE TABLE or ALTER TABLE tells MySQL engine that this value is not a separate column, but rather it is applied on a column within the table.

The FOREIGN KEY word tells MySQL that whatever is in that field must reference a valid PRIMARY KEY from the other table on INSERT or UPDATE record, otherwise an error is raised.

CONSTRAINT FOREIGN KEY is simply how you phrase it. For more information I suggest reading up about it in the manual.

Now for your criteria:

A patient must have a name: FALSE

That one is not true, unless you added either of those two to your CREATE TABLE PATIENT

NOT NULL to the userID column and a CONSTRAINT FOREIGN KEY (userID) REFERENCES USER(userID)
or, preferably in my opinion:
nameID MEDIUMINT NOT NULL, CONSTRAINT FOREIGN KEY(nameID) REFERENCES NAME(nameID),

A patient can be a user: TRUE
A doctor must have a name: TRUE
A doctor must be a user: TRUE
A patient can be a doctor and vice versa...: TRUE (via userID)
By 3 & 5, if a patient is a doctor that patient must be a user: TRUE


Populate Comboboxes with Hashtables using PowerShell Background

This is a PowerShell program that uses XAML code from Visual Studio to create a GUI. In this program, there are various Comboboxes (Drop-down menus) used to select different features of the program.

What I'm Trying To Acheieve:

I am trying to populate the Comboboxes with the data stored in the different Hashtables.

The Problem

There are different Comboboxes with different names that need to be populated. I cannot iterate through an array of the different Comboboxes. This is because I cannot (or haven't discovered the solution) have an array of objects. Therefore, this is the solution that I have resulted to. This works and solves my problem. However, I want to make the code more efficient and cleaner looking. I want to hear insight from other programmers as to how they would solve this problem, because I am curious.

The Code

For($i = 0; $i -lt $ColumnsHashTable.Column1.Length; $i++) {

    $UI.Combobox1.Items.Add($ColumnsHashTable.Column1[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column2.Length; $i++) {

    $UI.Combobox2.Items.Add($ColumnsHashTable.Column2[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column3.Length; $i++) {

    $UI.Combobox3.Items.Add($ColumnsHashTable.Column3[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column4.Length; $i++) {

    $UI.Combobox4.Items.Add($ColumnsHashTable.Column4[$i])

}

For($i = 0; $i -lt $ColumnsHashTable.Column5.Length; $i++) {

    $UI.Combobox5.Items.Add($ColumnsHashTable.Column5[$i])

}

The first thing to observe is that the five pieces of code are identical except for two parameters that are varying. We can capture the common the code in a function (let's call it populateComboBox), and call that five times:

populateComboBox $UI.Combobox1 $ColumnsHashTable.Column1
populateComboBox $UI.Combobox2 $ColumnsHashTable.Column2
populateComboBox $UI.Combobox3 $ColumnsHashTable.Column3
populateComboBox $UI.Combobox4 $ColumnsHashTable.Column4
populateComboBox $UI.Combobox5 $ColumnsHashTable.Column5

function populateComboBox($comboBox, $column)
{
    For($i = 0; $i -lt $column.Length; $i++) {
        $comboBox.Items.Add($column[$i])
    }
}

It's best not to use old C-style for loops with an index unless you need to because they add visual noise:

populateComboBox $UI.Combobox1 $ColumnsHashTable.Column1
populateComboBox $UI.Combobox2 $ColumnsHashTable.Column2
populateComboBox $UI.Combobox3 $ColumnsHashTable.Column3
populateComboBox $UI.Combobox4 $ColumnsHashTable.Column4
populateComboBox $UI.Combobox5 $ColumnsHashTable.Column5

function populateComboBox($comboBox, $column)
{
    foreach ($item in $column)
    {
        $comboBox.Items.Add($item)
    }
}

We could leave it there. I think that is acceptable code. If we wanted to however, we could take it further in one of two directions.

First, instead of the five calls to populateComboBox, we could make a loop from 1 to 5, and get the appropriate properties to pass to the function with Get-ItemProperty. (I'm assuming that ComboBox1 and so on are really named that way and are not just example names.)

The other idea would be to make an array of (ComboBox, Column) pairs and iterate through that. I quite like that idea because as a general rule it's good to put as much of your code as possible into datastructures. It might be overkill in this case however.

Added stuff:

To expand on the "other idea" above, we can make an array of (ComboBox, Column) pairs. We can use an array of arrays for this:

$comboVals = (
    ($UI.Combobox1, $ColumnsHashTable.Column1),
    ($UI.Combobox2, $ColumnsHashTable.Column2),
    ($UI.Combobox3, $ColumnsHashTable.Column3),
    ($UI.Combobox4, $ColumnsHashTable.Column4),
    ($UI.Combobox5, $ColumnsHashTable.Column5)
    );

(If you are wondering, I didn't put @ symbols on the arrays here because PowerShell is smart enough to figure out here that we are using arrays.)

We can then iterate through that data structure calling the same populateComboBox function we defined before:

foreach ($pair in $comboVals)
{
    populateComboBox $pair[0] $pair[1]
}

Below is the final script. Note that I haven't tried running this because it is not runnable for me since I don't have the ComboBoxes and columns to test with. I think it should be okay though.

$comboVals = (
    ($UI.Combobox1, $ColumnsHashTable.Column1),
    ($UI.Combobox2, $ColumnsHashTable.Column2),
    ($UI.Combobox3, $ColumnsHashTable.Column3),
    ($UI.Combobox4, $ColumnsHashTable.Column4),
    ($UI.Combobox5, $ColumnsHashTable.Column5)
    );

foreach ($pair in $comboVals)
{
    populateComboBox $pair[0] $pair[1]
}

function populateComboBox($comboBox, $column)
{
    foreach ($item in $column)
    {
        $comboBox.Items.Add($item)
    }
}


Simple IPv4 and port validation for chat client This is part of my chat client's code.  It works fine but it looks messy.  Any ideas?

//IP Validation
private void textBox3_Leave(object sender, EventArgs e)
{
    IPAddress ip;
    bool ValidateIP = IPAddress.TryParse(textBox3.Text, out ip);
    if (ValidateIP)
    {
        button2.Enabled = true;
        button3.Enabled = true;
    }
    else
    {
        //Disables buttons and locks into text box
        textBox3.Text = "Invalid IPv4 address!!";
        textBox3.Select();
        button2.Enabled = false;
        button3.Enabled = false;
    }
}

//Port Validation
private void textBox4_Leave(object sender, EventArgs e)
{
    bool ValidatePort;
    int porttest = 0;
    try
    {
        porttest = Convert.ToInt32(textBox4.Text);
    }
    catch (Exception)
    {
    }

    if (porttest > 1 && porttest < 65535)
    {
        ValidatePort = true;
    }
    else
    {
        ValidatePort = false;
    }

    if (ValidatePort)
    {
        button2.Enabled = true;
        button3.Enabled = true;
    }
    else
    {
        //Disables buttons and locks into text box
        textBox4.Text = "Invalid Port";
        textBox4.Select();
        button2.Enabled = false;
        button3.Enabled = false;
    }
}

Naming

By convention, variables local to a method should be camelCased. You seem to have a mixture of PascalCased and alllowercase, making it hard to see at a glance what a variable is. All lower case has the additional disadvantage of being hard to read.

Your boolean check variables also seem to be named in the form 'VerbNoun'. This is rather confusing because it's usually how methods are named. It sounds like they're supposed to do something. ValidatePort for example sounds like something that validates a port. A name like portValid or perhaps isPortValid more clearly states what the variables are.

Extracting methods

Looking at both of your methods, they have the same structure: Check if something is valid, if it is then change the state of the form one way, if it isn't then change the state of the form a different way. Each of those are basically completely separate pieces of functionality, so I'd suggest separating them out. This would turn textBox3_Leave, for example, into:

private void textBox3_Leave(object sender, EventArgs e)
{
   bool ipValid = ValidateIP(textbox3.Text);
   if(ipValid)
       EnableControls();
    else
       DisableControls();
}

Here the new methods ValidateIP, EnableControls and DisableControls would be private methods containing the bits of code they replace.

This method now immediately states what it is doing: it's validating the text in textbox3as an IP, if it's valid then enable the controls, otherwise disable them. Potentially you could get rid of ipValid and just put that ValidateIP call directly into the if statement, it's up to you what you think reads better. You may also be able to improve on those names a bit (enable which controls, for example).

Repetition

Now look at the second method. You'll see that EnableControls can be used here too. This means that just by making the first method a clearer statement of what it's doing, we've discovered a valuable abstraction, and we no longer have to repeat that enabling controls means enabling button2 and button3.

We can almost use DisableControls too, but there's a slight difference- the messages. So to fix that, DisableControls should take the message as a string parameter:

private void DisableControls(string message);

Integer parsing

It's generally considered bad to use exceptions in normal control flow. That's what you're doing here when you try to check whether the text in textbox4 is a valid integer or not.

An alternative, which you may not have known about, is Int32.TryParse. This method is designed for this exact situation- where you want to check whether a string represents an integer, but don't want to throw an exception if it isn't. This allows you to get rid of that try...catch and clean that bit of code up a bit.

Simplifying if statements

If you ever have an if statement which reads:

if(condition)
{
    value = true;
}
else
{
    value = false;
}

You should simplify this to:

value = condition;

In your case, you can do:

ValidatePort = porttest > 1 && porttest < 65535


Reset files in Git which show as modified but have no changes according to “git diff” This seems to be working but also is quite horrendously slow and seems a little hacky to me.

IFS=$'\n'

for currentFile in $(git status | grep "modified:" | cut -c 14-)
do
    gitDiff=$(git diff "$currentFile")
    gitDiffStr="[$gitDiff]"
    if [ "$gitDiffStr" == "[]" ]
    then
        echo match
        echo git checkout "$currentFile"
        git checkout "$currentFile"
    fi
done

The slowness

The slowness most probably comes from executing multiple git diff commands.
A faster way might be using a programming language with a Git library that would let you run a single git diff command,
and iterate over the entries of the diff to find the empty ones.

The hacky part

This is hacky:

git status | grep "modified:" | cut -c 14-

The output of the git status is not API,
and may also be subject to aliases and user settings.
It's not safe to use.
When parsing the output of Git commands,
look for a --porcelain option to make it safe.

Another hacky part is changing the value of IFS.
It's not a huge problem,
but it's good to minimize the scope of the change,
typically by using it in the form of IFS=... cmd,
which would limit the effect of the change to the execution of the cmd command.

Lastly, some minor style issues:

The $gitDiffStr variable is pointless, you can simply inline it.
The == operator within a [ ... ] is undocumented. Use = instead.

Alternative implementation

Applying the above suggestions, this is less hacky, and probably just as slow:

git status --porcelain -z | grep -z '^ M' | while IFS= read -r -d '' path0; do
    path=${path0:3}
    gitDiff=$(git diff "$path")
    if [ "$gitDiff" = "" ]; then
        echo git checkout "$currentFile"
        git checkout "$currentFile"
    fi
done


Storing data bytes into properties From the related questions here, I've found this and this answers, both of which suggest Replacing Conditional with Polymorphism, are probably what I'm looking for. However, I'm not sure if polymorphism would be a good choice for my particular case. Below are the relevant code snippets (sorry they're incomplete).

public enum Code : byte
{
    A = 0x01,
    B,
    C,

    // there's more

    a - 0x41,
    b,
    c,
    // there's more
}

The class constructor:

Code? code = null;
byte[] data = null;

public ContentHolder(Code code, byte[] data)
{
    this.code = code;
    this.data = data;
}

The switch statement:

int length = data.Length;

switch(code)
{
    case Code.A:
    case Code.E:
    case Code.F:
    case Code.G:
        QR = data[0];
        if (code == Code.F)
            // set another property
        break;
    case Code.B:
        if (length < 13)
            throw new ArgumentException();
        Index = data[0];
        break;
    case Code.C:
        int content_length = data[1];
        if (length < content_length + 30)
            throw new ArgumentException();
        Flag = (ContentFlag)data[0];
        ContentLength = data[1];
        if (Flag & ContentFlag.FlagA == ContentFlag.FlagA)
        {
            Content = new byte[content_length];
            Array.Copy(data, 2, Content, 0, content_length);
        }
        if (Flag & ContentFlag.FlagB == ContentFlag.FlagB)
        {
            // set property
        }
        // 5 more flags
        break;
    case Code.D:
        int genre = data[2];
        int genre_length = 2;
        switch (genre)
        {
            case Genre.TypeA:
                genre_length += 4;
                break;
            case Genre.TypeB:
                genre_length += 8;
                break;
            case Genre.TypeC:
                genre_length += 1;
                break;
            case Genre.TypeD:
                genre_length += 15;
                break;
        }
        if (length != genre_length)
            throw new ArgumentException();
        Array.Copy(data, 0, Target, 0, 2);
        switch (genre)
        {
            case Genre.TypeA:
                GenreID = BitConverter.ToUInt32(data, 2);
                break;
            case Genre.TypeB:
                GenreID = BitConverter.ToUInt64(data, 2);
                break;
            case Genre.TypeC:
                GenreID = data[2];
                break;
            case Genre.TypeD:
                GenreID = ASCIIEncoding.ASCII.GetString(data, 2, 15);
                break;
        }
        break;
default:
    throw new ArgumentException();

Basically, I have a class that takes in a byte array and a code. Based on the code, I am setting properties of the class. There will be more than 20 cases in total, each case may or may not have precondition verifications and may or may not be handled differently, as shown in the snippets. I feel this is already getting pretty hard to read and maintain, so I might end up with 20 implementation classes if I use polymorphism. What would the best way to refactor this?

Update

I guess my main concern is that I may have too many implementation classes if I use one for each case (except for the common ones which is about 10-15% of all cases), not to mention there'll likely be more codes added with other ways of being handled, and it doesn't make sense to not put them in one namespace...or is this not a problem at all?

Any advice is appreciated!

There is an answer in here I hope, and it is a polymorphic perspective. Your description is very reminiscent of a problem where using IEqualityComparer simplified the hell out of things.

Ask yourself if each enum member represents a different class or perhaps groups of enum members represent states for given classes. ... and/or ... Where's the context in such an abstract array? It's hidden in a morass of casees.

Does the length and/or value of certain element(s) determine the "type?" If so then a three step process will break apart the existing code, simplify, and clarify. 1) Evaluate for the type, 2) instantiate via a factory 3) do whatever with the instance.

Create a class that will hold the array (whole, intact) plus appropriate key fields (values extracted from the array). A super-set of key fields so any byte array "type" can be held there. Add a field for the type itself (likely an enum), as distinct from your Code enum.  This class will take an IEqualityComparer object in its constructor.

I had a case where seven distinct "types" were clearly in two groups (per data meaning/use by the users). It was convenient and practical to design only 2 IEqualityComparer classes.

Create "Processor" classes as needed that do stuff with and to these "byte[]-EqualtityComparer" instances individually and in collections.

If you need collections I strongly uge you to create type-specific collections (2 in my case) that by design know how to use the class. In my case I was looking for duplicates.

edit

  Sorry but I couldn't understand how IEqualityComparer come into place here. What do you compare with? Could you elaborate on it? Thank you!

We are lying the foundation for code organization and extensibility. With 20+ "types" this differentiation is also the single responsibility principle in action. This is fundamental functioning that every class/type needs. Now I can identify a plain-old byte[] by it's "type" and it behaves like a unique individual via it's values - as used in Equals, CompareTo, Contains, Sort, Find, etc. w/in the .NET framework.

The entire switch statement will devolve to one line:

ByteArrayClass myBAobject = myFactory.Create( Code.A );

This encapsulates everything that new object can do, now and in the future. I'm assuming it will need Equals() and/or CompareTo()

  I guess my main concern is that I may have too many implementation classes if I use one for each case (except for the common ones which is about 10-15% of all cases

Generic Handling: We can have a single ByteArrayClass collection that can be passed anywhere and used either generally or in type-specific ways.
A general Processing Class. For now: For expediency dump all that code into a ByteArrayClassProcessor class. The code should be organized by "type". This will facilitate refactoring to "type"-specific classes if this processor gets to be too much.
Determing Type: Yeah, the initial grunt work for determining the byte[]'s type must be done. But do the minimum required to do it. From that instantiate a ByteArrayClass object. From then on functionality is type-specific, and most of that switch case comes over from the dark side.

Use the factory pattern.

Validate a "typed" object, not a generic byte[]

I wonder if the byte[] length is type specific, even if it's the same for many, most of the types.

Constantly evaluate code evolution to decide when/if to create new classes

At this point, functionally oriented; "determine type", validation, database interaction, etc.
Create type-specific classes on an as-needed basis

Does not have to be all or nothing.
Use the factory pattern. And in an OMG moment you'll see the potential for this new factory utilizing the "determine type" factory above.
The ByteArrayClass object (output from the "determine type" factory) is wrapped by the new type-specific class.

endEdit


Give me thy name, I'll invoke thee This generic function invokes a property of a given object by name:

  Private Shared Function GetPropertyValueByName(Of TObject, TProperty)(
        ByVal T As TObject,
        ByVal PropertyName As String) As TProperty

        Dim result = GetType(TObject).GetProperties() _
            .Where(
                Function(p) (p.Name = PropertyName) _
                    AndAlso p.CanRead() _
                    AndAlso (p.PropertyType Is GetType(TProperty))
                ).FirstOrDefault()

        If (result IsNot Nothing) Then
            Return CType(result.GetValue(T), TProperty)
        End If

        Return Nothing

    End Function

Can this function be improved in some way? Can it generate some sort of issues I have to be aware of? Can it be improved in terms of readability?

LINQ has two syntaxes to offer. You've used the method syntax, which I find very neat and useful, but for simpler queries I find the query syntax looks much less bulky in VB.NET:

Dim result = (From p In GetType(TObject).GetProperties()
              Where p.Name = PropertyName _
                  AndAlso p.CanRead() _
                  AndAlso p.PropertyType Is GetType(TProperty)
              Select p) _
             .FirstOrDefault()

It removes the inline Function(p) anonymous function declaration, and leaves it up to the compiler to generate it, which in turns frees your code from some of the boilerplate.


Breaking of a sentence (Method signature is given with parameters)

Try to visualize me writing this code at an interview, and please be brutal while judging it.

  Problem:

  Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.  Return all such possible sentences.

  For example, given

s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"]

  A solution is

["cats and dog", "cat sand dog"]

Time complexity: I don't know how to analyze it, \$O(n)\$, since I visit each char of the string for sure, but since I am backtracking, I visit it again constant time.  I don't know, so please explain

Space Complexity: \$O(n)\$

public ArrayList<String> wordBreak(String s, Set<String> dict) {
    ArrayList<String> sentences = new ArrayList<String>();
    wordBreakHelper(s, dict, 0, new StringBuilder(), sentences);
    return sentences;
}
private static void wordBreakHelper(String givenSentence, Set<String> dictionary, int index, StringBuilder path, ArrayList<String> results){
    if(givenSentence.length() == 0){
        results.add(path.toString());
    }
    if(index > givenSentence.length()){
        return;
    }
    for(int i = index; i < givenSentence.length(); i++){
        boolean isSpace = false;
        if(dictionary.contains(givenSentence.substring(0, i+1))){
            if(i+1 == givenSentence.length()){
                path.append(givenSentence.substring(0, i+1));
            }else{
                path.append(givenSentence.substring(0, i+1) +" ");
                isSpace = true;
            }
            wordBreakHelper(givenSentence.substring(i+1), dictionary, 0, path, results);
            if(isSpace == true){
                path.replace(path.length() - givenSentence.substring(0, i+2).length() , path.length(), "");
            }else{
                path.replace(path.length() - givenSentence.substring(0, i+1).length() , path.length(), "");
            }
        }
    }
}

For the time and space complexity, think about how many sentences are possible with:

s = "aaaaaaaaaaa..."
dict = ["a", "aa"]

Any solutation that creates all of these sentences would need to have exponential complexity.

path.append(givenSentence.substring(0, i + 1) + " ");

If you are using a StringBuilder, you should use its append method instead of the '+' operator as it's more efficient.

The index parameter is always 0. This can be removed.

givenSentence.substring(0, i + 1) is used multiple times. You can assign this to a variable and reuse it instead.

if(isSpace == true)

There's no need to compare with true. Just use if(isSpace)

givenSentence.substring(0, i + 2).length()

Calling substring just to get the length of the String is unnessesary. This is the same as i + 2.

The handling of isSpace adds some complexity. There is some code duplication and extra if statements needed. I would try to remove the need for this.

Changing the bounds of the for-loop can remove the need for adding one to i each time it's used.

With these changes, you have something like:

private static void wordBreakHelper(String givenSentence, Set<String> dictionary, StringBuilder path, List<String> results) {
    if(givenSentence.length() == 0) {
        return;
    }

    if(dictionary.contains(givenSentence)) {
        results.add(path.toString() + givenSentence);
    }

    for(int i = 1; i < givenSentence.length(); i++) {
        String nextWord = givenSentence.substring(0, i);
        if(dictionary.contains(nextWord)) {
            path.append(nextWord).append(" ");
            wordBreakHelper(givenSentence.substring(i), dictionary, path, results);
            path.replace(path.length() - nextWord.length() - 1, path.length(), "");
        }
    }
}


How to create associative hashs in Ruby (on Rails) dynamicly I am developing a webapp with Ruby on Rails to expand the features of mite (online time-tracking app) with the help of the offical mite API. Unfortuanaly, the API can't return all projects by a specific customer id. Because of that, i am developing a workaround.

At first, i get all customers and save them in a hash. Then i iterate throug all projects and save each project object to a hash inside the customer hash.

My code looks like this:

def index
  # Mite authentication
  Mite.account = '...'
  Mite.authenticate('...','...')

  # get all customers from Mite
  @customers = Hash.new
  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => Hash.new}
  end

  # get all projects from Mite
  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] = {:project => project}
  end
end

Unfortuanaly, only the last project is saved in the ":projects" hash. But why? Adding customers works with this method too. In general, is this "the ruby way"? I'm very new to it :)

You should save projects in array or something like it, not hash. For example

  Mite::Customer.all.each do |customer|
    @customers[customer.id] = {:name => customer.name, :projects => []} # !!!
  end

  Mite::Project.all.each do |project|
    @customers[project.customer_id][:projects] << project # !!!
  end


Counting numbers that have an even number of digits I solved this problem: given an array/vector of numbers, return how many of them contain an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5

Please review the code:
impl Solution {
    pub fn find_numbers(nums: Vec<i32>) -> i32 {
        let mut count = 0;
        let mut len = 0;

        if nums.len() <= 500 {
            for num in nums {
                let digit: Vec<_> = num
                    .to_string()
                    .chars()
                    .map(|d| d.to_digit(10).unwrap())
                    .collect();

                len = digit.len();
                if num > 100000 {
                    panic!("Too much greater values are in vector");
                }
                if len % 2 == 0 {
                    count += 1;
                }
            }
        }
        count
    }
}

Are there better ways to apply the constraints and solve the problem?

A couple of points. Firstly about the code you have listed.

Are the constraints problems to be enforced or assumptions you can make while writing your solution? It's odd to artificially limit it.

len does not need to be defined outside the loop. It is overwritten on each loop so could be replaced with let len =  inside the loop.

Within the for loop, you are counting the number of digits, then checking the size of num and panicking if it's too high. It's better in general to exit as soon as possible if something's wrong, so in this case check the size before the more expensive process of counting digits.

In your character counting you are converting to characters, then back to digits before counting. If you only care about how many of them there are, you can leave them as characters. This gives num.to_string().chars().collect();

Once you have an iterator, you can use count instead of collecting to a vec and then finding the length. This reduces it further to let len = num.to_string().chars().count()

The outer for loop can also be replaced with an iterator
nums.iter()
        .map(|n| n.to_string().chars().count())
        .filter(|n| n % 2 == 0)
        .count();

This then doesn't need the count variable either.

Secondly, you ask about other ways to solve the problem. Converting between numbers and strings is slow, and keeping things as numbers wherever possible is generally preferable. In this case, the number of digits in a number (in base 10) is log10 of that number rounded up to the next integer. The edge cases are the powers of 10 which need to be 'rounded' to the next number.
The difficulty in writing this in rust is that log10 is only available for floating point types but as your values are bound 1 <= n <= 100_000, you can assume that all values can be mapped exactly to an f32. Numbers being >1 means that you can safely find a log (log isn't defined for negative numbers).
This lets you rewrite your method as something like
impl Solution {
    pub fn find_numbers(nums: Vec<i32>) -> i32 {
        // iterate over the numbers
        nums.iter()
            // for each n, find log10(n), round down and +1
            // this is the number of digits
            .map(|n| (*n as f32).log10().floor() as i32 + 1)
            // discard numbers that don't have an even number of digits
            .filter(|n| n % 2 == 0)
            // count how many are left
            .count()
    }
}

There is no restriction here of the size  or number of numbers. If that is required, an additional check can be made before the iter call.


Fast comparison of molecular structures and deleting duplicates I have a program that reads in two xyz-files (molecular structures) and compares them by an intramolecular distance measure (dRMSD, Fig. 22). A friend told me that my program structure is bad, and as he is a programmer while I am not, I guess he is right. But as he has no time to help me much, I thought maybe some one of you could provide me with helpful answers.

What my program does right now:

read in molecule 1 (p) and molecule 2 (q)
compare them by dRMSD $$\sqrt{\frac{1}{N(N+1)}\sum_{i<j}\left(p_{ij}-q_{ij}\right)^2}$$ with \$N\$ as the total number of atoms and \$p_{ij}\$ and \$q_{ij}\$ as the euclidean distance between atom i and atom j in each molecule
delete the file of molecule 1 if dRMSD is below a certain threshold

#!/usr/bin/env python

import sys
import math
import os
import numpy as np
from scipy import linalg

def ecd(vec1, vec2):
    "euclidean distance"
    a = np.array(vec1)
    b = np.array(vec2)
    return np.linalg.norm(a-b)

def drmsd(p, q):
    "intra-molecular distance measure"
    a = np.array(p)
    b = np.array(q)
    k = len(p)*(len(p)+1.0)
    total = 0.0
    for i in range(len(p)):
        for j in range(i+1,len(p)):
            total += (ecd(a[i],a[j])-ecd(b[i],b[j]))**2
    return np.sqrt(total/k)

nconf = int(sys.argv[1])

for i in range(1,nconf+1):
    for j in range(i+1,nconf+1):
        fname1 = "h" + str(i) + ".xyz"
        xyz = open(fname1)
        n_atoms = int(xyz.readline())
        coord1 = np.zeros(shape=(n_atoms,3))
        title = xyz.readline()

        cnt = 0
        for line in xyz:
            atom,x,y,z = line.split()
            coord1[cnt] = [float(x), float(y), float(z)]
            cnt += 1
        xyz.close()

        fname2 = "h" + str(j) + ".xyz"
        xyz = open(fname2)
        n_atoms = int(xyz.readline())
        coord2 = np.zeros(shape=(n_atoms,3))
        title = xyz.readline()

        cnt = 0
        for line in xyz:
            atom,x,y,z = line.split()
            coord2[cnt] = [float(x), float(y), float(z)]
            cnt += 1
        xyz.close()

        dist = drmsd(coord1,coord2)
        if dist < 0.0001:
            print i, j, dist, " ... ", fname1, "deleted"
            #os.remove(fname1)
            break

I probably get what your friend meant when they said that your code wasn't particularly well-structured: your program has a main double for loop and ought to be broken into more small functions with names that could be understood at first glance (at least for somebody fluent in the application domain). Putting that aside, there are many small things that could be improved:

Iteration over numpy arrays is slow. While numpy arrays can help to write much faster code than with regular Python lists, iterating over them is slower than iterating over a regular Python list. The trick to numpy arrays is to use functions designed for them when possible, time, convert them to Python lists when you really need to iterate over them, time again, read the documentation to find the most useful functions from numpy and scipy, then time again and in the end you will know which solution is the fastest. Agreed, that's not the nicest thing in the world to do.

I didn't time your code, but I guess that it would be more performant if you used regular Python lists while you read files, still use Python lists in drmsd since you only iterate over the arrays, but use numpy arrays in ecd since you have to use np.linalg.norm.
Instead of manually calling close on file instances, use with instead:

with open('some_file') as f:
    # do things with f
# Here, f is automagically closed

The file will be closed when you leave the scope of the with. That ensures that your file is always closed, even if an exception is thrown while you are doing things with it. It prevents resource leaks without having to use cumbersome try/catch/finally clauses.
Instead of putting your main code directly in the file, try to do this:

if __name__ == '__main__':
    # Here your main code

It will ensure that your main is only called if the file containing it is the one launched by the Python interpreter. That, you can reuse its functions from other modules without risking to launch the main code when you don't want to. This feature is generally used to provide example code in modules.
You seem to be using Python 2.7. If this is the case, then you can turn your range into xrange. While range produces a full list, xrange only produces a lightweight generator object that will produce a return a new integer at every iteration. It is much more memory efficient than using range for the purpose of iterating.


Find optimum teams given calendar availabilities I'm designing an algorithm that creates optimum teams based on everyone's availabilities (maximizes the amount of shared availability). To this end, I've made a function that takes in a dictionary of availabilities mapping person to an array of their availabilities throughout the week at every 15 minute point (e.g. [True, True, False,...,False]) and desired team size and outputs final teams. Here's my working code:
import numpy as np
from itertools import combinations, chain
import operator
from functools import reduce
from tqdm import tqdm
import operator
def ncr(n, r):
    """N Choose R combination"""
    r = min(r, n-r)
    numer = reduce(operator.mul, range(n, n-r, -1), 1)
    denom = reduce(operator.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

NUM_PEOPLE = 100
TEAM_SIZE = 5
time_slots = 24*4*7

# random availabilities
availabilities = np.random.randint(2, size=(NUM_PEOPLE, time_slots), dtype="bool")
availabilities_dict = {}
for i, availability in enumerate(availabilities):
    availabilities_dict[i] = availability

def make_teams(availabilities_dict, team_size):
    """
    availabilities_dict form: {player: [0,0,0,...,1], player2: [0,0,0,0,1...,0]}
    """

    sums = []
    comb = combinations(availabilities_dict, TEAM_SIZE)
    for i in tqdm(list(comb)):
        sum_of_array = np.logical_and.reduce((np.array(availabilities[i,:]))).sum()
        sums.append((i, sum_of_array))
    sums.sort(key=operator.itemgetter(1))
    sums.reverse()

    assigned = []
    teams = []
    i = 0
    while (len(assigned) < NUM_PEOPLE):
        considering = list(sums[i][0])
        none_assigned = True
        for person in considering:
            if person in assigned:
                none_assigned = False
        if none_assigned:
            teams.append((considering, sums[i][1]))
            for person in considering:
                assigned.append(person)
        i += 1
    return teams
teams = make_teams(availabilities_dict, TEAM_SIZE)

Example output consists of a list of tuples (team, total blocks intersecting):
[([15, 18, 42, 70, 94], 36),
 ([14, 30, 63, 80, 97], 36),
 ([1, 12, 40, 64, 88], 36),
 ([22, 48, 62, 72, 87], 34),
 ([25, 29, 35, 53, 85], 32),
 ([26, 31, 49, 60, 78], 31),
 ([13, 44, 79, 93, 96], 29),
 ([32, 59, 67, 71, 82], 28),
 ([24, 39, 41, 50, 91], 28),
 ([9, 28, 55, 92, 95], 28),
 ([5, 8, 11, 19, 86], 28),
 ([4, 33, 56, 76, 83], 27),
 ([2, 10, 16, 17, 69], 27),
 ([21, 43, 73, 75, 81], 24),
 ([7, 20, 57, 89, 99], 24),
 ([23, 36, 37, 58, 66], 22),
 ([52, 61, 65, 68, 84], 20),
 ([3, 27, 34, 47, 74], 18),
 ([6, 38, 51, 54, 77], 16),
 ([0, 45, 46, 90, 98], 9)]

But this took over 10 mins to run on my state of the art computer! Is there a way to still find an optimum team match without running through all of the possible combinations? How can I make it faster? Thank you!

Review
Imports
import operator is being done twice, which is unnecessary.
from itertools import combinations, chain: chain is never used, and can be removed.
N Choose R
As of Python 3.8, the "n choose r" function is built-in and can simply be imported:
from math import comb.
The function is never used, so may be deleted.
Constants
time_slots = 24*4*7
That is ... the number of hours in a 4-week month?  No?  Perhaps you should name some of those numbers, and use UPPER_CASE to indicate the result is a constant:
SLOTS_PER_HR = 4
HRS_PER_DAY = 24
DAYS_PER_WEEK = 7
TIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK

Code Organization
You've got imports, function definition, constants, code, another function definition, more code.  Organize your code, please!

imports
constants
function definitions
code (ideally in a main-guard)

Use blank lines to separate sections.  Your first function immediately follows the imports without a blank line, which makes it harder to understand.  3 blank lines before the second function definition seems excessive, and no blank line after the last function makes it harder to see that the code which follows is not part of the function.
Order import ... statements before from ... import ... statements.
Use Function Parameters
def make_teams(availabilities_dict, team_size):
If I call make_teams(availabilities, 10), I'd expect the function to make teams of 10, but it will actually make teams of size TEAM_SIZE (a global constant) instead!  The team_size parameter is never used.
Similarly, if I pass in a dictionary of 200 people, it will stop making teams when NUM_PEOPLE is reached.  len(availabilities_dict) would be more intuitive.
Use a for loop instead of a manual loop counter
    i = 0
    while len(assigned) < NUM_PEOPLE:
        considering = list(sums[i][0])
        ...
        i += 1

This loop can be changed to something like the following, which has eliminated the i loop variable.  We've even moved the test for number of people assigned from every loop to only being done when the list of assigned people changes.
    for considering, team_sum in sums:
        ...
        if none_assigned:
            ...
            if not len(assigned) < NUM_PEOPLE:
                break

Large functions
make_teams() is a large function, 22 lines long, not counting blank lines or docstrings.  No comment is in sight.  Functions should be decomposed into smaller functions, which do simpler tasks, instead of a single monolithic function doing everything.  Smaller functions are easier to understand.
Type Hints
Adding type-hints can go a long way towards improving readability of the code.
Optimizations
NumPy -vs- Bitarray
numpy is a powerful, flexible, and fast library for manipulating vast quantities of data in multidimensional arrays.
Most of the power of numpy is completely unused by this code.  The part that is being done by numpy could be replaced with bitarray, a library that is optimized exclusively for dealing with arrays of bits in a fast, efficient, memory conscious way.
I haven't run timed trials of numpy using 1-dimensional bit arrays against the bitarray library, so I'm offering this as something to look into, rather than explicitly stating one is better than the other.
Lists -vs- Sets
You are maintaining a list of all assigned players, and testing that no player in a considering list is in the assigned list.  The problem is person in assigned is an \$O(N)\$ operation.  If you maintained as set of assigned players, then player in assigned becomes an \$O(1)\$ operation, significantly faster.
Moreover, with sets you can test all the players in considering at once.  If assigned.isdisjoint(considering) is true, there is no overlap; no player in considering has been assigned.
Suggested code
from bitarray import bitarray
from bitarray.util import urandom
from itertools import combinations

# Types for type-hints (using Python3.9 style)
Schedules = dict[int, bitarray]
Team = tuple[int]
Teams = list[tuple[Team, int]]

# Constants
SLOTS_PER_HR = 4
HRS_PER_DAY = 24
DAYS_PER_WEEK = 7
TIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK

def make_teams(availability: Schedules, team_size: int) -> Teams:
    """
    A good docstring here
    """

    # Inner function for determining the common availability of a team
    def common_availability(team: tuple[int]) -> int:
        avail = bitarray(TIME_SLOTS)
        avail.setall(True)
        for player in team:
            avail &= availability[player]
        return avail.count()

    # team combinations are created and sorted in one step.
    team_combinations = sorted(combinations(availability, team_size),
                               key=common_availability, reverse=True)

    # Collect teams, while maintaining a set of assigned players
    assigned = set()
    teams = []

    for team in team_combinations:
        if assigned.isdisjoint(team):
            # I didn't store availability scores, so recalculate here if really needed.
            teams.append((team, common_availability(team)))
            assigned |= set(team)

    return teams

# Create random schedules
def test_data(num_people: int, time_slots: int) -> Schedules:
    return {i: urandom(time_slots) for i in range(num_people)}

if __name__ == '__main__':
    from time import perf_timer

    for num_people in range(TEAM_SIZE, 101, TEAM_SIZE):
        availability = test_data(num_people, TIME_SLOTS)
        start = perf_counter()
        teams = make_teams(availability, TEAM_SIZE)
        secs = perf_counter() - start
        mins = int(secs / 60)
        secs -= mins * 60

        print(f"{num_people:3d} {mins:02d}:{secs:06.3f}")

My 5 year old laptop finds teams of 5 from 100 people in 02:08.887 ... well under the 10 minutes you're experiencing on your "state of the art computer".  That isn't a really good, qualitative performance comparison, so you'll have to profile it to see how much of an improvement you see.


Mixing arbitrary integers and enum values I'm writing a text adventure editor that identifies various StoryEntity instances by name, among other means, but the name is the primary way for the user or player to refer to them. The name doesn't have to be unique. For example, there may by many instances of "North" which each refer to a different StoryEntity depending on where the player is, or the context of which container you're referring to. Sometimes I know the name will be ambiguous, but I want to give preference to names of entities that are near the player. Other times, like when the user types Edit North, they may be dealing with a design-mode copy of the data where the player is always in its designed starting location, but I have another way of identifying the "current location". Still other times, I don't want to waste time sorting the results at all because I will handle all of them equally. So I updated the function that retrieves a StoryEntity by name to include a parameter indicating whether and how to sort the results by relevance:

public IEnumerable<StoryEntity> EntitiesNamed(string name,
   RelevantContainer relevantContainer)
{
   if (relevantContainer == RelevantContainer.PlayerAndContainer)
      return byName[name.ToLower()].OrderBy((e) => (e.Container == PLAYER_ENTITYID)
         ? 1 : ((e.Container == Player.Container) ? 2 : 3));
   else if (relevantContainer > 0)
      return byName[name.ToLower()].OrderBy((e) => ((e.Container == relevantContainer)
         ? 2 : 3));
   else
      return byName[name.ToLower()];
}

Now my question is how can I best define RelevantContainer so that it allows pre-defined values as well as arbitrary int (container ID) values? I can imagine implementing it as an enum or a struct:

Struct

public struct RelevantContainer
{
   private int value;
   public static implicit operator RelevantContainer(int containerId)
   {
      return new RelevantContainer() { value = containerId };
   }
   public static implicit operator Int32(RelevantContainer relevantContainer)
   {
      return relevantContainer.value;
   }
   public readonly static RelevantContainer None = 0;
   public readonly static RelevantContainer PlayerAndContainer = -1;
}

Enum

public enum RelevantContainer
{
   None = 0,
   PlayerAndContainer = -1
}

Of course if I implement it as an enum, then I will have to do more casting to persuade the compiler to allow integer values and enum values to be interchanged, but the code for RelevantContainer itself is much simpler. Is there a clear choice for which approach to use here? If it matters, this is a Xamarin Android project.

Unless I am mistaken you are dealing with a int32, string key value pair, why not use a simple struct consisting of an int and a string?

although as this is CodeReview I have to say, your use of ternary operators nested in linq statements with more terniaries is damn near illegible.

Don't forget, code you wrote 6 months ago is indistinguishable from strangers code.

If you saw this code and had never seen it before you would think it is clear and makes sense?

to be polite that EntitiesNamed method is mostly gibberish.

You are trying to define relevance in your story entities, I get it, but a hard coded nest of grouping ids is scary to read and very easy to mess up.

you are basically talking about a rule engine, Given a name and a gamestate, find the right StoryEntities.

A level down from that is, if the current gamestate and name match a certain condition, filter the returned Entities.

then you are, based on conditions grouping those entities by relevance.

you method is doing a search, a filtering and a conditional grouping, these are different tasks and need to at least be method separate, certainly not be all on one or two lines.

what if you decide to swap return order?

Remember, great code looks like well written prose, would something like

var storyentities = GetEntitiesByName(entityName);
var orderedentities = OrderByContainer(storyentities,container);

not make more sense?

could the OrderByContainer method not even be a method on a ContainerOrderer interface of some kind defining the rules for deciding relevancy? would that not separate your concerns, make testing easier and over all make it clearer what each piece of your code is doing?


Deleting a section of a website using Ajax I am currently writing a decent amount of ajax to help me delete a section of a website.

It's already becoming a pretty big piece of code, I wondered if it were possible to compact a section of my code.

$('.trg-finished').on('click', function() {
    if(confirm('Are you sure?')) {
        var that = $(this);
        var catid = that.data("id");

        $.ajax({
            type: "POST",
            url: "./close-cat.php",
            data: { catID: catid }
        })
        .done(function(data) {
            if(data == 1) {
                that
                .css("background-color", "#27AE60")
                .css("color", "#FFF")
                .html('Success');
            } else {
                that
                .css("background-color", "#C0392B")
                .css("color", "#FFF")
                .html('Failure');
            };

            window.setTimeout(function() {
                that
                .css("background-color", "")
                .css("color", "")
                .html('Finished');
            }, 5000);
        })
        .fail(function(data) {
            that
            .css("background-color", "#C0392B")
            .css("color", "#FFF")
            .html('Failure');

            window.setTimeout(function() {
                that
                .css("background-color", "")
                .css("color", "")
                .html('Finished');
            }, 5000);
        });
    };
});

Is it possible to compact this code, or is this as small as it can get?

This is very weird. If I read the code without this line, I wouldn't have a clue what that might be:

var that = $(this); // this is very weird
// I suggest the following name, (or thisElement, or something like that)
var $elem = $(this); // I use the $ in the name to indicate 'jQuery Object'

Saving the object is a good thing, saving multiple DOM look-ups, just be obvious about the name.

Instead of getting the data-id, you could use this to get the id of your element, which you can access it directly via JS, which is a lot faster:

var catid = that.data("id"); // instead of this:
var catid = this.id; // Just use id:

You chain your css methods, you can use them more effectively by using the multiple input variant:

that
    .css({backgroundColor: "#27AE60", color: "#FFF"}) // multiple in one go

Even better, do this via classes. You should not style with javascript, apart from tiny exceptions.

if(data == 1) {
    that.addClass("HighlightGood").html('Success');
} else {
    that.addClass("HighlightBad").html('Failure');
};

window.setTimeout(function() {
    that.removeClass("HighlightGood HighlightBad").html('Finished');
}, 5000);

This way you can style via css, as you should. This also allows simple css animation.

Instead of calling the timeout, use a function. DRY (=don't repeat yourself) programming is often more maintainable (IMO):

function setAsFinished( $elem, timeout ){
    timeoutLength = timeout || 5000; // Take the given input (if set), else default value 5sec
    window.setTimeout(function() {
        $elem.removeClass("HighlightGood HighlightBad").html('Finished');
    }, timeoutLength);
}

All suggestions combined:

function setAsFinished( $elem, timeout ){
    timeoutLength = timeout || 5000; // Take the given input (if set), else default value 5sec
    window.setTimeout(function() {
        $elem.removeClass("HighlightGood HighlightBad").html('Finished');
    }, timeoutLength);
}

$('.trg-finished').on('click', function() {
    if( confirm('Are you sure?') ){
        var $thisElem = $(this);
        var catid = this.id;

        $.ajax({
            type: "POST",
            url: "./close-cat.php",
            data: { catID: catid }
        })
        .done(function(data) {
            if(data == 1) {
                $thisElem.addClass("HighlightGood").html('Success');
            } else {
                $thisElem.addClass("HighlightBad").html('Failure').html('Failure');
            };
            setAsFinished( $thisElem );
        })
        .fail(function(data) {
            $thisElem.addClass("HighlightBad").html('Failure');
            setAsFinished( $thisElem );
        });
    };
});