.NET (293) administrative (41) Ajax (42) AngularJS (2) ASP.NET (144) bicycle (2) books (180) browser (8) C# (131) cars (1) chess (28) CodePlex (10) Coma (8) database (46) deployment (3) Entity Framework (2) essay (110) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (82) LInQ (2) Linux (6) management (4) manga (42) misc (665) mobile (1) movies (89) MsAccess (1) murder (2) music (64) mysql (1) news (98) permanent (1) personal (67) PHP (1) physics (2) picture (307) places (12) politics (13) programming (499) rant (119) religion (3) science (40) Sharepoint (3) software (57) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (97) Visual Studio (44) web design (45) Windows API (8) Windows Forms (3) Windows Server (4) WPF/Silverlight (63) XML (11)

Tuesday, July 01, 2014

Changing the grouping template of the AngularJS grid



I had this AngularJS grid that I wanted to show totals for certain categories and types. To be more precise, I had a list of items with Category and Type and I want to know the total for all categories and, for each category, the total for each type. This works perfectly if I load all items as individual, but I had hundred of thousands of items so it was clearly impractical. The solution? Send totals for every category and type, then just add them in the grid. In order to do that, though, I had to change the template of the "grouping row", the one that in ngGrid has the ngAggregate class.

It seems that all that is required for that is to change the aggregate template in the grid options. If you are not interested in the details, jump directly to the solution.

There is already an aggregate template in ngGrid.js, one that (at this time) looks like this:
<div ng-click="row.toggleExpand()" ng-style="rowStyle(row)" class="ngAggregate">
    <span class="ngAggregateText">{{row.label CUSTOM_FILTERS}} ({{row.totalChildren()}} {{AggItemsLabel}})</span>
    <div class="{{row.aggClass()}}"></div>
</div>

So we see that that the number displayed in an aggregate row is coming from a function of the row object called totalChildren, which is defined in ngAggregate.prototype and looks like this:
ngAggregate.prototype.totalChildren = function () {
    if (this.aggChildren.length > 0) {
        var i = 0;
        var recurse = function (cur) {
            if (cur.aggChildren.length > 0) {
                angular.forEach(cur.aggChildren, function (a) {
                    recurse(a);
                });
            } else {
                i += cur.children.length;
            }
        };
        recurse(this);
        return i;
    } else {
        return this.children.length;
    }
};
Maybe one could change the function to cover specific types of objects and return a sum instead of a count, but that is not the scope of the current post.

The solution described here will involve a custom function and a custom template. Here is how you do it:
  • Define the options for the grid. I am sure you already have it defined somewhere, if not, it is advisable you would. Sooner or later you will want to customize the output and functionality.
  • Add a new property to the options called aggregateTemplate. This will look probably like the default template, but with another function instead of totalChildren.
  • Define the function that will aggregate the items.

Solution 1:

Define template:
$scope.gridOptions = {
        data: 'Data.Units',
        enableColumnResize: true,
        showColumnMenu: false,
        showFilter: true,
        multiSelect: false,
        showGroupPanel: true,
        enablePaging: false,
        showFooter: true,
        columnDefs: [
            { field: 'Country', displayName: 'Country', width: 190 },
            { field: 'Type', displayName: 'Unit Type' },
            { field: 'Count', displayName: 'Count', width: 180}
        ],
        aggregateTemplate: "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
    "    <span class=\"ngAggregateText\">{{row.label CUSTOM_FILTERS}} ({{aggFunc(row)}} {{AggItemsLabel}})</span>" +
    "    <div class=\"{{row.aggClass()}}\"></div>" +
    "</div>"
    };
Define function:
$scope.aggFunc = function (row) {
        var sumColumn='Count';
        var total = 0;
        angular.forEach(row.children, function(entry) {
            total+=entry.entity[sumColumn];
        });
        angular.forEach(row.aggChildren, function(entry) {
            total+=$scope.aggFunc(entry);
        });
        return total;
    };

What we did here is we replaced row.totalChildren() with aggFunc(row) which we defined in the scope. What it does is add to the total the value of 'Count' rather than just count the items. It goes through row.children, which contains normal row items, then through aggChildren, which contains aggregate rows, which we pass through the same function in order to get their total.

Well, this works perfectly, but doesn't that mean we need to use this for each grid? There is a lot of code duplication. Let's first put the template in the cache so we can reuse it:
module.run(["$templateCache", function($templateCache) {

  $templateCache.put("aggregateCountTemplate.html",
    "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
    "    <span class=\"ngAggregateText\">{{row.label CUSTOM_FILTERS}} ({{aggFunc(row)}} {{AggItemsLabel}})</span>" +
    "    <div class=\"{{row.aggClass()}}\"></div>" +
    "</div>"
  );

}]);
Now the gridOptions change to
$scope.gridOptions = {
        [...]
        aggregateTemplate: "aggregateCountTemplate.html"
    };
and we can reuse the template anytime we want. Alternatively we can create a file and reference it, without using the cache:
$scope.gridOptions = {
        [...]
        aggregateTemplate: "/templates/aggregateCountTemplate.html"
    };

Now, if we could replace the aggFunc function with a row function, adding it to ngAggregate.prototype. Unfortunately we cannot do that, since ngAggregate is a 'private' object. The only thing we can do is to add some sort of static function. The solution is to add it in the root scope, so that is available everywhere.

Solution 2:

Here is the content of the file aggregateCountTemplateCache.js, that I created and load every time in the site. It does two things: inject the function in the root scope of the application and add the template to the cache. The only other thing to do is to use the aggregateTemplate: "aggregateCountTemplate.html" grid options.
var module = angular.module('app', ['ngResource', 'ui.bootstrap', 'ui', 'ngGrid', 'importTreeFilter', 'ui.date', 'SharedServices', 'ui.autocomplete']);

module.run(["$templateCache","$rootScope", function($templateCache,$rootScope) {

  $rootScope.aggregateCountFunc = function (row) {
        var total = 0;
        angular.forEach(row.children, function(entry) {
            total+=entry.entity.Count;
        });
        angular.forEach(row.aggChildren, function(entry) {
            total+=$rootScope.aggregateCountFunc(entry);
        });
        return total;
    };

  $templateCache.put("aggregateCountTemplate.html",
    "<div ng-click=\"row.toggleExpand()\" ng-style=\"rowStyle(row)\" class=\"ngAggregate\">" +
    "    <span class=\"ngAggregateText\">{{row.label CUSTOM_FILTERS}} ({{aggregateCountFunc(row)}}{{AggItemsLabel}})</span>" +
    "    <div class=\"{{row.aggClass()}}\"></div>" +
    "</div>"
  );

}]);

Enjoy!

Wednesday, June 18, 2014

TV Series I've Been Watching - part 19

The summer season is fast approaching and there have been a lot of changes in the TV series arena. As usual, the red indicates shows that I don't recommend and green the ones that I recommend.



  • Elementary - I was correct, there was an entire arch of the story regarding the brother of Sherlock, French mafia, MI6, moles, etc. It lacked subtlety and it was mostly boring. How come normal murders are so much more interesting than archvillain trickery?
  • The Tomorrow People (2013) - the show was cancelled in May. I can't say I am sorry, though. It was typical young adolescent idiocy.
  • The Originals - I am however completely not happy for NOT cancelling this crap.
  • Marvel's agents of S.H.I.E.L.D. - Yay! Hail Shield! Good guys win again. And also Samuel L. Jackson appears in the end season, bringing with him what appear to be Shield agent clones? Did he steal them from Star Wars?
  • Ripper Street - Filming for the Amazon online channel was supposed to begin in May. I think it has.
  • Babylon - No news yet, but there are certainly no news of cancellation, so I guess we will see the next episodes being released later this year.
  • Banshee - Third season confirmed.
  • Bitten - Another show that was renewed for a second season for no apparent reason. It is just awful.
  • Black Sails - Renewed for a second season, I partly like it. It is at least well done, with decent acting and an eye for detail.
  • From Dusk Till Dawn - As a funny commenter observed: in an incredible moves the owners of the El Rey network renew the show produced by El Rey for a second season. I understand the difficulty of translating a movie into a series... wait, there is a sequel, too? Wait, there is a From Dusk Till Dawn third part? I've never heard of them before. Nevermind.
  • Helix - I think I got it now. When a show makes an effort to really suck ass, they renew it. It's like an executive learned behaviour to promote ass sucking. Renewed for a second season, Helix is the poster child of bad movie making.
  • House of Cards - It's good that I had to write this review, because it reminded me to watch the second season. Still haven't done it, though, which indicates either a problem with me or with the show. Probably me. Again, Kevin Spacey can't go wrong.
  • Intelligence - Amazingly enough, a show that I sort of enjoyed, without liking it too much, was cancelled. Very *intelligent* move...
  • Ressurection - I really tried to make myself watch this show, but I just procrastinated for a really long time. It says something about my feelings for this show. I was really waiting for the second season of the French one and the American remake doesn't do it for me.
  • Star Crossed - Teenage sci fi show about alien romance? Really beautiful actors, incredibly stupid script and acting. I just can't believe it was cancelled. It ruins my theory, because it trully sucked ass.
  • The 100 - The show started really well, predictably degenerated in artificial drama that had no place in the series, while going soft on the problems that someone would meet in that exact situation. Suddenly 100 teenagers from space have a functional colony, fight "grounders" for no good reason and keep alternating between screwing, screwing over and screwing up. Typical teenager, one might say, but their parents on "The Ark" are even worse. The show was renewed for a second season. The season finale, though, didn't give me much hope. They added two (and a half, one might say) human factions to the mix in just the one episode
  • The After - The pilot got positive reviews to they ordered it to series. I am not holding my breath.
  • The Americans - I liked the second season, although the arch with the American mole that turns homicidal and discovers the entire KGB operation by himself was really ridiculous. It was a nice touch about the murder of the KGB agents, also what happened to Nina and the reactions of the people. However the Moscow verdict makes no sense.
  • The Red Road - Ah, maybe exceptions just confirm a rule. Another crappy show that gets renewed for a second season.
  • True Detective - The first season was great, so there will be new seasons. New actors and new stories, though, for each season.
  • Vikings - Politics keep interfering with nice raiding and pillaging. That is the moment in history when things started going downwards and global warming started. True fact!
  • Suits - The fourth season just started. They try to keep it exciting, but the feel is gone.
  • Continuum - The third season went all over the place. The season finale has Cameron cooling it off with a new boyfriend from (yet) another timeline, then another mysterious traveler from a very far future that seems to have started the Freelancer cult, Liber8 split off after realizing they do more harm than good (while each character in the group starts to get a "nice" shine on them) and finally the Freelancers getting mowed down. But then, they never really die, do they?
  • Crisis - For me the scene when a stupid kid sees Francis killing a kid and then tells all of the others that the kidnappers made him do it has done it for me! Oh, or the one when he forces a Chinese spy to unleash a virus that effectively destroys the Internet in order to gain time. Where do you get this idiocy from? BTW, it was cancelled.
  • Da Vinci's Demons - Enemies get together, they eventually run into Mayas on America and, of course, traces of DaVinci's parents, then they return just in time to stave off the invasion of Italy by the Turkish navy which just appeared out of nowhere. Not only will this be renewed, but it won prizes! It is a guilty pleasure that I like it, most of the time, I have to admit.
  • Turn - Interesting show. It lacks something, probably sympathetic characters. I really don't see myself liking any of them, including the generously bosomed women who have casual sex all the time. That is saying something.
  • The Crimson Field - Was it cancelled because it featured female main characters? Or because it was well acted? I just don't know.
  • Silicon Valley - Elon Musk accused the show of showing the wrong weirdness of Silicon Valley. I don't know how things are there, but to me it feels like he probably is right. A lot of crap about sex, race, manhood, geekiness seen as emasculating, random genius, etc. For me the scene when in one night the guy develops what his entire team failed to in five months has done it for me. I like parts of the show, but I don't think I liked the show overall.
  • Bad Teacher - I could stand literally 2 minutes of it. Then I stopped and deleted everything. It is the type of ha ha ha sitcom that brings nothing.
  • Black Box - A movie about a brilliant woman psychiatrist. Of course she is very sexually active, a bit insane and a sexy redhead. It's basically Doctor House meets Unforgettable. I bet it will be cancelled because she is a crazy broad and only male characters are allowed to be brilliant. Plus she is annoying. Nice ass, though.
  • Californication - The seventh season will be the last, thank you! They butchered a lovely idea that was fantastic in the first two seasons and let it die in agony for the last five, blood and guts pouring out of it until nothing but a boring husk remained. Duchovny was my god at the beginning of the show.
  • Deadbeat - comedy about a deadbeat seeing ghosts and solving their problems. I actually commented on Imdb (I usually don't for TV series) to warn people off it. It is offensively boring and formulaic and completely not funny.
  • Dracula - It was a weird reinvention of Dracula, but one that I kind of liked. Guess what! They cancelled it! Perhaps the trick is to not like anything that I like and like everything that I dislike. In this way they will renew the shows that I hate to love, rather than the ones that I love to hate. Yes, that's a good plan.
  • Game of Thrones - Thank God for Peter Dinklage! One realizes how tedious the books are when they watch this well done series that compresses whole books in half a day of video and you still feel nothing happens. And then someone dies and the episode ends.
  • Halt and Catch Fire - Imagine Mad Men, but with a real psychopath as the main character, the field changed from advertising to personal computer manufacturing and a clone of Angelina Jolie's persona from the movie Hackers as the "tech genius". So, in other words, with more Mad, and less Men. I really dislike the main character and I don't see where this is going. Hardware is not glamorous, software is! *cough* *cough*
  • In the Flesh - I really liked the first season, but I waited to see episodes from the new one as well. Somehow I can't bring myself to start watching it again. I will, though, soon.
  • Penny Dreadful - Ok, it is a horror series that mixes in all the Victorian themes like Jack the Ripper, vampires, werewolves, tuberculosis, Frankenstein, Dorian Gray, etc. But it's well done and it has a nice cast: Eva Green, Timothy Dalton, Billie Piper, Josh Hartnett and others.
  • Prey - John Simm is a detective in this British drama, and he is framed for the murder of his wife and son by a mysterious man. He is a... fugitive from the law trying to solve his own case. Kind of bland and hard to believe in this day and age. The Fugitive was much more credible because not only movies were silly at that time, but also most people. Now we have evolved quite a lot *cough* *I should stop with these asterisks everywhere* *cough*
  • Quirke - Gabriel Byrne is the lead in this British miniseries, playing a doctor that somehow is connected to everyone in the city and where the problems usually stem from one member of his extended family or another. Feels like In Treatment set in the past and in which Byrne is both doctor and patient. I think it could have been more. As such, it's a little bit annoying and slow.
  • Salem - It is still the season of the witch. Salem is a new show, but I haven't started watching it. The premise seemed a little bit forced.
  • The Wil Wheaton Project - Wesley from Star Trek is hosting a show that is not a TV series. It is a humorous take on the latest sci-fi news. You might not know it, but Wheaton is very active online in all kind of geeky indie shows, together with his friend Felicia Day (The Guild). I found it a little too satirical, but I liked it.
  • Under the Dome - the boring and annoying show has been renewed for a second season that will air at the end of the month.
  • Crossbones - Pirates! Again! This time starring John Malkovich. Haven't started watching yet.
  • Fargo - Based on a Coen brothers movie with the same name, it stars Billy Bob Thornton and has the brothers as executive producers. Haven't started watching yet.
  • From There to Here - British drama covering life from the Manchester bombing up to 2000. Haven't started watching yet.

That's about it so far.

Sunday, June 15, 2014

No patent reform to foster innovation? How about innovation to foster patent reform?

I think you have heard of Elon Musk by now. If you haven't, confess and pray to the Church of Musk for forgiveness. Jokes aside, the guy is scarily awesome, so much, in fact, that I think he forgot how to fail, which is dangerous. His ideas, though, eerily mirror some of my own (he probably gets them from me, hmm). This post is about Musk's decision to publicize their Tesla patents and allow anyone to use the technology "in good faith". And I will argue that this is a kind of patent revolt which is just as significant as blogging.

A while ago I had these weird ideas and a lot of extra energy. It occurred to me that if I would invent some cool algorithm or think of a disruptively ingenious device I could patent it and make some money. As you know, I am not much of an entrepreneur (in fact, I am probably the antithesis of that) and so I asked some people how this patent thing works. I was amazed to learn of the huge amount of money required to file, the lack of security against rich competitors who would really want to take your idea without paying and so on and so on. I was more than amazed, I was angry. As I saw it, the system was created so only people having rich investors on their side could even begin to patent something. Otherwise, if you just want to claim the ownership of an idea, you have to pay a lot of money before you even begin planning to use your idea to make them. Banks would win. Again. Poor and brilliant scientists and technicians would lose. Again.

But then I heard about this principle that if I have an idea and publish it somewhere, I can't patent it anymore. The trick is that no one else can, either. Practically, whenever I have an idea, if I put it on my blog I ensure people will be able to use it without it being patented by some asshole. They can still change it into something else and patent that, but they can never stop you using the idea in the form that was published. So I do that whenever I can. Not that I have so many patent worthy ideas, but if I think something is useful enough, I put it out there to spite a system that was corrupted in order for capital rich organizations to be able to hold control over new ideas.

Enter Elon Musk. He just took a lot of the technological effort that he invested in for Tesla and made it public. It's not completely free, it's still their patent, but they pledge to leave you alone if you use it in a reasonable way. Of course, there is a catch, Musk is investing heavily in electric car battery manufacturing, so it is still in his best interest for other people to start building electric cars. But I honestly think he is finding solutions that benefit the world and also increase his options, instead of the other way around. Do you see the similarity in the idea, though? Instead of expecting lawmakers to reform patent law, you just circumvent the whole system by making your idea publicly available. It helps to previously invest in support systems for that tech, too. It's a deceptively simple idea, the equivalent of inventing steam engine, letting everybody know how to make one, while previously investing in coal.

In software development, you can sort of do that same thing. First of all, have an awesome idea, implement it, make it freely available for use and publish it in your blog. This seems like a very altruistic thing to do, maybe even naive, but think about your life afterwards. People will know your name, employers would separate you from the crowd of wannabe programmers. In a weird way, it is the equivalent of branding yourself, that personal marketing skill that most technicians lack completely, but translated in code. A form of "pay it forward", perhaps. The reason why this works is that the cost of sharing information is practically zero nowadays, while the information itself is generating informational capital linked to your person as the inventor. And in turn, this fame, the kudos, is translated into trust which turns into credit because "you are good for it". I still don't have it clear in my head, but I feel the system changing from the cash printed by governments, essentially IOUs for that government from the public, to a more diverse offer. It would still be credit, but based on idea capital, not gold in banks. Worth a thought.

Friday, June 06, 2014

The horrible case of Bravofly (Volagratis)

So I have to leave Italy and go to Belgium for some business. I would make the trip with my colleagues so, imagining they know better how to fly from Italy, since they live here, I ask them to search for the flight. They do that and they send me this link to a site called VolaGratis ("fly for free" would be the translation). This is actually an Italian web site for BravoFly, an Italian flight search aggregator. I find my flight, it says 89EUR a two way flight, which was OK. The site is in Italian, though, so I choose English, it takes me to the BravoFly site, I select the same flight: 105EUR. I'll be damned! So I use the Italian site. I also check the special needs box and write down "Long Legs", expecting them to book me one of those extra legroom places. Now it gets interesting.

The payment section held a big message telling me how great it is that I use Mastercard, so they can give me a big discount. I don't use Mastercard, though, so I select VISA. Suddenly the price jumps from 89 to 125EUR. Well, that probably explained why there was a difference between the Italian and international site. So I proceed. In about half an hour I receive a call from a weirdly formatted Italian number: +39 followed by only 6 digits. I answer in English. There is a long pause, then (in English) I hear the question "Do you speak French?", I reply that I don't, the voice asks a quivering "Do you speak Italian?" (also in English) I also reply no, but I ask her to wait and I pass my phone to an Italian colleague. The operator has closed the connection by then, probably couldn't wait for more than 2 seconds without asking an inane question. A minute later I receive an SMS - in Italian, of course - that I couldn't be contacted and that I should call them back. All nice and all, only their phone numbers are all paid numbers, I have to pay 6EUR per call, give them my credit card details, etc. Or I can call the Italian paid number (six digits) and pay 1.8EUR per minute. Funny enough, I could not call the Italian number from the land line, since it was a paid one, nor from my friend's phone, also because it was locked for paid lines, nor could I call the international number from any Italian phone, as there was an automated voice telling me to call the other number. I wrote them a scalding email, awaiting a reply. I got a phone call at 8 PM which clicked two times and closed after two seconds, but no other reply.

So I was forced to call them using my Romanian number, in roaming in Italy, calling the paid "international" Italian number. And that is because their site could only show my bookings, but would not allow me to cancel one, so in fact they were holding my credit card details hostage. In order to cancel any booking with BravoFly I had to - yeah, you guessed it - call them. Meanwhile I was stuck not knowing if they will book the flight or not. After speaking with an operator speaking English with a thick Italian accent, one who barely mumbled anything she said and then acted annoyed that I ask her to speak louder, I realize that the whole thing was caused by my ticking the special request box and asking for the legroom. I needed to pay extra for that, of course. I said OK, waited for five minutes, nothing happened. I hung up the phone. Got called back in 5 minutes that my booking could not be confirmed. They might just as well have said "Thank you for the money and time you spent trying to make us do what we advertised we do, but we can't, so fuck you!". And I wouldn't have minded as much, since that could have been a nice email message and I wouldn't have had to get this angry.

The ending of the story is me getting to the EasyJet site directly, getting the ticket (with the extra legroom) for about 40EUR less than the one from VolaGratis, all in one nice and clear web interface. Perhaps Vola Gratis in the name of the site is all about them getting to fly for free with the money they extort from you. Don't ever use the BravoFly site or any of their differently named clones. From the way I was treated, I can only assume it is basically a scam, their purpose being only to steal from you.

Monday, June 02, 2014

Lichess - a very interesting chess server

Some time ago I started playing chess, got a trainer, played with my colleagues and friends. I felt a passion for the game that I have no idea from where it came and, just as suddenly as it appeared, it vanished. For more than a year I have not even looked at chess videos. I can't say when I would start playing again, not even if I ever would. And it's not because I am not really good at the game :), it is just a matter of random passion.

Passion is probably what made the creators of Lichess create the server. It is a chess site with a very clean interface, a lot of options, even a REST API (that's a programming thing, don't worry about it). Most of all, the site is completely free, no ads, no nags and a mission statement that ensures that the game will remain thus forever. Open source, with a lot of help from the community, Lichess shows a passion for both software development and chess. If I will ever start playing again, it will probably be because of people like these. Thanks, guys!