czwartek, 13 listopada 2014

JAVA OMG

  • Name: lets call this anti-pattern signification
  • Description: we can be sure that the original string will be converted to string
  • Why: to much free RAM and CPU
  • Example:
    new String(Integer.toString(deviceInfo.imageWidth))
    

środa, 12 listopada 2014

Quine

A quine is a program that prints itself:

Quine in JS

// browser
!function $(){console.log('!'+$+'()')}()

// node
(function quine() {
    console.log(quine.toString())
})()

Quine in Java

  // http://c2.com/cgi/wiki?QuineProgram
  public class Quine {
 public static void main(String[] args) {
 String[] str = {
  "public class Quine {",
  " public static void main(String[] args) {",
  "  String[] str = {",
  "  };",
  "  for(int i=0;i<3;i++)System.out.println(str[i]);",
  "  for(int i=0;i<9;i++)System.out.println((char)34+str[i]+(char)34+',');",
  "  for(int i=3;i<9;i++)System.out.println(str[i]);",
  " }",
  "}",
 };
 for(int i=0;i<3;i++)System.out.println(str[i]);
 for(int i=0;i<9;i++)System.out.println((char)34+str[i]+(char)34+',');
 for(int i=3;i<9;i++)System.out.println(str[i]);
 }
  }

Practical use

I used quines to print my programs as slides during Functional Programming workshop.

wtorek, 21 października 2014

Cat implementation of Maybe Monad

var _ = require('lodash');
var expect = require('chai').expect;

// implementation by Brandon Weaver
var maybe = function (object, methodCalls) {
    if (_.isUndefined(object)) {
        return undefined;
    }
    if (_.isEmpty(methodCalls)) {
        return object;
    }

    return _.reduce(methodCalls.split('.'), function (obj, method) {
        return obj ? obj[method] : undefined;
    }, object);
};

_.mixin({maybe:maybe});

describe('maybe', function () {

    afterEach(function (done) {
        setTimeout(done, 60);
    });

    // now
    var foodChain = [
        {food: 'mice', race: 'cat'},
        {food: null, race: 'mice'}
    ];

    var getFood = function (anml) {
        return anml.race + ' loves to eat ' + anml.food;
    };

    // with maybe
    var safeGet = function (anml) {
        return _.maybe(anml.race) + ' loves to eat ' + _.maybe(anml.food);
    };

    var betterSafeGet = _.maybe(getFood);

    it ('allows safe filters', function (done){
        // old way to do it
        var safeFilter = _(foodChain)
            .filter(function (el) {
                return el.food && el.race ? true : false;
            })
            .map(getFood);
        var mapWithBetterSafeGet = _(foodChain).map(betterSafeGet);
        var filterSafeGet = _(foodChain).filter(betterSafeGet);

        //ERROR
        expect(filterSafeGet.value()).eql(safeFilter.value());

        done();
    });

    it('gets same output as getter with if', function (done){
        var mapWithIf= _(foodChain)
            .map(function (anml) {
                if (anml.food && anml.race) {
                    return getFood(anml)
                }
            });

        var mapWithBetterSafeGet = _(foodChain).map(betterSafeGet);

        //ERROR
        expect(mapWithIf.value()).eql(mapWithBetterSafeGet.value());

        done();
    });

    it('allows safe getters getter', function (done) {
        var outSafeGet = _(foodChain).filter(safeGet);
        var filterWithBetterSafeGet = _(foodChain).filter(betterSafeGet);
        expect(outSafeGet.value()).eql(filterWithBetterSafeGet.value());

        done();
    });

    //describe dot notation
    it('is idempotent', function (done) {
        var object = {a: {b: {c: 1}}};
        expect(_.maybe(object, 'a.b.c')).eql(1); // returns 1
        expect(_.maybe(object, 'a.b.c.d.e.f.g')).to.be.undefined;
        // 1*1 ?= 1
        var one = _.maybe(_.maybe(object, 'a.b.c'), 'a.b.c');

        // ERROR returns undefined
        expect(one).eql(1);

        done();
    })
});

środa, 3 września 2014

CPU access in NOT like File Access

Yesterday on a meeting, someone mentioned, that CPU is like File access, that if we have ex: 4 threads system. Having 2 processes accessing the all 4 threads would be on first-come-first-serve basis.
That first process will utilize almost 100% CPU power (will be resource hog). Resulting huge overhead.

That is not the case.

Modern CPU's are very efficient in switching between threads.
The CPU time (computation time) of both processes would be divided almost equally.
The computation time of each processes would be ca. twice slower. Than running them separetly.
The total computation time of both processes would be (almost) equal to time of running them sequentially.

So CPU access in nothing like File Access

BTW: Modern kernels also can give multiple file descriptors so even File access would not be on first come-first-serve-basis

It all would be ok, I mean, all people can have false assumptions, but the person stating such bologna is Head of IT Unit :(...


Further reading:
http://en.wikipedia.org/wiki/Hyper-threading
http://en.wikipedia.org/wiki/Thread_%28computing%29
 

środa, 16 lipca 2014

brack.ch never again

brack.ch never again... they just sold me used phone as a new one. I start the phone.. and what do I see? A naked picture of previous owner :D ... together with his Hotmail account, and a friends list... :( What is more disturbing that the shop representative did not care at all. Apparently I'm supposed to send the phone on my cost to some 3rd party shop, and they will allow me to buy other things on theirs website up to phone cost.

czwartek, 28 marca 2013

Choosing Framework for your business

Wich framework would be best to build company on? This graphs may help deciding. We can see that due to extensive commercial support 'Play'(blue) is really quickly closing gap to 'Spring Java'(yellow). 'Ruby on Rails'(purple) stays 'the coolest' framework, and 'Zend Framework' basically kills 'Symfony Framework'(green) play frameworkzend frameworkspring framework200520072009201120...2020404060608080100100

wtorek, 12 lutego 2013

Refactoring To Command Pattern

//usage of command pattern to refactoring big or overloaded methods
//Gigantic classes with hard to change methods
class Wrong_Customer {
    var  $_age;
    var $_bill;
    var $_man;
    function __construct($age, $bill, $man) {
        $this->_age=$age;
        $this->_bill=$bill;
        $this->_man= $man;
    }
    //addind discount will require modyfy other classes
    //new calculation devices requre to chenge methods
    function returnFinalBill() {
        $discountPercent=0;
        if($this->_age >60) { $discountPercent +=0.10;}
        if(!$this->_man) { $discountPercent +=0.20;}
        $bill = $this->_bill*(1-$discountPercent);   //100%=1
        return ("Wrong Customer Bill Amount: $".$bill."
"); } } interface BillPlayer { //based on sex how to calculate bill public function calculateBill($amountDue); } interface Command { //methods that change function executeCalculateBill($amountDue); } class WomanOver60 implements BillPlayer { public function calculateBill($amountDue) { return "Bill Amount for Woman over 60: $".($amountDue*(1-0.30))."
"; } } class ManOver60 implements BillPLayer { public function calculateBill($amountDue) { return "Bill Amount for Man over 60: $".($amountDue*(1-0.10))."
"; } } class ManUnder60 implements BillPLayer { public function calculateBill($amountDue) { return "Bill Amount for Man under 60: $".($amountDue)."
"; //no discount } } class Waiter implements Command { //Comander var $_billPayer; function __construct(BillPlayer $billPayer) { $this->_billPayer=$billPayer; } function executeCalculateBill($amountDue) { return $this->_billPayer->calculateBill($amountDue); } } class CashRegister { //invoker from command pattern, execute diferent methods based onobject type passed //return final bill //_Waiter diferent weiters, !adds flexibility! //stores Command's var $_command; function __construct(Command $command) { $this->_command=$command; //all things that implements command //like waiters } function returnFinalBill($amountDue) { return $this->_command->executeCalculateBill($amountDue); } } // more flexebility - only one thing to change for adding bill Payers class CustomerTypePicker { //if u want NEW bill payer tpe goes here!!! static function getManOver60(){ return new ManOver60(); } static function getManUnder60(){ return new ManUnder60(); } static function getWomanOver60(){ return new WomanOver60(); } } //adding customer group for easier to menage diferent customers class CustomerGroup { private $_customers=array(); function __construct($customers=array()) { $this->_customers = $customers; } function getCustomer($index) { return $this->_customers[$index]; } function addCustomer(BillPlayer $customer) { return $this->_customers[]=$customer; }//TODO deleteCustomer } class Main { function __construct() { $wC = new Wrong_Customer(70, 100, false); //woman Over 60 echo $wC->returnFinalBill(); } function testCommandOnWomenOver60() { $picker = new CustomerTypePicker(); $sally = $picker::getWomanOver60(); $waiter = new Waiter($sally); //sallysWaiter $bill = new CashRegister($waiter); echo $bill->returnFinalBill(100); } function testCommandOnManOver60() { //NOW better groups customers to array $picker = new CustomerTypePicker(); $bob = $picker::getManOver60(); $waiter = new Waiter($bob); //sallysWaiter $bill = new CashRegister($waiter); echo $bill->returnFinalBill(100); } function testCustomerGroup() { $picker = new CustomerTypePicker(); $customerGroup = new CustomerGroup(); $sally = $picker::getWomanOver60(); $customerGroup->addCustomer($sally); echo $customerGroup->getCustomer(0)->calculateBill(100); } } $run = new Main(); $run->testCommandOnWomenOver60(); $run->testCommandOnManOver60(); $run->testCustomerGroup();
Java implementation here: http://www.newthinktank.com/2013/02/code-refactoring-13/