Left join query of user profiles I have the following left join LINQ query that is returning the results that I expect, but it does not "feel" right. I need ALL records from the UserProfile table.

Then the LastWinnerDate is a single record from the winner table (possible multiple records) indicating the DateTime the last record was entered in that table for the user.

WinnerCount is the number of records for the user in the winner table (possible multiple records).
Video1 is basically a bool indicating there is, or is not a record for the user in the winner table matching on a third table Objective (should be 1 or 0 rows).
Quiz1 is same as Video1 matching another record from Objective Table (should be 1 or 0 rows).
Video and Quiz is repeated 12 times because they're used for a report, which is to be displayed to a user listing all user records and indicate if they have met the objectives.

var objectiveIds = new List<int>();
objectiveIds.AddRange(GetObjectiveIds(objectiveName, false));

var q =
    from up in MetaData.UserProfile
    select new RankingDTO
    {
        UserId = up.UserID,
        FirstName = up.FirstName,
        LastName = up.LastName,
        LastWinnerDate = (
            from winner in MetaData.Winner
            where objectiveIds.Contains(winner.ObjectiveID)
            where winner.Active
            where winner.UserID == up.UserID
            orderby winner.CreatedOn descending
            select winner.CreatedOn).First(),
        WinnerCount = (
            from winner in MetaData.Winner
            where objectiveIds.Contains(winner.ObjectiveID)
            where winner.Active
            where winner.UserID == up.UserID
            orderby winner.CreatedOn descending
            select winner).Count(),
        Video1 = (
            from winner in MetaData.Winner
            join o in MetaData.Objective on winner.ObjectiveID equals o.ObjectiveID
            where o.ObjectiveNm == Constants.Promotions.SecVideo1
            where winner.Active
            where winner.UserID == up.UserID
            select winner).Count(),
        Quiz1 = (
            from winner2 in MetaData.Winner
            join o2 in MetaData.Objective on winner2.ObjectiveID equals o2.ObjectiveID
            where o2.ObjectiveNm == Constants.Promotions.SecQuiz1
            where winner2.Active
            where winner2.UserID == up.UserID
            select winner2).Count(),
    };

It doesn't feel right, because you have a lot of repetitive code.

Notice how each property selector's where statement contains

        where objectiveIds.Contains(winner.ObjectiveID)
        where winner.Active
        where winner.UserID == up.UserID

That means you can refactor this where condition to a join in the containing query.

Also, you specify an order by clause, when you are only using the values to get the Count().  This does nothing but take up space and time.

I think this query might be more along the line of what you are trying to achieve:

        var rankingDtos =
                    from user in MetaData.UserProfile
                    let userWinners = from winner in MetaData.Winner
                                      let objectives = from objective in MetaData.Objective
                                                       where winner.ObjectiveID == objective.ObjectiveID
                                                       select objective
                                      where winner.UserID == user.UserID && winner.Active
                                      orderby winner.CreatedOn descending
                                      select new
                                                 {
                                                     Winner = winner,
                                                     Objectives = objectives
                                                 }
                    select new RankingDTO
                               {
                                   UserId = user.UserID,
                                   FirstName = user.FirstName,
                                   LastName = user.LastName,
                                   LastWinnerDate = userWinners.First().Winner.CreatedOn,
                                   WinnerCount = userWinners.Count(x => objectiveIds.Contains(x.Winner.ObjectiveID)),
                                   Video1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecVideo1)),
                                   Quiz1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecQuiz1))
                               };


T-SQL Secure String Comparison The previous version of my function was scalar-valued and employed a WHILE loop to do the comparison, this is SLOW. This new version is tabled-valued and uses a typical tally table in place of the loop. The result is an implementation that is MUCH more efficient while being slightly easier to comprenhend (IMHO).

There is a slight drawback to the new version however: it fails on strings longer than 2GB in size.

create function api.ConstantTimeIsEqual (
    @x varbinary(max) = 0x00
  , @y varbinary(max) = 0x00
)
/*
    What? Compares two variable length binary strings byte by byte in constant time.

    When? Cryptography, Gaming.

    Why? Given the strings 0x1234 and 0x1213: a simple equality comparison will stop processing after
         it hits the first mismatch at byte position 3. An opponent who only knows @x can exploit this
         feature to guess @y by trying thousands of comparisons and gathering statistics on how long
         each one took.

         In other words, assuming that it takes 100 milliseconds to compare a 16 byte string, an
         opponent can rely on the fact that strings that take more than 50 milliseconds to process are
         better guesses than ones that take less than 50 milliseconds. Thus, if a comparison takes 50
         milliseconds then @x is a 50% match of @y (from byte positions 1 through 8).

    How? 1. cache the length of @x into [@xLength] (n)
         2. cache a range of integers from 1 to XLength.n into [Iterator] (n)
         3. bail early if the lengths of @x and @y are not equal
         4. XOR nth byte of @x with nth byte of @y
         5. SUM all XOR results, cast result to bit (0 will stay 0, any other number will become 1)
         6. flip the final bit to retain "IsEqual" semantics
 */
returns table
with schemabinding as
return (
    select Cast(Sum(Substring(@x, [Iterator].n, 1) ^ Cast(Substring(@y, [Iterator].n, 1) as tinyint) /* 4 */) as bit /* 5 */) ^ 1 /* 6 */ as b
    from (values(DataLength(@x))) as [@xLength] (n) /* 1 */
    cross apply math.RangeInt(1, [@xLength].n) as [Iterator] /* 2 */
    where Abs([@xLength].n - DataLength(@y)) = 0 /* 3 */
);

As discussed in the comments, this isn't cryptographically secure. The most obvious reason is that the optimizer may choose to do any number of things. The most likely to be concerning are a change in order of operations, or a change in join methodology. If math.RangeInt does any kind of table access (I assume this gives you a numbers table equivalent) then table access type could affect it as well.

Additionally, the bail-early for inequal length exposes information if this assumption isn't met (from comments):

  [I] wrote the code under an assumption that doesn't hold in general: that the strings being compared are hashes and thus the length is public knowledge

Ignoring comments regarding cryptographic security, I think the implementation is straightforward and makes sense. To try and address the cryptography I have a few ideas, but I am not an expert and do not endorse rolling your own security and cryptography algorithms/libraries (or using my suggestions, ever, in production).

(click here to see the image on imgur, otherwise click the image to read the original informative and entertaining comic).

Now that we have that out of the way, I think to even come close to accomplishing this, we would need to do the following:

Stop using a table valued function - we're going to need several hints to ensure that this performs consistently, which we can't add to a TVF and auditing all uses of this would be too difficult. In particular, OPTION( FORCE ORDER, RECOMPILE, MAXDOP 1, OPTIMIZE FOR @x = 0x00, @y = 0x00 ) will be necessary.
Instead of CROSS APPLY math.RangeInt, I think you'll need to join to a materialized numbers table (see below)
You're going to have to remove the length check, and pad the two values to an even 8000 (this is tedious but not hard, and I think should be doable in constant time)

I picked those hints because we want to ensure that it always joins in the order we specify, and doesn't get clever. We want to prohibit parallelism as well so it behaves consistently. Optimizing for those constant values prevents it from getting smart with parameter sniffing. We may not need to recompile; in my gut I think we want it, but I don't have a great reason for this. We may want to set a min/max grant percentage to be the same, so we get consistent behavior based on memory grant. It might also be valuable to use the USE PLAN hint, which lets you hardcode the plan to use. This might be the best way to get a consistent execution.

We're also going to have to add join and table access hints; assuming that dbo.Numbers exists with a clustered index on the first (and only) column, we might be able to do this:

FULL OUTER LOOP JOIN dbo.Numbers WITH ( INDEX(0), FORCESCAN )
  ON Numbers.Number = [@xLength].n

This should run in the same amount of time no matter the length of the string, and the query will always use the same join and table access pattern.

Overall, I think this is a lot of reasons why implementing something cryptographically secure in SQL is a bad idea; I would guess there are a lot of things I'm missing that still prevent this from being "safe".


Optimization of multiple arrays for filtering My app will be running on an iPad with A7. I pass in 3 JSON arrays and right now do some simple filtering, in the future the operation will be much more complicated.  I realize the if statement is slowing down the process, but how can I avoid it?  Is there a way to have this loop on one CPU and run the GUI on the other CPU (assign affinity)?

class func filterPhenotypeByPvalues(
    phenotypeJSON:[String],
    SNPJSON:[String],
    dataJSON:[Float],
    limit:Float) -> ([Float],[String],[String])
  {
    let dbg:Bool = true
    var PvalueFiltered:[Float] = []
    var PhenotypeFiltered:[String] = []
    var SNPFiltered:[String] = []
    //initialize arrays with value
    //[Float](count: data.count, repeatedValue: 0.0)

    var i:Int = 0

    let startTime = CFAbsoluteTimeGetCurrent()

    for (i = 0; i < dataJSON.count; i++) {
      if dataJSON[i] <= limit {
        PvalueFiltered.append(-log10(dataJSON[i]))
        PhenotypeFiltered.append(phenotypeJSON[i])
        SNPFiltered.append(SNPJSON[i])
      }
    }

    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    if(dbg){println("Time elapsed filterPhenotypeByPvalues: \(timeElapsed) s")}

    return (PvalueFiltered,PhenotypeFiltered,SNPFiltered)
  }

A very small sample of the JSON data file:

{
    "data": [
        ["rs6855911","Negative control - flare length",0.0000000002],
        ["rs6855911","BMD of intertrochanter region - gm/cm sq",0.0000000007],
        ["rs1501908","BMD of intertrochanter region - gm/cm sq",0.000000001]
    ]
}

Screenshot of timing profile:

There may exist a way to make this particular loop run faster.  In fact, I'm sure there probably is... however, it's kind of a futile effort.

There's a lot of time also being wasted elsewhere where we're creating these original three arrays we're passing in here.  We need to take a far more OOP approach to this problem.

I don't know what this code actually represents, but for now, I'm going to use "Phenotype" and assume that's an accurate noun to give to the object that the JSON data is trying to describe.

The way the JSON data is structured suggests that the these three data points are obviously tied to each other.  We don't need to create three separate arrays and somehow rely on a common index among them to remember what goes with what.  Let's make a container to hold all of this information:

struct Phenotype {
    var phenotype: String
    var SNP: String
    var data: String
}

(The struct name and its variable names are probably far from optimal.)

Now, when we parse out the JSON data, we create a single array of instances of our Phenotype struct rather than three arrays of the different types.

Now we don't even need to write the method in your question, because we can do it with the built-in filter method:

let limit = someValue
let dataFromJSON = someFuncCreatingArrayOfPhenotypesFromJSONData(data)

let filteredData = dataFromJSON.filter { $0.data <= limit }

And filteredData represents exactly the data your method was trying to extract.


Generate all permutations in Clojure Given a set, generate all permutations:

(permutations #{1 4 5}) => ((5 4 1) (4 5 1) (5 1 4) (1 5 4) (4 1 5) (1 4 5))

Here's what I cobbled together:

(defn perm-r [allPerms currentPerm input i]
  (cond
    (empty? input) (conj allPerms currentPerm)
    (< i 0) allPerms
    :else (perm-r
            (perm-r
              allPerms
              (conj currentPerm (nth input i))
              (remove (fn [x] (= x (nth input i))) input)
              (dec
                (count
                  (remove
                    (fn [x] (= x (nth input i)))
                    input))))
            currentPerm
            input
            (dec i))))

(defn permutations [a-set]
  (perm-r `() `() (seq a-set) (dec (count a-set))))

I thought my solution was awful, so I went to look for other solutions and found this:

(defn rotations [a-seq]
  (distinct (map concat (tails a-seq) (inits a-seq))))

(defn permutations [a-set]
  (if (empty? a-set)
    (list ())
    (apply concat (map (fn [x] (map cons (repeat (first x))
                                         (permutations (rest x))))
                  (rotations a-set)))))

It looks so elegant! I'm not used to functional programming, so I find the execution flow immensely difficult to follow. In particular, I don't understand what's being concatenated. Is the result of the first map call (which represents what exactly?) to every rotation of a-set?

Any tips on improving my thought process so that I could come up with a solution like that on my own? I'm used to programming imperatively and I don't find functions like map or apply intuitive. Is there a way to make this function more readable or improve it further in other ways?

Let's clean the code up a bit.

Function tails gives us all the possible ending sub-sequences. For example ...

(tails (range 3)) ; ((0 1 2) (1 2) (2) ())

And inits gives us all the initial sub-sequences. For example ...

(inits (range 3)) ; (() (0) (0 1) (0 1 2))

To get the rotations, we marry the init with the corresponding tail,using concat. If we just

(defn rotations [a-seq]
  (map concat (tails a-seq) (inits a-seq)))

`
... then we get the original sequence at both ends:

(rotations (range 5)) ; ((0 1 2 3 4) (1 2 3 4 0) (2 3 4 0 1) (3 4 0 1 2) (4 0 1 2 3) (0 1 2 3 4))

The given code uses distinct to get rid of the duplicate. It's faster and simpler to use rest:

(defn rotations [a-seq]
  (rest (map concat (tails a-seq) (inits a-seq))))

Now

(rotations (range 5)) ; ((1 2 3 4 0) (2 3 4 0 1) (3 4 0 1 2) (4 0 1 2 3) (0 1 2 3 4))

And we're ready to generate all the permutations. We can rewrite the given code as follows:

(defn permutations [a-set]
  (if (empty? a-set)
    (list ())
    (mapcat
     (fn [[x & xs]] (map #(cons x %) (permutations xs)))
     (rotations a-set))))

(mapcat f coll)is an abbreviation for (apply concat (map f coll)).
(fn [[x & xs]] ... ) is a destructuring form that sets x to the
first and xs to the rest of its sequence argument.
#(cons x %) is an abbreviation for (fn [y] (cons x y)), a
function that puts x on the front of its sequence argument.

For every rotation of the given set, the permutations function glues its first element onto each permutation of the rest of the elements, and then concatenates all these collections together. For example ...

(permutations (range 3))
; ((1 0 2) (1 2 0) (2 1 0) (2 0 1) (0 2 1) (0 1 2))

That's it.

The given inits ...

(defn inits [a-seq]
  (reverse (map reverse (tails (reverse a-seq)))))

... is somewhat overworked, on account of all the reverses. A neater way to get the rotations is

(defn rotations [a-seq]
  (let [a-vec (vec a-seq)]
    (for [i (range (count a-vec))]
      (concat (subvec a-vec i) (subvec a-vec 0 i)))))


Snakes and ladders random world builder I wrote a random world generator for the classic Snakes and Ladders board game.

Snakes and Ladders is a dice game played over a grid, usually 10x10. You win by reaching the last square first. The board has ladders and snakes that connect specific squares. Land at the base of a ladder and you climb to the ladder's head (good). Land on the head of a snake and you slide down to the snake's tail (bad).

Snakes and ladders are key value pairs; the key represents the start point, and the value represents the end point. Both are identical except that a snake's start point must be greater than its end point, while the opposite is true for a ladder.

World rules:

A snake's head can't be on the last square otherwise you can't win the game.
A ladder's base can't be on the last square since there's no where to go.
A square can not contain the base of a ladder and the head of a snake. You either slide, or climb.
Players start off the board.

A square can technically contain the tail of a snake and the base of a ladder, or head of the snake and head of a ladder. But this could have weird side effects (presumably why I've not seen a board with those characteristics): You slide down a snake only to reach the base of a ladder that takes you to the winning square; or you climb up a ladder only to reach the head of a snake that drags you down. While not fatal, such side effects muddle the role definition of ladders and snakes; in that, ladders are no longer necessarily good, and neither are snakes necessarily bad.

Example World

# snakes
{97=>62, 35=>21, 80=>67, 38=>12, 64=>6, 79=>20, 26=>11, 89=>33, 22=>21, 45=>25}
# Ladders
{10=>74, 77=>88, 5=>68, 24=>93, 68=>90, 73=>84, 76=>85, 50=>53, 78=>85, 12=>73}

Builder

  class World
    attr_reader :size, :ladders, :snakes

    def initialize(size, ladders = 10, snakes = 10)
      @size = size
      @snakes = place_snakes(snakes)
      @ladders = place_ladders(ladders)
    end

    def place_snakes(count)
      count.times.each_with_object({}) do |_, hash|
        start_point = rand(snake_habitable_range)
        end_point = rand(snake_habitable_range.begin..(start_point - 1))
        hash[start_point] = end_point
      end
    end

    def place_ladders(count)
      count.times.each_with_object({}) do |_, hash|
        begin
          start_point = rand(ladder_habitable_range)
        end while snakes.keys.include?(start_point)

        begin
          end_point = rand((start_point + 1)..ladder_habitable_range.end)
        end while snakes.keys.include?(end_point)

        hash[start_point] = end_point
      end
    end

  private

    def snake_habitable_range
      2..(size - 1)
    end

    def ladder_habitable_range
      1..(size - 1)
    end
  end

I'm going to be bold and review my own code having spent the last hour refactoring it.

The original implementation had bugs. Sometimes less than 10 ladders were placed. This is because the algorithm did not check to see if there was a ladder already present at the current insertion point.

# Tough luck if start_point is 10 and there's already a ladder there
begin
  start_point = rand(ladder_habitable_range)
end while snakes.keys.include?(start_point)

The best way to ensure a bullet proof implementation is to avoid having a square contain more than one object. For example, there's an edge case where a square can contain a ladder's head and a tail, causing you to progress even further.

To do that, the placement should be delegated to a method that checks if the square is occupied. This requires tweaking the initialize method, but it's worth it:

  def place_point(range = habitable_range)
    begin
      point = rand(range)
    end while occupied?(point)
  end

  def occupied?(number)
    [snakes.keys, snakes.values, ladders.keys, ladders.values].flatten.include?(number)
  end

Doing so means the placement methods for ladders and snakes only have to worry about working out the range and populating their respective hashes, which are the only two differences between them. This reduces duplication.

  def place_snakes(count)
    count.times do
      start_point = place_point
      end_point_range = habitable_range.begin..(start_point - 1)

      snakes[start_point] = place_point(end_point_range)
    end
  end

Finally The habitable range for ladders and snakes is the same, so this can be replaced with a single range 1..(size - 1):

def snake_habitable_range
  2..(size - 1)
end

def ladder_habitable_range
  1..(size - 1)
end

Behold! My new implementation.

class World
  attr_reader :size, :snakes, :ladders

  def initialize(size, snakes = 10, ladders = 10)
    @size = size
    @snakes, @ladders = {}, {}
    place_snakes(snakes)
    place_ladders(ladders)
  end

  def place_snakes(count)
    count.times do
      start_point = place_point
      end_point_range = habitable_range.begin..(start_point - 1)

      snakes[start_point] = place_point(end_point_range)
    end
  end

  def place_ladders(count)
    count.times do
      start_point = place_point
      end_point_range = (start_point + 1)..habitable_range.end

      ladders[start_point] = place_point(end_point_range)
    end
  end

private

  def place_point(range = habitable_range)
    begin
      point = rand(range)
    end while occupied?(point)
  end

  def occupied?(number)
    [snakes.keys, snakes.values, ladders.keys, ladders.values].flatten.include?(number)
  end

  def habitable_range
    1..(size - 1)
  end
end


Generating and re-using unique, sequential, positive integers (re-posting from StackOverflow as this is more of a review)

In the past, I've often encountered the following problem and so far my go-to solution was to combine a counter with a hashtable (with open-addressing).

The only operations I need to implement are the following:

next: generates a new integer or re-uses a previously freed one
free: frees a previously generated integer
size: returns the number of generated integers (excluding those who have been freed and not yet re-used)

Here's some working code that I use very often when this case pops up.

class IdGenerator
{
    typedef std::uint64_t Id;

public:
    IdGenerator():
        total_ids_(0)
    {
    }

    Id next()
    {
        Id id;
        if (available_ids_.empty())
        {
            id = total_ids_;
            ++total_ids_;
        }
        else
        {
            auto it = available_ids_.begin();
            id = *it;
            available_ids_.erase(it);
        }
        return id;
    }

    void free(Id id)
    {
        available_ids_.insert(id);
    }

    Id size() const
    {
        return total_ids_ - available_ids_.size();
    }

private:
    std::unordered_set<Id> available_ids_; // usually, I use open-adressing here
    Id total_ids_;
};

While this code generally brings good performance, I've always wondered if there was a faster way of doing this.

The only improvement I can see here is pretty marginal:

unordered containers have an average insert complexity of O(1), but that can become O(N) in degenerate cases (because of hash collision handling). That's pretty rare, but enough in my book to not use the datastructure if a simpler alternative would work just as well.

In your case, std::unordered_set doesn't provide anything you wouldn't get from a simple std::stack or std::queue anyways. So I would personally switch to one of these.

That being said, depending on the context behind how and why you use such an index generator, there are sometimes better ways to do this.

For example, if you are using this logic in order to manage a small block allocator, you can store the free list inside the unalocated memory. see example


Generic function With to do a one-liner using block I like this.  Anyone want to rain on my parade here?

public void LoadDatabasesTest()
{
    string[] args = new[] { "LoadDatabases" };
    ReportsService.Program_Accessor.Main(args);
    With(GetModel(), m => m.Databases.ToList().ForEach(c => Console.WriteLine(c.Name)));
}

void With<T>(T target, Action<T> action) where T : IDisposable
{
    using (target)
    {
        action(target);
    }
}

What is more clearer here?
This:
using (Model model = GetModel())
{
    foreach (var item in model.Databases)
    {
        Console.WriteLine(item.Name);
    }
}

or this:
With(GetModel(), model =>
    model.Databases.ToList().ForEach(c =>
        Console.WriteLine(c.Name)
    )
)

You've defined some method so you could rearrange some things and add additional levels of indirection to run slower and more inefficient than if you had just written the standard way using the using and foreach blocks.  What did you gain here?  I'll tell you, nothing.
Any half-decent C# programmer should know what the using and foreach blocks do.  There should be no question about it.  Seeing your block of code, it's not so clear... we'd have to figure out what you're doing here.
What if someone saw your block of code and wanted to know what is going on?  I look at that and see With... "With" what?  What the heck is that supposed to mean?  If anything, it is only more confusing to people who are familiar with VB.NET's With keyword (which does something completely different).  The name isn't very great.  You should have given it a more descriptive name.  UsingDisposable might have been a better choice or something along those lines.
Don't even get me started on the ToList/ForEach combo... You can never go right doing this instead of using a simple foreach loop.  Why would to take a perfectly good collection, copy that collection into another list, just so you can call some method to do stuff with the added overhead of calling another method to do something on each item?  The ForEach method has it's place and that's if and only if you start out with a list in the beginning.  The overhead of the delegate is more forgivable here since that's what it was designed for.  I understand that this particular usage is just a "hack" just to make this loop work, but this should never be the answer.  If you must, write an extension at least.
See reason number two of Eric Lippert's "foreach" vs "ForEach".  The same can be said here twofold, both for the With() method and your use of ForEach().
What happens if you need to do more than one statement in each of the blocks:
With(GetModel(), model =>
{
    HelloThere();
    model.Databases.ToList().ForEach(c =>
    {
        DoSomething();
        Console.WriteLine(c.Name);
        DoSomethingElse();
    });
    DoMoreStuff();
});

Here come the braces again and even more typing when instead you could have just done:
using (var model = GetModel())
{
    HelloThere();
    foreach (var item in model.Databases)
    {
        DoSomething();
        Console.WriteLine(item.Name);
        DoSomethingElse();
    }
    DoMoreStuff();
}

Save yourself the grief, just use the using and foreach blocks.


Selecting elements from the DOM of a page To get the book list from https://www.java67.com/2015/09/top-10-algorithm-books-every-programmer-read-learn.html , I am using the following code in the console of the firefox DevTools:
var select =  document.querySelectorAll("div.post-body.entry-content div h3 b");

for (i = 0; i < select.length; ++i) {

  try {
    var title =  select[i].querySelectorAll("u")[0];
    console.log (title.innerHTML);
  }
  catch(err) {
  }

  try {
    var author =  select[i].querySelectorAll("a")[0];
    console.log (author.innerHTML);
  }
  catch(err) {
  }

}

The output is:
Introduction to Algorithms by Thomas H. Corman debugger eval code:12:13
Algorithms by Robert Sedgewick &amp; Kevin Wayne debugger eval code:12:13
The Algorithm Design Manual by Steve S. Skiena debugger eval code:12:13
Algorithm for Interviews debugger eval code:12:13
5. Algorithm in Nutshell debugger eval code:5:13
6. Algorithm Design by Kleinberg &amp; Tardos debugger eval code:5:13
7. Introduction to Algorithms: A Creative Approach debugger eval code:5:13
7. Introduction to Algorithms: A Creative Approach debugger eval code:12:13
8. The Design and Analysis of Algorithms debugger eval code:5:13
9. Data Structures and Algorithms. Aho, Ullman &amp; Hopcroft debugger eval code:5:13
10. Python Algorithms: Mastering Basic Algorithms in the Python Language debugger eval code:5:13
undefined

You can see from the code that the first part div.post-body.entry-content div h3 b is same. Then I am using u or a. Is there any easier way to achieve this.

Don't implicitly create global variables for (i = 0; uses a global i. Always declare variables before using them - in modern times, declare them with let or const, not var (which has too many problems, such as an unintuitive function scope rather than block scope, to be worth using nowadays)
Iterators Or, even better, rather than iterating manually, invoke the NodeList's iterator, and use for..of instead, eg:
for (const b of bs) {
  // do stuff with each <b> element
}

querySelector If you only want to select one element matching a selector, don't use querySelectorAll followed by [0] index lookup - use querySelector instead.
try/catch In predictable, synchronous code, there shouldn't be any need for try/catch. If you aren't sure whether an element exists, just test it first, instead of possibly throwing an error.
textContent Use textContent rather than innerHTML - textContent is faster and more appropriate when you aren't deliberately retrieving HTML markup. Also, .innerHTML gives you difficult HTML entities, as you can see with your Kleinberg &amp; Tardos, instead of Kleinberg & Tardos
Try something like this instead:
const bs = document.querySelectorAll("div.post-body.entry-content div h3 b");
for (const b of bs) {
  const child = b.querySelector('u, a');
  if (child) {
    console.log(child.textContent);
  }
}


Expand string patterns in Elisp I need to expand logical patterns to list of strings.

For example I have the following definition:

(expand-pattern '(and "xy"
                      (or "1" "2")
                      (or (and "ab0"
                               (or "1" "2" "3"))
                          "cd01")))

Which evaluates to the following list of strings:

("xy1ab01" "xy2ab01" "xy1ab02" "xy2ab02" "xy1ab03" "xy2ab03" "xy1cd01" "xy2cd01")

I wrote the following code:

(defun expand-pattern (pattern)
  (defun expat (parents expr)
    (pcase expr
      ((or (pred stringp)
           (pred numberp))   (mapcar (lambda (parent)
                                     (cons expr parent))
                                     parents))
      (`(and ,first)         (expat parents first))
      (`(and ,first . ,rest) (expat (expat parents first)
                                    (cons 'and rest)))
      (`(or . ,args)         (apply #'append
                                    (mapcar (lambda (arg)
                                              (expat parents arg))
                                            args)))
      (_                     (error "unknown %S" expr))))
  (mapcar (lambda (tokens)
            (mapconcat (lambda (token)
                         (format "%s" token))
                       (reverse tokens)
                       ""))
          (expat '(()) pattern)))

I am new to Emacs Lisp and would like to know, if this is a reasonable way to solve the problem in Elisp or if it can be optimized, to simplify the code.

Scoping

In Emacs Lisp a nesting a defun inside another defun does not create a lexically scoped function. The symbol for the 'nested' function is still interned at in the current objarray. The behavior is unlike that of Scheme.

In Emacs Lisp let ((f (lambda (x) (body))))...(funcall f some-value) is the general structure for a 'local' function.

Formatting

The formatting of the code within the call to pcase is difficult to read. When the condition and consequent cannot be listed on the same line, it is probably more common to place the consequent below the conditional.

Suggested Alternative Format

(defun expand-pattern (pattern)
  (mapcar (lambda (tokens)
            (mapconcat (lambda (token)
                         (format "%s" token))
                       (reverse tokens)
                       ""))
          (expat '(()) pattern)))

(defun expat (parents expr)
  "Utility function for expand pattern."
  (pcase expr
    ((or (pred stringp)
         (pred numberp))
     (mapcar (lambda (parent)
               (cons expr parent))
             parents))
    (`(and ,first)
     (expat parents first))
    (`(and ,first . ,rest)
     (expat (expat parents first)
            (cons 'and rest)))
    (`(or . ,args)
     (apply #'append
            (mapcar (lambda (arg)
                      (expat parents arg))
                    args)))
    (_ (error "unknown %S" expr))))

Other Remarks

Because expat throws an error, it might make sense to have expand-pattern invoke expat within a try...catch block. Alternatively, expat could return nil when no match is found. If nil is a possible return value from processing the pattern, then a "Lispy" thing to do is to return two values, the first being the result of processing the expression and the second being either nil or t to indicate an error or no error.


Implementation of FastICA in multithreading approach I am to implement a parallel version of FastICA, so I implemented the serial version of FastICA.

Now this is the architectural diagram of how it is going to parallelize. I just coded a basic thread model of this. But I need to know what I did was correct or wrong regarding inter threads synchronization.

#include <condition_variable>
#include <mutex>
#include <vector>
#include <iostream>
#include <thread>

int numberOfThreads=10;
std::vector<int> checkedEvent(numberOfThreads);
std::vector<double> data(numberOfThreads);
std::mutex lock;
int IsPrepare=0;

std::condition_variable data_prepare;

class MainProcess
{
private:
    int rank;
    double input;
public:
    MainProcess(int rank_, double dataPr){
        rank=rank_;
        input=dataPr;
    }
    MainProcess(){

    }
    void fastICA_processing()
    {
        while(true){
            std::unique_lock<std::mutex> lk(lock);
            data_prepare.wait(lk,[this]{return checkedEvent[rank]!=1;});
            data[rank]=input;
            checkedEvent[rank]=1;
            IsPrepare=IsPrepare+1;
            std::cerr <<IsPrepare<<" thread is processing"<<std::endl;
            lk.unlock();
        }

    }

    void controller()
    {
        while(true)
        {

            while(IsPrepare==numberOfThreads)
            {
                std::lock_guard<std::mutex> lk(lock);
                std::cerr<<"Now controller is checking fastICA is converged or not "<<std::endl;
                std::fill(checkedEvent.begin(), checkedEvent.end(), 0);
                IsPrepare=0;
                data_prepare.notify_all();
            }
        }

    }
    };

int main()
{
    std::vector<std::thread> thredArray;
    MainProcess p3(0,0);
    std::thread process_thread(&MainProcess::controller,&p3);
    for(int i=0;i<numberOfThreads;i++){
        MainProcess* p1= new MainProcess(i,i);
        thredArray.push_back(std::thread (&MainProcess::fastICA_processing,p1));
    }
    for(auto &t:thredArray)
    {
        t.join();
    }
    process_thread.join();

    return 0;
}

Note: Here "data" stands for input data. First fastICA_processing threads do some mathematical calculations and then the controller thread gets all that data and processes it. This will happen again and again. I didn't add threads detaching part here.

The code is a mess, but I can tell you that it will spin forever right here:

std::thread process_thread(&MainProcess::controller,&p3);

This starts controller running immediately.

void controller()
{
    while(true)
    {
        while(IsPrepare==numberOfThreads)
        {
            std::lock_guard<std::mutex> lk(lock);
            std::cerr<<"Now controller is checking fastICA is converged or not "<<std::endl;
            std::fill(checkedEvent.begin(), checkedEvent.end(), 0);
            IsPrepare=0;
            data_prepare.notify_all();
        }
    }
}

IsPrepare is 0, and numberOfThreads is 10, and there's no synchronization to worry about here (no locks, no atomics), so we can definitely say that 0 == 10 is invariably false. Thus controller reduces to

void controller()
{
    while(true)
    {
        while(false) {}
    }
}

Okay, so that thread won't be doing anything anytime soon.
And with that code out of the way, the rest is pretty much irrelevant; it looks to me as if it will end up blocking forever, since there's nobody left to notify the condition variable.

Your problem might be suited to a TBB flowgraph; consider using TBB instead of hand-rolling your own stuff.


Average days on market calculation I have the following method which calculates average days on market for a sale type segment:

def average_days_on_market_sale_type_segment
    # on market days
    on_market_days = {}

    # 1. get last year sales - note that the dates need to be sequential in time (oldest in time comes first, most recent in time commes last)
    last_year_sales = self.real_property_sale_projects.where(status: 'reviewed')
      .where('deal_date between ? and ?', Time.at(Time.now - 1.years), Time.now)
      .map(&:real_property_sale)

    # 2. loop each sale type, convert sale description string to symbol
    last_year_sales.each do |sale|
      sd = sale.sale_description.parameterize.underscore.to_sym

      on_market_days[sd] ||= { count: 0, days: 0 }

      on_market_days[sd][:count] += 1

      # get the days on market value
      on_market_days[sd][:days] += sale.real_property_sale_project.days_on_market
    end

    # 3. summarize average
    summary = {}

    on_market_days.each do |k, v|
      summary[k.to_s.humanize] = (v[:days].to_f / v[:count].to_f).round
    end

    # 4. return summarized result
    # it should contain each sale description type as a key and average day as a number
    summary
  end

Is there a more elegant way to achieve the same thing? Does the solution contain any performance issues/gotchas?

Main notes:

Whenever you have a method broken up into commented sections, consider pulling out each section into its own, clearly named method.  This will make the pieces of your code focused and readable, and eliminate the need for comments.
Use ruby's built in functional methods rather than procedurally looping and bulding things manually.  group_by does most of the work for you in this case.
You can map over hashes, returning an array of [key, value] arrays, and then call to_h at the end to get back a transformed hash.
average_days_on_market_sale_type_segment is an unwieldy name.  avg_days_on_market_by_type seems like a small improvement you could make (generally naming hashes as value_by_key is clearer), but it's still long.  If you have expertise in real estate, you might be able to come up with something clearer that reflects language used by agents.  A quick google search came up with "CDOM", so maybe cdom_by_type would work, but with naming, there's no "correct" answer -- only what will be clear to the people working with the system.

A couple other things:

This isn't tested, since I don't have your data to test with.  So there may be some trivial errors.
The methods sales_description and avg_days_on_market that I introduced aren't really instance methods, since they are pure functions operating on a sale or array of sales.  This hints at further opportunities for refactoring by introducing objects for Sale or Sales, but that may be overkill at this point.

Refactored code:

def average_days_on_market_sale_type_segment
  last_years_sales.group_by {|sale| sales_description(sale)}
                  .map {|desc, sales| [desc, avg_days_on_market(sales)]}.to_h
end

def last_year_sales
  self.real_property_sale_projects
  .where(status: 'reviewed')
  .where('deal_date between ? and ?', Time.at(Time.now - 1.years), Time.now)
  .map(&:real_property_sale)
end

def sales_description(sale)
  sale.sale_description.parameterize.underscore.to_sym
end

def avg_days_on_market(sales)
  total_days = sales.map {|sale| sale.real_property_sale_project.days_on_market}
                    .inject(:+)
  total_days / sales.size
end


Returning a value based on a lookup I am trying to return a value (a.tnAddress) from a custom class based on a lookup (foreach loop).  Depending on the type of transaction, I will need to do the foreach loop based on different properties (sExecID, iMsgSeqNum, orsClOrderID).  I prefer to not have 3 differentforeach` loops just but I am not sure how else to re-write this.

Keep in mind that the code is working fine; I just want to simplify it.

private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction)
{
    switch (trPassedInTransaction.sMessageType)
    {
        case "Q":
        case "8b":
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.sExecID == a.sExecID)
                {
                    return a.tnAddress;
                }
            }
            break;
        case "3":
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.iMsgSeqNum == a.iMsgSeqNum)
                {
                    return a.tnAddress;
                }
            }
            break;
        default:
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.sClOrderID == a.sClOrderID)
                {
                    return a.tnAddress;
                }
            }
            break;
    }

    return null;
}

This will add the use of LINQ to clean up the code the way you want:

private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction)
{
    //a predicate to pass to the FirstOrDefault method
    Func<cls_Transactions,Boolean> filter = null;
    switch (trPassedInTransaction.sMessageType)
    {

        case "Q":
        case "8b":
                 filter = x => trPassedInTransaction.sExecID == x.sExecID;
            break;
        case "3":
                 filter = x => trPassedInTransaction.iMsgSeqNum == x.iMsgSeqNum;
            break;
        default:
                 filter = x => trPassedInTransaction.sClOrderID == x.sClOrderID;
            break;
    }

    cls_Transactions result = cls_GlobalVariables.transList.FirstOrDefault(filter);
    return result != null ? result.tnAddress : null;
}

As an explanation, the switch statement has just been converted to use a predicate, which is a function type where it passes one parameter (in this case a cls_Transactions) and returns true/false.

The FirstOrDefault method is shorthand for the foreach loop and return, foreach-ing through the elements and using the predicate to determine if it meets the required condition, if none meet the required condition it will return a default value (in the case null).

You can use the First method also, which will throw an exception if nothing is found :)


Given a set of points and pairs of lines, count the number of points that are between the pairs of lines This is a contest problem. The entire description is here.
In resume:
The question gives a point simulating a light explosion that always has a negative x coordinate, a set of pairs line segments on the y axis are given simulating walls and a set of points with positive x coordinate representing possible positions for a soldier.
The walls block  the light forming a cone with low profile. So, in how many of the given points its possible for the soldier stay in low profile? (A point that stays exactly in the cone line is not valid)
Here is a image describing what I want to say:
The points g3 and g1 are not valid.

The input description:

The first line contains an integer T (T = 100) indicating the number of test cases.
In the first line of each case there will be the coordinate (x, y) of the explosion epicenter. The next line will contain an integer P (1 ≤ P), indicating the number of walls. The next P lines there will be pairs of integers indicating the position of the walls, the start and end of a wall (remember that they stay in the Y axis, it is, X = 0). Then there will be an integer G (G ≤ 10^4) indicating the points that are candidates to a hide place. Then G lines will follow with pairs of coordinates (x, y) indicating their coordinates.
All the coordinates will be between -10^4 and 10^4 and will be integers. The epicenter of the explosion will have X < 0 and the hides positions X > 0. The initial Y of a wall will be strictly less than its end. The walls will not be sorted. The walls won't overlap each other, nor share endpoints. There might be some repeated Goemon positions.

My solution test for each point if it is inside of the cone formed by a wall (if the point is above one line and below other line).
The problem is that this solution is too slow, resulting in time limit exceeded. How can I optimize it?
#include <stdio.h>
#include <algorithm>
using namespace std;

typedef struct _point{
    int x,y;
    _point():x(0),y(0){}
    _point(int _x,int _y):x(_x),y(_y){}
}point_t;

typedef struct _line{
    point_t p1,p2;
    _line() : p1(0,0),p2(0,0){}
    _line(int y1,int y2) : p1(0,y1),p2(0,y2){}
}line_t;

inline int cross(point_t &a, point_t &b,point_t &c){
    return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
}

inline bool hasSameSign(int a,int b){
    return (a<0) == (b<0);
}

int main(void){
    int t;
    scanf("%d",&t);

    for (int i = 0,p,g,valid; i < t; ++i) {
        //read explosion coords
        int x,y;
        scanf("%d %d",&x,&y);
        point_t exps(x,y);

        //read initial and end points for each wall
        scanf("%d",&p);
        line_t *wall = new line_t[p];
        for (int j = 0; j < p; ++j)
            scanf("%d %d",&wall[j].p1.y,&wall[j].p2.y);

        //read all possible positions
        scanf("%d",&g);
        point_t *pos = new point_t[g];
        for (int j = 0; j < g; ++j)
           scanf("%d %d",&pos[j].x,&pos[j].y);

        //for each possible position and walls
        valid = 0;
        for (int k = 0; k < g; ++k) {
            for (int j = 0,signal1,signal2; j < p; ++j) {
                signal1 = cross(exps,wall[j].p1,pos[k]);
                signal2 = cross(exps,wall[j].p2,pos[k]);

                if(!hasSameSign(signal1, signal2)){
                    ++valid;
                    break;
                }

                //printf("%d %d\n",sinal1,sinal2);
            }
        }

        printf("%d\n",valid);
        delete [] wall;
        delete [] pos;
    }
}

You can get the intersection of a line described by 2 points with the y axis pretty easily using a simple formula.

First you sort the walls in increasing order. O(P log P)

For each point g you can get the intersection between the line g-E and x = 0 with g' = (g-E) / ((0-E.x) / (g.x-E.x)) + E (will need floating point operations) and you can search for g'.y in the walls array with a binary search. O(G log P)

Beyond that some comments about your code:

using namespace std; is usually a warning sign. This has several issues. Instead only use it to pull in specific thing you actually use or limit it to function scope.
Everything is in main. Reading the problem I'd expect a few functions like main, doSingleTest, readWalls and processPoints.
Declaring additional variables in the for initializer. This is very odd to see. Give each of them their own line in the body:

for (int j = 0; j < p; ++j) {
    //j can stay because it's the iterator value

    // you calculate them immediately after so join the declaration with initialization
    int signal1 = cross(exps,wall[j].p1,pos[k]);
    int signal2 = cross(exps,wall[j].p2,pos[k]);

Raw array usage. Instead use vector which will auto clean up when it goes out of scope.


Printing to terminal in a color Basically, I wish to have 3 printers to print in error state, success state or info state which means nothing but different colors.

    class ColorCode{
        private static $options = [
            "dark_gray"     => "1;30",
            "light_gray"    => "0;37",
            "blue"          => "0;34",
            "green"         => "0;32",
            "cyan"          => "0;36",
            "red"           => "0;31",
            "yellow"        => "1;33"
        ];

        public static function get($key){
            if(isset(self::$options[$key])){
                return self::$options[$key];
            } else {
                return '';
            }
        }
    }

    class ColorPrint {
        public $color = '';

        function __construct($color) {
            $this->color = ColorCode::get($color);
        }

        public function printc($msg) {
            echo "\033[". $this->color ."m".$msg."\033[0m\n";
        }

    }

    $out = [
        'error'     => new ColorPrint('red'),
        'info'      => new ColorPrint('cyan'),
        'success'   => new ColorPrint('green'),
    ];
    $out['error']->printc('Invalid Option');

I like your code, but I just have a couple of small points:

Be consistent with your spacing (around { and especially .).
I doubt that this will work on Windows, so I would check if the script is run on Windows, if it is, just print without color (or find a way to use color in Windows), and maybe trigger a warning.
I would rename printc, either to the shorter print (because it's easier to remember, and you don't really lose any meaning), to print_color (if you want to make it really really explicit that it is in color), or print_console (in case you also later implement something like print_web with CSS).
I would not just ignore it if a color is requested that does not exist, but handle it in some way (throw an exception, trigger a warning, etc). Otherwise users might wonder why ligth_gray or orange do not result in any color changes.


Circular doubly linked list in JavaScript I've been studying data structures and have taken a stab at implementing a doubly LL in JavaScript. Please review and advise on any additional improvements and optimizations. I'm more interested in feedback particularly regarding the implementations of removeAt(), contains() and getItem() methods as they share similar, repetitive code:

//Blueprints
function Node(val){
  this.data = val;
  this.next = null;
  this.prev = null;
}

function DoublyList(){
  this._length = 0;
  this._isCircular = false;
  this.head = null;
  this.tail = null;
}

//Adds to the list
DoublyList.prototype.add = function(val){
  var node = new Node(val);

  if(this._length){
    this.tail.next = node;
    node.prev = this.tail;
    this.tail = node;
  }else{
    this.head = node;
    this.tail = node;
  }

  this._length++;
  return node;
}

//Check if list is empty
DoublyList.prototype.isEmpty = function(){
  return this._length===0;
}

//Contains method returns index if true
DoublyList.prototype.contains = function(val){
  if(this.isEmpty()){
    return 'List is Empty';
  }
  var currentNode = this.head, i=0;
  //if val is in 1st node
  if(currentNode.data === val){
    return 0;
  }
  //if val is in last node
  if(this.tail.data === val){
    return (this._length-1);
  }
  //if val is in middle
  while(i++ < (this._length-1)){
    if(currentNode.data === val){
      return (i-1);
    }
    currentNode = currentNode.next;
  }
  return false;
}

//Make circular
DoublyList.prototype.makeCircular = function(){
  if(!this.isEmpty()){
    this.head.prev = this.tail;
    this.tail.next = this.head;
    this._isCircular = true;
  }
}

//get data by node index
DoublyList.prototype.getItem = function(index){

  if(this.isEmpty()){
    return 'List is Empty';
  }

  if(index<0 || index > this._length){
    return 'Invalid Index!';
  }

  var currentNode = this.head, i=0;
  //if first item in list
  if(index===0){
    return currentNode.data;
  }
  //if last item in list
  if(index === (this._length-1)){
    return this.tail.data;
  }
  //if item is in middle of list
  while(i++ < index){
    currentNode = currentNode.next;
  }
  return currentNode.data;
}

DoublyList.prototype.removeAt = function(index){
  if(this.isEmpty()){
    return 'List is Empty';
  }

  if(index<0 || index > this._length){
    return 'Invalid Index!';
  }

  var currentNode = this.head, i=0;
  //if first item in list: O(1)
  if(index===0){
    this.head = currentNode.next;
    this.head.prev = this.tail;
    this.tail.next = this.head;
    this._length--;
    return this;
  }
  //if last item in list: O(1)
  if(index === (this._length-1)){
    this.tail = this.tail.prev;
    this.tail.next = this.head;
    this.head.prev = this.tail;
    this._length--;
    return this;
  }
  //if item is in middle of list: O(n)
  while(i++ < index){
    currentNode = currentNode.next;
  }
  var temp = currentNode;
  temp.prev.next = currentNode.next;
  this._length--;
  return this;
}

var doublyList = new DoublyList();

console.log('isEmpty:\n'+doublyList.isEmpty());
doublyList.add(5);
doublyList.add(10);
doublyList.add(15);
doublyList.add(20);
doublyList.add(25);
doublyList.add(30);
doublyList.add(35);
doublyList.add(40);

console.log('Added items...\n');
console.log('Original List:\n'+doublyList);
console.log('makeCircular:\n'+doublyList.makeCircular());
console.log('Circular List:\n'+doublyList);
console.log('Get 3rd item:\n'+doublyList.getItem(2));
console.log('Contains:\n'+doublyList.contains(15));
console.log('RemoveAt:\n'+doublyList.removeAt(2));

the main observation I have is that if you know the length, and you have the tail and head, then you should use that in getItem(index) (meaning that if you want the 8th element out of 10, you should start from the head and go down, 2 operations instead of 8)

Other than that:

Contains can return a string, a number, or a boolean. That is bad design. In my mind it should return only a boolean. If you wanted to return the index, it should have been called indexOf
The shortcuts you take in contains are probably not worth the code, by that I mean that unless you know that more often than not the target value is in the first or last node, I would not code exceptions for those cases.
It is not intuitive that the caller must first add a node before turning the list into a circular one. Not to mention that makeCircular fails quietly when it does not make an empty list circular
You should probably check _isCircular in removeAt(0), it seems as if you assume the list is circular now.

Personally, I would make the list always circular or never circular and optimize the code accordingly instead of checking this property and coding accordingly in 1 list.


Simple C++ calculator I'm a programming newbie. In fact, this is my second code ever (after Hello World). I did a lot of reading actually, here on Stack Overflow, and other websites. I would like to know if there's a way to further improve this code.

#include <iostream>
#include <string>
using std::cout; using std::cin;

int main()
{
cout << "Calculator..... \n";
cout << "Type '3a3'to exit... \n";

double a=0 ,b=0;
char op = 'a'; //operator // 'a' is the exit operator, the value of the integers doesn't matter

int ch = 0; //while loop checker

do
{
    cin >> a >> op >> b;
    if (op == '/' && b == 0)
    {
        cout << "Division By Zero, Please Retry \n" ;
        goto retry;
    }
    switch (op)
    {
        case '+':
        cout << a << " + "<< b << " = " << a+b << "\n";
        ch = 0 ;
        break;

        case '-':
        cout << a << " - "<< b << " = " << a-b << "\n";
        ch = 0 ;
        break;

        case 'x':
        case '*':
        cout << a << " * "<< b << " = " << a*b << "\n";
        ch = 0 ;
        break;

        case '/':
        cout << a << " / "<< b << " = " << a/b << "\n";
        ch = 0;
        break;

        case 'a':
        ch = 1;
        break;

        default:
        ch = 0;
        cout << "Invalid operator, Please retry \n";
    }

    retry: ;

}while (ch != 1);

}

Structure aids understanding

Variable names, functions, classes... most of the code you actually write gets thrown away by the compiler, and is much more about readability and maintainability than anything else. Well structured code is also easier to spot holes in, easier to debug, etc.

So let's start by isolating the maths bit:

double evaluateSimpleExpression(double a, char op, double b)
{
    switch (op)
    {
    case '+': return a+b;
    case '-': return a-b;
    case 'x': return a*b;
    case '*': return a*b;
    case '/': return a/b;
    default:
        throw std::invalid_argument::invalid_argument("Invalid operator");
    }
}

This collects the logic for the actual expression evaluation given some input values, and also throws an error if the operator isn't valid. We've excluded the logic for getting user inputs in, so we could easily point this at a file of inputs or some other format with minimal effort. Using a standard error like this makes it easier to understand the type of error (just need to #include <stdexcept>).

It's still not quite free of the worries about inputs, which we can improve thus:

enum MathOp
{
    Plus = 0,
    Minus,
    Multiply,
    Divide,
    //...
    MathOp__LAST
};

MathOp interpretOperatorChar(char op)
{
    switch(op)
    {
        case '+': return Plus;
        case '-': return Minus;
        case 'x': return Multiply;
        case '*': return Multiply;
        case '/': return Divide;
        default: return MathOp__LAST;
    }
}

double evaluateSimpleExpression(double a, MathOp mop, double b)
{
    switch(mop)
    {
       case Plus: return a + b;
       case Minus: return a - b;
       case Multiply: return a * b;
       case Divide: return a / b;
       default:
         throw std::invalid_argument::invalid_argument("Invalid operator");
    }
}

Now we have separated the input-specific part (the characters used for operations, and the fact that there are two ways of entering a multiply) from the logic to perform the operation. If you wanted to add in a power operator '^'  then hopefully it would be clear what to add.

Clearly the second sample here is somewhat overkill for a little math processing, but it is the kind of structure you'd expect to see for a more comprehensive application; it would be easy, for example, to change the characters used for operations, or to interpret the expression and store it to evaluation later.

Separation of concerns

We have separated the logic from the specification of the inputs - we could easily run the evaluation function with completely different inputs like '10111PLUS11000'.

You'll notice that the operator interpreting function returns a non-value if it can't find the operator in its switch, and that the evaluation function throws if it can't process the given operator. These are the two different ways of coping with invalid inputs - we will use the interpret method generally, and then only evaluate the expression if we think we have a valid operator; the throw is there in case something goes exceptionally badly.

int main()
{
    cout << "Calculator..... " << endl;
    cout << "Type '3a3' to exit... " << endl;

    while(true)
    {
        double a=0 ,b=0;
        char op = 'a';

        bool parsedOK = cin >> a >> op >> b;
        if(!parsedOK)
        {
           cout << "Could not parse expression, expected form a + b"
                << endl;
           continue;
        }
        // 'a' is the exit operator, the value of the integers doesn't matter
        if(op == 'a')
           break;

        // attempt to parse operator
        MathOp gotOperator = interpretOperatorChar(op);
        if(gotOperator == MathOp__LAST)
        {
            cout << "Operator " << op << " invalid" << endl;
            continue;
        }

        // have a valid operator, attempt operation
        double result = _nan();
        try
        {
            result = evaluateSimpleExpression(a, gotOperator, b);
        }
        catch(std::invalid_argument e)
        {
            cout << "Operation failed: " << e.what();
            continue;
        }

        // print interpreted expression and result
        cout << a << " " << op << " " << b << " = " << result << endl;
    }
    return 0;
}

With this structure, we can progress through parsing and evaluating an expression in stages, and give appropriate errors that should inform the user. Now, we haven't included the divide by zero, but it's easy to see where to put it - it is the job of evaluateSimpleExpression to actually do the maths, so we should put it there:

double evaluateSimpleExpression(double a, MathOp mop, double b)
{
    switch(mop)
    case Plus: return a + b;
    case Minus: return a - b;
    case Multiply: return a * b;
    case Divide:
    {
      if(b == 0)
         throw std::invalid_argument::invalid_argument("Attempt to divide by zero");
      return a / b;
    }
    default:
      throw std::invalid_argument::invalid_argument("Invalid operator");
}

If, for example, we added a 'root' operator to get the bth root of a, we could add conditions for valid inputs (like only positive values of b, or only positive values of a when b is even), again providing error messages that give as much contextual information to the user as would help them understand it.


Speeding up Python date conversion function currently using list comprehension and datetime I am reading a large data file where the time is given in number of days since some epoch. I am currently converting this to Python's datetime format using this function:

import datetime as dt
def days2dt(days_since_epoch):
    epoch = dt.datetime(1980, 1, 6)
    datelist = [epoch + dt.timedelta(days=x) for x in days_since_epoch]
    return datelist

# run with sample data (might be larger in real life, in worst case multiply
# the list by 40 instead of 6)
import numpy as np
sample = list(np.arange(0, 3/24., 1/24./3600./50.))*6
dates = days2dt(sample)

Running this function takes 5x longer than reading the entire file using pandas.read_csv() (perhaps because the listcomp performs an addition for each element). The returned list is used immediately as the index of the pandas DataFrame, though interestingly, using a generator expression instead of a listcomp as above improves performance by ~35% (why?).

Aside from using a generator expression, can the performance of this function be improved in any way, e.g. by not performing this date conversion per-element or by using some NumPy feature I'm not aware of?

You should try Numpy's datetime and timedelta support:

def days2dt(days_since_epoch):
    microseconds = np.around(np.asarray(days_since_epoch) * (24*60*60*10**6))
    return np.datetime64('1980-01-06') + microseconds.astype('timedelta64[us]')

I suggest you read the units section of the docs to make sure this is safe (both resolution and min/max dates), but it should be fine.

Note that 90% of the time taken for days2dt is converting the input list to a numpy.array; if you pass in a numpy.array it goes much faster. Nevertheless, this is significantly faster than the list comprehension already.


Generating three-letter strings from five-letter words I am looking for feedback on a solution to the following problem posed from a book that I'm working through (Java: How To Program, 9th Edition):

  Write an application that reads a five-letter word from the user and produces every possible three-letter string that can be derived from the letters of that word.  For example, the three-letter words produced from the word "bathe" include "ate," "bet," "tab," "hat," "the," and "tea."

I have a sneaking suspicion that I've over complicated things.  Is my code easy to understand?  I'm a rookie coder still going over the basics.

import java.util.Scanner;

public class ThreeLetterStrings {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner( System.in );
        System.out.println( "Please enter a five letter word" );
        String userInput = sc.nextLine();           // get input
        int wordLength = userInput.length();       // get length of string in question
        char[] charArray = new char[ wordLength ];
        int stem = 0;       // stem being the 2nd letter after the first - b(a)the or ba(t)he
        int scan = 0;       // scan count for while loop
        boolean stamp;

        for( int i = 0; i < charArray.length; i++ )     // feed string into char array
        {
            charArray[ i ] = userInput.charAt( i );
        }

        for( int startLetter = 0; startLetter < wordLength; startLetter++ )
        {
            for( int stemLetter = 1; stemLetter < wordLength; stemLetter++ )
            {
            stem = startLetter + stemLetter;
            if( stem >= wordLength )
                stem = stem - wordLength;
            scan = 0;       // reset scan count after walk for loop
                for( int walk = 0; walk < wordLength - 2; walk++ )
                {
                    System.out.printf( "%c", charArray[ startLetter ] );
                    System.out.printf( "%c", charArray[ stem ] );
                    stamp = false;      // determines whether a character was printed

                    while( stamp == false )
                    {
                        if( scan == startLetter || scan == stem  )
                        {
                            scan++;
                        }
                        else
                        {
                            System.out.printf( "%c", charArray[ scan ] );
                            stamp = true;
                            System.out.println();
                            scan++;
                        }
                    } // end while
                } // end walk for
            } // end stemLetter for
        } // end startLetter for
    }
}

Your program can be simplified to something like this:

System.out.println("Please enter a five letter word");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

for (int i = 0; i < input.length(); i++) {             // pos. of 1st letter
    for (int j = 0; j < input.length(); j++) {         // pos. of 2nd letter
        for (int k = 0; k < input.length(); k++) {     // pos. of 3rd letter
            if (i == j || i == k || j == k) continue;  // any letter taken twice? -> skip
            System.out.printf("%c%c%c\n", input.charAt(i), input.charAt(j), input.charAt(k));
        }
    }
}

Some more pointers:

while this works for combinations of three letters, for combinations of more letters (or arbitrary numbers of letters) you should use some sort of recursive function
you might want to check whether the entered word is actually five letters long
before printing, you could store the three-letter-words in a Set<String> to filter out duplicates
the question is a bit unclear whether it's about three-letter strings or three-letter words; in the latter case you might want to get some dictionary of valid three-letter words and check whether the combinations are in that list


Checking whether any of some large collection of attributes has changed I have to check a large number of attributes and do something if any of them have changed. However, right now there are way too many or statements. Is there a better way to do this?

def check_updates
  if self.post_code_changed? || self.preferred_gender_changed?
    # do something
  elsif self.occupation_changed? || self.date_of_birth_changed?
        || self.religion_changed? || self.smoke_changed?
        || self.drink_changed? || self.drugs_changed?
        || self.diet_changed? || self.looking_for_changed?
        || self.edu_status_changed? || self.edu_type_changed?
    # do something else
  end
end

(In the following, I'm assuming this is a regular ActiveRecord-derived model class, you're dealing with.)

I'd do something like this for a 1st pass (note that I've elided some of the many attribute names in the array):

def bio_updated?
  [:occupation, :date_of_birth, :religion, ...].any? do |attribute|
    __send__(:"#{attribute}_changed?")
  end
end

after which you can just call self.bio_updated?.

A second pass would be add some more declarative way of handling this at the model class level. E.g. implement something that'd let you write:

class SomeModel < ActiveRecord::Base
  # idea is to write something like
  #
  #   tracked_attributes [group name], [array of attributes]
  #
  # to define stuff
  tracked_attributes :bio, [:occupation, :date_of_birth, :religion, ...]
  tracked_attributes :something_else, [...]
end

Which would do some meta-programming magic to give you a bio_updated? method and a something_else_updated? method (like seen above) you can call. (you may want to stick to *_changed? instead of *_updated? to keep to the Rails convention, though you can also argue that it'd be more confusing, since you're dealing with groups of attributes not single ones. Your call.)

There's probably a gem somewhere that does something like this already.

A middle way would be to abstract the any? matching into a generic method, just to stay DRY:

def bio_updated?
  any_attributes_changed? :occupation, :date_of_birth, :religion, ...
end

def something_else_updated?
  any_attributes_changed? ...
end

private

def any_attributes_changed?(*attrs)
  attrs.any? do |attribute|
    __send__(:"#{attribute}_changed?")
  end
end


Get maximum int key from a map of ints This code snippet gets the maximum int out of a map's keys

func max(numbers map[int]bool) int {
    var maxNumber int
    for n := range numbers {
        maxNumber = n
        break
    }
    for n := range numbers {
        if n > maxNumber {
            maxNumber = n
        }
    }
    return maxNumber
}

You could remove the first range by initialising maxNumber with math.MinInt(32|64) depending on the architecture. E.g. on 32-bit systems:

func max(numbers map[int]bool) (maxNumber int) {
    maxNumber = math.MinInt32
    for n := range numbers {
        if n > maxNumber {
            maxNumber = n
        }
    }
    return maxNumber
}

You can make it work with either system using build tags.


Taking input from push buttons I want to know if what I have coded is good enough or if there is any simpler/faster/better/less size taking substitute.

I am trying to take input from push buttons and I also want to remove repeated input so I coded like it and saved in a variable key. I used internal pullup to eradicated random input from digital pins. I am in pre-graduation in computer applications and a beginner in electronics.

byte key=0;
unsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime

void setup()
{
  delay(5000);            //start prog after 5 sec
  pinMode(7, INPUT);
  pinMode(8, INPUT);
  pinMode(9, INPUT);
  byte i;
  for(i=7;i<=9;i++)
    digitalWrite(i, HIGH);    //7,8,9 pins HIGH  for internal pullup
  Serial.begin(9600);
}
void loop()
{
  byte i;

  for(i=7;i<=9;i++)
    if(checkswitch(i)==1)       //check which switch was last pressed
    {
      key=i;
      st=millis();
      while(st>65000)            //controlling limits of unsigned int
        st=st-65000;
    }
  ct=millis();
  while(ct>65000)
    ct=ct-65000;                 //controlling limits of unsigned int

  if(ct>st+200)                 //Triggers only if 200 ms passed
  {                             //to not fill the Serial input

    if(key!=0)
    {
      Serial.println(key);
      key=0;                       //clear saved key
    }

  }
}

byte checkswitch(byte n)           //Check button pressed with internal pullup
{
  byte p=0;
  if(digitalRead(n)==LOW) p=1;      //my best algo for if-else statement
  return p;
}

I don't know the Arduino language but I've recently been learning, from what I can gather on the website unsigned ints will "roll-back" to zero if they reach their maximum (which will be reached in a huge "fifty days" so no need to worry about that.

You can clean up your syntax for your statements by putting the braces at the end  of the statement (on the same line), also remove the byte i from the function visibility into only the loop by declaring it in the for.

I also noticed that your function checkswitch is only used for boolean operations yet it's returning a byte - this can be fixed by returning the result of the comparison of the if you used directly.

Here is my suggestion:

byte key=0;
unsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime

void setup() {
  delay(5000);            //start prog after 5 sec
  pinMode(7, INPUT);
  pinMode(8, INPUT);
  pinMode(9, INPUT);
  for(byte i=7;i<=9;i++)
    digitalWrite(i, HIGH);    //7,8,9 pins HIGH  for internal pullup
  Serial.begin(9600);
}

void loop() {
  for(byte i=7;i<=9;i++)
    if(isHigh(i)) {      //check which switch was last pressed
      key=i;
      st=millis();
    }

  if(ct>st+200) {                 //triggers only if 200 ms passed to not fill the Serial input
    if(key!=0) {
      Serial.println(key);
      key=0;                       //clear saved key
    }
  }
}

boolean isHigh(byte n) {          //Check button pressed with internal pullup
    return digitalRead(n)==LOW;
}


Is this spaghetti code already? I post the following code writen all by hand. Why I have the feeling that it is a western spaghetti on its own. Second, could that be written better?

    <?php
    echo $this->Form->create('mysubmit');
    echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));
    echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));

    echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));
    echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));

    echo $this->Form->end("Submit");
    ?>

    <?php echo $this->Html->link("Error Results", "#"); ?>

Move all your Javascript out of the way.
From Yahoo's Best Practices for Speeding Up Your Web Site:

Make JavaScript and CSS External
Many of these performance rules deal with how external components are managed. However, before these considerations arise you should ask a more basic question: Should JavaScript and CSS be contained in external files, or inlined in the page itself?
Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.

Obviously, what's more important right now is to minimize that glorious readability mess, hopefully the (small) performance gain might be just the incentive you needed.
Cache your jQuery objects
You are using $('#inputs') in $("#mysubmitIndexForm").submit( ... ); and twice in $("#inputs").change( ... );. That's three times jQuery traverses the DOM to find #inputs, what you need to do is:
var inputs = $("#inputs");

at the top of your (external) script, and then use $(inputs) instead. Do it for all your objects, even if you're using them once, it will stay with you as a (good) habit.
Avoid inline CSS
Consider moving all your style declarations into an external CSS file. Other than a slight performance gain (similar to external JavaScript), you'll have all your style declarations in one, easy to find, place.

If you do all of the above, your code would look like:

    <link rel="stylesheet" type="text/css" href="myFunkyStyles.css" />

    ...

        <?php
        echo $this->Form->create('mysubmit');
        echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));
        echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));

        echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));
        echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));

        echo $this->Form->end("Submit");
        ?>

        <?php echo $this->Html->link("Error Results", "#"); ?>

and what's up with that empty

? If you just want to add some margin-bottom, why not do that on .notice instead?


Function composition in Python3 I wanted to implement a version of rambda's compose function in python. I also implemented some examples to show its working. However, I would like the community's input on my code:

These are the methods I use for testing

from functools import reduce, partial
import random
import math

def calcMean(iterable):
    return sum(iterable) / len(iterable)

def formatMean(mean):
    return round(float(mean), 2)

def adder(val, value):
    return val + value

def multiplier(val, value):
    return val * value

def isEven(val):
    return val % 2 == 0

The actual compose function

def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

The first exercise is something I came up with. In it I populate a list of length 10000 with random numbers from 0 to 10000, find the mean, round it to 2 decimal places, add 1 to it , then floor it and finally print out whether it is even or not.

if __name__ == '__main__':
    # Ex1
    rand_range = [random.randint(0, 10000) for x in range(0, 10000)]

    isRandIntEven = compose(calcMean, formatMean,
                            partial(adder, value=1), math.floor.__call__, isEven)

    print(isRandIntEven(rand_range))

The second exercise is taken from rambda's compose page. I tried to see if I could replicate the example (theirs is much more elegant)

    # Ex2
    classyGreeting = lambda firstName, lastName: "The name's " + \
        lastName + ", " + firstName + " " + lastName
    yellGreeting = compose(partial(
    classyGreeting, "James".upper()), str.upper.__call__)

    print(yellGreeting("Bond"))

The last example is also taken from rambda's compose page

# Ex3
    print(compose(
        partial(multiplier, value=2),
        partial(adder, value=1),
        math.fabs)(-4))

Suggestions for compose:

def compose(*fargs):
    def inner(arg):
        if not arg:
            raise ValueError("Invalid argument")
        if not all([callable(f) for f in fargs]):
            raise TypeError("Function is not callable")
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

if not arg: What's wrong with arg being falsey? Perhaps that's an acceptable input. Input validation should be designated to the functions being composed, which can raise their own errors.
if not all([callable(f) ...: This line should be before def inner(args). It should be a single-time input validation to ensure that all given inputs in fargs are callable. Currently, it checks needless amounts of times (each inner call) and does not check immediately.
if not all([callable(f) ...: You can use a generator expression instead of a list comprehension for this, slightly improving readability.

If both of these suggestions are implemented, your compose would look like:

def compose(*fargs):
    if not all(callable(f) for f in fargs):
        raise TypeError("Function is not callable")
    def inner(arg):
        return reduce(lambda arg, func: func(arg), fargs, arg)
    return inner

Please tell me if I have misunderstood your code.


Balanced smileys check algorithm (part 2) This is a follow-up for here.

  Problem

  Your friend John uses a lot of emoticons when you talk to him on
  Messenger. In addition to being a person who likes to express himself
  through emoticons, he hates unbalanced parenthesis so much that it
  makes him go :(

  Sometimes he puts emoticons within parentheses, and you find it hard
  to tell if a parenthesis really is a parenthesis or part of an
  emoticon.

  A message has balanced parentheses if it consists of one of the
  following:

  An empty string ""
  One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  A message with balanced parentheses followed by another message with balanced parentheses.
  A smiley face ":)" or a frowny face ":("
  Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:

At any point, the number of ) (close) should be less than the number of ( (open) + number of :( (frown)
At the end, the number of ( (open) should be less than the number of ) (close) and :) (smile)

I'm wondering if any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.

def check_balance(source):
    left = 0
    right = 0
    frown = 0
    smile = 0
    for i,c in enumerate(source):
        if c == '(':
            left += 1
            if i > 0 and source[i-1] == ':': # :(
                left -= 1
                frown += 1
        elif c == ')':
            right += 1
            if i > 0 and source[i-1] == ':': # :)
                right -= 1
                smile += 1
                if left + frown < right:
                    return False
    if left > right + smile:
        return False
    return True
if __name__ == "__main__":
    raw_smile_string = 'abc(b:)cdef(:()'
    print check_balance(raw_smile_string)

Some notes:

Variable naming

Can be greatly improved by the use of an IDE like IDEA which supports trivial variable renaming.
Don't use single character variables, index and character (or even char) is much more readable than i and c.
It's not immediately obvious what any of the variables are.

You only have one test case. There should be test cases including and excluding each of the types of content of a message. If you get started with the simplest one you can even use TDD to get to a working but simple design.
Knowing the index of the unbalanced parenthesis would be nice.
Checking the number of parentheses is not enough, you have to whether they match up. For example, your algorithm fails (reports True when it shouldn't) on strings like )(.
The assignment calls for a recursive solution:

  A message has balanced parentheses if it consists of one of the following: […] An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.

This means that within each pair of parentheses there must be a valid message, meaning all the rules apply within them.


Monitor webserver accessibility inconsistencies I have written a simple application to monitor whether a couple of Java EE 6 web applications deployed to Glassfish 3.1.2.2 are accessible. My intent is to demonstrate to our operations team that the applications are intermittently inaccessible.

package monitoring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Monitoring {

    private static final Logger logger = Logger.getLogger("MonitoringLogger");

    public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {
        configureLogger();
        URL[] urls = {
            new URL("http://alpha:11480/AlphaApplication-war/"),
            new URL("http://beta:11680/BetaApplication-war/")
        };
        while (true) {
            for (URL url : urls) {
                URLConnection connection = url.openConnection();
                connection.setReadTimeout(5000);
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    while (reader.ready()) {
                        logger.info(reader.readLine());
                    }
                } catch (SocketTimeoutException exception) {
                    logger.log(Level.SEVERE, "Read timed out to {0}", url);
                }
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(5));
        }
    }

    private static void configureLogger() throws IOException {
        FileHandler fh;
        fh = new FileHandler("logfile.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("Logger initialized");
    }
}

When the connection is successful, the reply is logged. When the connection times-out, the timeout is logged.

A Windows batch file runs this application on start-up:

java -jar "C:\Users\Me\Monitoring\dist\Monitoring.jar"
pause

I'm satisfied with the behaviour of this application, but I'm using unfamiliar APIs to accomplish an unfamiliar task, so I'm looking for broad advice.

The concept in your code is fundamentally good, but there are a few things I would recommend you change.
Static initializers
First up, I like static initializer functions when the static component is non-trivial. So, for example, this code:

private static final Logger logger = Logger.getLogger("MonitoringLogger");

public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {
    configureLogger();
    ......
}

private static void configureLogger() throws IOException {
    FileHandler fh;
    fh = new FileHandler("logfile.log");
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.info("Logger initialized");
}

I would replace with:
private static final Logger logger = configureLogger();

private static Logger configureLogger() {

    try {
        Logger logger = Logger.getLogger("MonitoringLogger");
        FileHandler fh;
        fh = new FileHandler("logfile.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("Logger initialized");
        return logger;
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not get logger up.", ioe);
    }
}

That's a 'trivial' change, but it puts the initialization sequence of the code in to a much more structured system.
What to log.
You don't really want to be logging what the sites are showing, you want to be logging their response times. I suggest pulling different metrics than the ones you are getting..... How long it took for the repsonse to come, and whether it was successful, or not. A log that looks like:

2015-07-22 12:23:34 [INFO] 3ms response from http://alpha:11480/AlphaApplication-war/
2015-07-22 12:26:12 [INFO] 3984ms response from http://alpha:11480/AlphaApplication-war/
2015-07-22 12:29:49 [ERROR] 5000ms TIME OUT FROM http://alpha:11480/AlphaApplication-war/

That would be much easier to process.
To do that, you will want to measure the actual times, not the responses... and you will pick up slow-to-respond servers too (perhaps a big garbage collection, over-congested network handler, or something).
So, create a function that has a response, which should be an Object:
private static final class ServerStat {
    private final boolean success;
    private final long milliseconds;

    ServerStat(boolean success, long milliseconds) {
        .....
    }
}

and then a function that tests an HTTP URL:
public static ServerStat pingServer(URL host) {
    long start = System.currentTimeMillis();

    boolean ok = false;
    try {

        URLConnection connection = url.openConnection();
        try (InputStream stream = connection.getInputStream()) {

            byte[] buffer = new byte[4096];
            while (stream.read(buffer) >= 0) {
                // throw the data away
            }
        }
        // no exceptions
        ok = true;
    } catch (Exception e) {
        // swallow any exception
    }
    return new ServerStat(ok, System.currentTimeMillis() - start);
}

Now, you have a function which times how long it takes to get a complete response (or fail) from a server.
Now, instead of having an infinite while-loop, have a non-daemon scheduled thread executor instead. Something like:
    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
    ses.scheduleAtFixedRate(() -> pingServerList(totest), 0, 5, TimeUnit.SECONDS);

That runs a function every 5 seconds.
I put it all together like this:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PingServer {

    private static final class ServerStat {
        private final boolean success;
        private final long milliseconds;
        private final String message;

        ServerStat(boolean success, long milliseconds, String message) {
            this.success = success;
            this.milliseconds = milliseconds;
            this.message = message;
        }
    }

    public static ServerStat pingServer(URL url) {
        long start = System.currentTimeMillis();

        boolean ok = false;
        String message = "OK";
        try {

            URLConnection connection = url.openConnection();
            connection.setReadTimeout(3000);
            try (InputStream stream = connection.getInputStream()) {

                byte[] buffer = new byte[4096];
                while (stream.read(buffer) >= 0) {
                    // throw the data away
                }
            }
            // no exceptions
            ok = true;
        } catch (Exception e) {
            message = e.getClass().getName() + ": " + e.getMessage();
        }
        return new ServerStat(ok, System.currentTimeMillis() - start, message);
    }

    public static void main(String[] args) throws IOException {
        List<URL> totest = Arrays.asList(new URL("http://localhost:3000"));
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        ses.scheduleAtFixedRate(() -> pingServerList(totest), 0, 5, TimeUnit.SECONDS);

    }

    private static void pingServerList(List<URL> totest) {
        for(URL url : totest) {
            ServerStat ss = pingServer(url);
            System.out.printf("%tc [%s] %dms %s %s\n", System.currentTimeMillis(),
                    ss.success ? "INFO" : "ERROR",
                    ss.milliseconds, url.toString(), ss.message);
        }
    }

}

and when I run it on my machine, with a test server running (then not running), I get the output:

Wed Jul 22 16:20:51 EDT 2015 [ERROR] 22ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:20:56 EDT 2015 [ERROR] 1ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:21:01 EDT 2015 [ERROR] 2ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:21:06 EDT 2015 [INFO] 21ms http://localhost:3000 OK
Wed Jul 22 16:21:11 EDT 2015 [INFO] 8ms http://localhost:3000 OK
Wed Jul 22 16:21:16 EDT 2015 [INFO] 5ms http://localhost:3000 OK
Wed Jul 22 16:21:21 EDT 2015 [INFO] 4ms http://localhost:3000 OK
Wed Jul 22 16:21:26 EDT 2015 [ERROR] 4ms http://localhost:3000 java.net.ConnectException: Connection refused


Storing Temporal Message Lists in ASP.NET MVC TempData I've been using the following the code to store temporal error messages in TempData, to be displayed from my master page on production sites without any problems, but is this a good way of doing it?

The controller helper code:

namespace System.Web.Mvc
{
    public static class Controllers
    {
        public static void SetMessage(this ControllerBase controller, string message)
        {
            List<string> messages = controller.TempData["Messages"] as List<string> ?? new List<string>();
            messages.Add(message);
            controller.TempData["Messages"] = messages;
        }
        public static void SetErrorMessage(this ControllerBase controller, string errorMessage)
        {
            List<string> messages = controller.TempData["ErrorMessages"] as List<string> ?? new List<string>();
            messages.Add(errorMessage);
            controller.TempData["ErrorMessages"] = messages;
        }
    }
}

Example Use:

public ActionResult Edit()
{
    // .. do stuff
    this.SetMessage("You edited X.");
    return View();
}

Here is the rendering code:

<%
    if (TempData["ErrorMessages"] != null)
    {
    %>
        Error Messages
        <%
        foreach (string s in TempData["ErrorMessages"] as List<string>)
        {
            %><%=s%><%
        }
    }

    if (TempData["Messages"] != null)
    {
    %>
        Messages
        <%
        foreach (string s in TempData["Messages"] as List<string>)
        {
            %><%=s%><%
        }
    }
%>

Can you spot any issues?

On the whole the approach is fine, but do not use TempData unless you're looking to populate this information across redirects. TempData comes with a host of issues, and its behaviour isn't quite what you think.

ViewData, on the other hand, is designed exactly for this purpose but comes with the caveat that it doesn't persist across redirects.

Therefore, if you're looking to put something in place which allows developers to push messages into your views easily, you need to expose the ability to put data in either ViewData or TempData, depending on whether they want to redirect or not.

Another option is to clear the TempData entry manually after the call has finished, but I wouldn't recommend this approach.

As a final point, your function names SetMessage and SetErrorMessage are misleading in that they imply you've got one spot only for the message. To me, as a user of your function, when doing this:

this.SetMessage("Foo");
this.SetMessage("Bar");

I would assume that my message is now set to "Bar", but behind the scenes it's a list with both "Foo" and "Bar". I'd recommend changing your function names to AddMessage and AddErrorMessage instead, which implies that behind the scenes there is a collection of elements.


Efficiently splitting a string in C++ I've made a splitString() function which receives a character and a string and returns a vector<string> containing all the string split by a character in the input string:
vector<string> splitString(string input, char separator) {

    size_t pos;
    vector<string> text;

    while (!input.empty()) {

        pos = input.find(separator); //find separator character position

        if (pos == string::npos) {
            text.push_back(input);
            break;
        }
        text.push_back(input.substr(0, pos));

        input = input.substr(pos + 1);
    }
    return text; //returns a vector with all the strings
}

Example Input(.csv):
name;surname;age

Output would be:
vector<string> contains {name, surname, age}

Is there any efficient way of doing this?
As you can see, the ; was deleted separating the strings.
I was wondering if there is any way of adding an option to NOT delete the separator character, including it in the split strings.

What are the expensive operations you do?

Allocating memory for the copy of a std::string passed into splitString().
This can be fixed by accepting a std::string_view instead, or at least a constant reference instead of a copy.
See How exactly is std::string_view faster than const std::string&? and What is string_view? for details.

Allocating memory for the std::strings stored in the result-vector.
Those might be replacable with std::string_view if the argument is changed, but no guarantees. This would be a significant usage change.

Repeatedly shuffling all the rest of the string to the front when removing a match.
Just find the target and copy / reference from there.

Constructing the result-elements in-place using .emplace_back() can also save some effort.

Adding the option to not remove the separator would only really make sense if you allow multiple separators.
Regarding your code, I'm not sure whether you use the dreaded using namespace std;, or the far more benign using std::string; using std::vector;.
If the former, see Why is “using namespace std;” considered bad practice?.
One behavioral point I changed: You ignore the last entry if empty. I decided to preserve it always, thus even an empty string gets at least one result.
auto splitString(std::string_view in, char sep) {
    std::vector<std::string_view> r;
    r.reserve(std::count(in.begin(), in.end(), sep) + 1); // optional
    for (auto p = in.begin();; ++p) {
        auto q = p;
        p = std::find(p, in.end(), sep);
        r.emplace_back(q, p);
        if (p == in.end())
            return r;
    }
}