JS debug: visually compare two objects or JSONs in browser

Today I was trying to find differences between two objects (coming from JSON API) during debugging in Chrome. First, I was printing them separately using console.log() and then copy-pasting into http://www.jsondiff.com/ for visual inspection. When I did it 3 times I decided I need better approach. So I wrote helper static function (ES6 syntax):

class Utils {
    static logComparison(message, a, b) {
        const encodedJsonA = encodeURIComponent(JSON.stringify(a))
        const encodedJsonB = encodeURIComponent(JSON.stringify(b))

        const link = `http://www.jsondiff.com/?left=${encodedJsonA}&right=${encodedJsonB}`
        console.log(message, link)
    }
}

Utils.logComparison(
    "Test",
    {a: 5, c: [1, 2, 3], b: 7},
    {a: 5, b: 42, c: [1, 3]}
)

How does it work?

  1. It converts JS objects into JSON string
  2. Encode that string so it can be used in URL
  3. Compose URL to jsondiff.com with both serialized objects as parameters
  4. Print this link into console together with message – so you can have some debugging context.

When executed, it prints following into Chrome/Firefox/MaybeOther Developer Tools console:

consoleline.png

If you click on that link, it opens new tab with visual comparison:

jsondiff

Please note that jsondiff.com can even handle scattered keys and missing array entries. It is so cool and does not need to install any special plugins. Handy little trick, don’t you think so?

Advertisements

4 tips to return multiple values

Java directly does not support returning multiple values from method. During time some workarounds were invented. I personally like Immutables approach.

Return array of values

Only one data type can be used, semantic of array items is not directly visible:

class Test {
    void test() {
        String[] name = getCompleteName();

        System.out.println(name[2]+", "+name[1]);
    }

    String[] getCompleteName() {
        DbPerson person = ...;

        return new String[]{person.getName(), person.getSurname()];
    }
}

This brings many issues:

  • Necessity to check length
  • Test NULL values
  • Semantics of fields is lost
  • Only one data type can be used

Use higher structure like Pair, List, Map

Use for example Pair:

class Test {
    void test() {
        Pair<String, String> name = getCompleteName();

        System.out.println(name.getSecond()+", "+name.getFirst());
    }

    Pair<String, String> getCompleteName() {
        DbPerson person = ...;

        return new Pair<>(person.getName(), person.getSurname());
    }
}

I don’t like this approach for the same reason as array – you lose semantics of fields and only one data type can be used.

Define returned type as class

Define nested/inner class with necessary members:

class Test {
    void test() {
        CompleteName name = getCompleteName();

        System.out.println(name._surname+", "+name._name);
    }

    public class CompleteName {
        String _name;
        String _surname;
    }

    CompleteName getCompleteName() {
        DbPerson person = ...;

        CompleteName res = new CompleteName();
        res._name = person.getName();
        res._surname = person.getSurname();

        return res;
    }
}

I don’t like accessing instance variables without accessors. But adding constructors/getters/setters is sooooo exhaustive. Fine for 2 fields but what about 10 or 20?

Use Immutables

Newest possibility and my favorite is to use library called Immutables. It allows you to define interface using with getters and generates builder/access methods according to it:

class Test {
    void test() {
        CompleteName name = getCompleteName();

        System.out.println(name.getSurname()+", "+name.getName());
    }

    @Value.Immutable
    public interface CompleteName {
        String getName();
        String getSurname();
    }

    CompleteName getCompleteName() {
        DbPerson person = ...;

        return ImmutableCompleteName
            .builder()
            .name(person.getName())
            .surname(person.getSurname())
            .build();
    }
}

This approach has many positive properties:

  • Semantic is kept
  • You may use arbitrary data types
  • Basic validation is done automatically (NULL checks, …)
  • You can define more complex validation using annotations

Reakce na článek: Úvaha listopadová spojená s prokletím

Ondřej Neff v článku Úvaha listopadová spojená s prokletím u příležitosti smutného 100. výročí VŘSR píše:

K tomu dodám jen svoji mantru, která se ke stému výročí ruské revoluce hodí: Za vše dobré, co je na světě, vděčíme přírodním vědcům a technikům. Za vše špatné, co je na světe, můžeme proklínat filosofy, kněží a politiky.

Vědci a technici rozhodně mají prsty nejen v akcích přínosných pro lidstvo. Pár příkladů:

  • DDT,
  • atomová bomba,
  • lék Contergan,
  • olověné trubky,
  • de Havilland Comet,
  • auta,
  • frontální lobotomie,
  • pouštění žilou.

Když udělají vědci a technici chybu, následky můžou být fatální. Vemte si takové špatně zkonstruované letadlo. Musely spadnout dvě de Havilland Comet a zemřít 56 lidí, než si technici uvědomili tak banální fakt, že mají vyměnit hranatá okna za kulatá.

Dalším příkladem mohou být bezpečnostní pásy nebo airbag v autech. Jejich vynalezení trvalo zoufale dlouho a dodnes umírá v EU na silnicích 26.000 osob ročně. Nebylo by lépe vymyslet auta rovnou dokonalá a zamezit tragédiím? Proč vědci a technici nevymysleli tak primitivní věc jako bezpečnostní pás dříve? Vždyť se jedná jen o kus plochého lana! Airbag je zase textilní pytel, který se nafoukne když auto narazí do překážky. Každý školák dokáže popsat jak fungují.

Je velmi pravděpodobné, že když si zapínáte bezpečnostní pás nebo letíte moderním letadlem, tak si s vděčností nevzpomenete na všechny oběti, které byly lidstvem položeny na cestě k jejich objevení. Nestavíme pomníky všem lidem zabitým na silnicích.

Abych to shrnul:

  1. Pokud je věc stvořena vyloženě pro páchání zla nebo má nějakou vadu či nedokonalost, umírají lidé. Hodně lidí.
  2. Získaná znalost má po čase tendenci být považován za úplnou samozřejmost.
  3. Vývoj jde pomaleji, než bychom si přáli.
  4. Občas se věda a technika vydá slepou uličkou.
  5. Na oběti už si reálně nikdo nevzpomene.

Proč by tyto principy neměly a nemohly fungovat také v humanitních oborech?

Zdá se, že obětí experimentů humanitních oborů je mnohem více. Když ale člověk poctivě promyslí oběti vědeckotechnických oborů, už to tak jednoznačně nevypadá. Navíc – humanitní obory mají tu nevýhodu, že musí pracovat s objektem s nejkomplexnějším chováním v celém známém vesmíru – člověkem. Máme problém popsat společenstva mravenců a včel. A co pak celé lidstvo?

Všichni známe skvělé objevy na poli vědy a techniky, uznáváme ale i skvělé objevy na poli humanity? Mantra tak trochu naznačuje, že bez humanitních oborů bylo na světě lépe. Ale spousta principů, pro které dnes máme jméno a přijímáme je samozřejmě, vznikla za cenu obrovských obětí. Jmenovitě:

  • schopnost žít společně ve velkých komunitách
  • schopnost pracovat na společném cíli
  • ctnosti
  • etika
  • právo
  • svobody jednotlivce
  • demokracie
  • sociální systém

Velmi pochybuji, že byl člověk stvořen jako hotový. Stejně, jako se zdokonaloval a zdokonaluje ve vědě a technice, se zdokonaluje v humanitě. “Těžko hned čekat dílo dokonalé a na věky,” řekl Masaryk.

Bylo by zajímavé sledovat svět, který si oběti vývoje humanity ušetřil. Nejspíš by v něm na všech úrovních platilo právo silnějšího. Nedošlo by k velkým objevům vědy. Vědci a technici by nepracovali v laboratořích, ale otročili na stavbách pyramid.

Rád bych se ohradil vůči bipolární vidění světa. Jde v něm o to najít jednoduchou dělicí čáru dobra a zla. Rozdělení jsou různá:
  • vědci a ne-vědci
  • produktivní lidé a důchodci
  • ženy a muži
  • černí a bílí
  • pravičáci a levičáci
  • inženýři a gender aktivistky
  • věřící a nevěřící
  • nadčlověk a podčlověk
  • buržoazie a dělnická třída

Jak nás učí historie, žádné z nich nefunguje. Pokusme se proto soudit konkrétní lidi podle jejich myšlenek a činů a přestat uplatňovat kolektivní vinu. Experiment už lidstvo udělalo, oběti už byly položeny a měli bychom se poučit.

Na druhou stranu je snadné rozlišit Mengeleho a Barnarda, Humbla a Fleminga, Hitlera a Gandího. A pak je morálně odsoudit nebo oslavit a dát tak jasnou zprávu dalším generacím.

Díky.

DisplayLink drivers on Ubuntu 17.10

Update: Driver version 1.4 works on 17.10 without hacks mentioned below. 

(there is whole journey of me and DisplayLink, NVidia, Intel and Dell troublemakers – see here and here and here)

After last updates I ended up with unbelievably annoying flickering, and sometimes completely missing, cursor on main display.

Desperate people do desperate actions. So I have tried to upgrade to Ubuntu 17.10 with kernel 4.13. Attempt to install “DisplayLink USB Graphics Software for Ubuntu 1.3.54” failed with following issue:

/var/lib/dkms/evdi/1.3.54/build/evdi_gem.c: In function ‘evdi_prime_create’:
/var/lib/dkms/evdi/1.3.54/build/evdi_gem.c:276:15: error: implicit declaration of function ‘drm_malloc_ab’; did you mean ‘dma_alloc_wc’? [-Werror=implicit-function-declaration]
 obj->pages = drm_malloc_ab(npages, sizeof(struct page *));
 ^~~~~~~~~~~~~
 dma_alloc_wc

I have asked on forum when 17.10 will be supported. Meanwhile there is workaround:

  1. Download 1.3.54 driver from http://www.displaylink.com/downloads/ubuntu
  2. Run installer with parameter keep ./displaylink-driver-1.3.54.run –keep
  3. It fails, but in current directory there is folder displaylink-driver-1.3.54
  4. There is file evdi-1.3.54-src.tar.gz, move it somewhere into temp directory
  5. Unpack using tar -zxvf evdi-1.3.54-src.tar.gz
  6. Replace evdi_gem.c by this file from this commit
  7. Pack it again using tar cvzf evdi-1.3.54-src.tar.gz *
  8. Replace original file in folder displaylink-driver-1.3.54
  9. Install driver using ./displaylink-driver-1.3.54/displaylink-installer.sh install
  10. Reboot computer, device should be recognized
  11. But Gnome with Wayland will switch off because recognizes unsupported device. (when will be supported Wayland is a big question)
  12. So first other shell is selected – Plasma in my case. Unfortunatelly most of packages is missing so nasty error appears.
  13. Log out, and on login screen below credentials select cog and there Unity
  14. Then it works except screen connected on DisplayLink shows only cursor
  15. Apply workaround 2 from here, reboot computer
  16. Voila!

20170922_084749

i-tec USB 3.0 Dual Docking Station & Ubuntu 16.04.3 or newer kernels

[There is updated article for Ubuntu 17.10]

There are older articles (first, second) about my issues with graphic on my hardware (Dell Inspiron 15 7559 and i-tec USB 3.0 Dual Docking Station).

Recently I have updated to Ubuntu 16.04.3 (kernel 4.10) so which configuration works now?

It is still necessary to block nvidia and nouveau modules in blacklist.conf. Package bbswitch-dkms is no longer required. Then monitor connected through i-tec docking station is visible in display settings. But when desktop is extended to it then is keeps to be blank. For my setup works first workaround mentioned in DisplayLink knowledge base.

Then everything works fine…..except of annoying flickering of cursor!!! There are some workarounds but unfortunately none works for me 😦

I wish one day problems with graphic cards disappear on Linux. I remember trying Linux for the first time.  There was CD attached to paper magazine. It was around year 2000. Guess why I was not able to use it?! Graphic card issues! Since then I had issue with EVERY graphic card I have used. Intel, ATI, NVidia.

vscub

React.js and MobX: Escape the Redux trap

I have seen React in action for the first time in relatively complex legacy application. There were some attempts to develop new functions using React and, of course, Redux. Because everyone is using that combination. It is the clear, cool way. Hm…

notsure

I fell in love with React quickly but with Redux it was not so hot. Alex Dixon wrote great article about his problems with Redux and functional programming in JavaScript. TLDR:

  • You never know whether you have plain JS object or Immutable.js object under your hands.
  • If you are not using Immutable.js then you still should know whether object you have can be mutated or not.
  • In every file you have to manually import libraries like Immutable or Lodash.

I had those issues plus:

  • It was real pain to describe complex change you would like to perform on immutable state within store. Like add 6th item into array, remove 3 different keys from map, etc.
  • For doing even simple things you have to modify code in multiple files. One often do a hack instead of nice solution.
  • Problems with using multiple stores. I still had feeling that I should not store state of form in global store. Local data should be local, right?
  • Same store is used during navigation without page reload. It is hard to clean everything properly.
  • React-Redux library is doing incredible magic I was never able fully understand.
  • Using Promises just made thing worse.
  • I still had feeling that if I have to reorganize store structure I will got mad.

Then, out of blue sky, I have found MobX. And I realized that I found great React’s partner.

thinking

I can have multiple stores – one that holds application state (selected language, global formatting settings), second that holds form state and handles communication with server, third for caching currency conversions, etc. This stores are available through React context – therefore their presence is checked by React using contextTypes definition. You can freely move components in hierarchy as long as you assure that proper stores are in context.

I still have certain level of immutability because MobX checks that no change is done during processing previous change.

Adding functionality is deadly simple. You have two classes – component and store.

Because store is single purpose and is object of class, it is quite easy to determine what you can do with it. If there is method, try to call it. Compare that with searching for proper Redux action.

Despite I have never use truly functional programming language I highly utilize lambda expressions (Ruby, Java 8, JavaScript), enjoy passing function as parameter and since then my usage of class inheritance dropped by 90% 🙂 In Java I employ Immutables, Jooq and high percentage of methods I write are static ones. So I consider myself open minded in functional programming area. That hopefully gives me some credit to have strong feeling that combination of React and Redux is simply wrong. MobX and React, on the other hand, are just great combination. At least for me 😉

 

 

 

 

Lambda: simplify method calls

There is important part of good programmers skills – ability to detect duplicity. Over years I have developed it for various situations. But recently I have added new situation – duplicity in calling methods with many parameters. And especially with many parameters in local scope. Take a look on following example:

package test;

import java.awt.Graphics;

public class NaiveRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		if (paramA<100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.2);
		} else {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Obviously, there is huge duplicity in renderSubpart calls. Calculation of some parameters is repeated many times. Let’s improve it:

package test;

import java.awt.Graphics;

public class BetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		boolean newParamB = !paramB;
		double newParamC = paramC*22.3;
		String newParamD = paramD+" oh";
		
		if (paramA<100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.2);
		} else {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Hm. So we have bloated scope by three new local variables. And we have to name it. Plus there is still problem with many similar calls to the renderSubpart. But only one parameter varies. Let’s improve that:

package test;

import java.awt.Graphics;

public class EvenBetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		double calculatedB;
		
		if (paramA<100) {
			calculatedB = -1.0;
		} else if (paramA<10) {
			calculatedB = -0.2;
		} else if (paramA==0) {
			calculatedB = 0.0;
		} else if (paramA>100) {
			calculatedB = 1.0;
		} else if (paramA>10) {
			calculatedB = 0.2;
		} else {
			calculatedB = 0.0;
		}
		
		renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So now we reduced number of added local variables to one. Great, but I don’t like decoupling of condition and method call. Block of condition just set calculatedB which is later used for calling renderSubpart. Can’t we improve that?

I realized that I can wrap parameters into local lambda function like this:

package test;

import java.awt.Graphics;
import java.util.function.Consumer;

public class LambdaRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		Consumer<Double> renderSubpartLambda = (calculatedB)->renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
		
		if (paramA<100) {
			renderSubpartLambda.accept(-1.0);
		} else if (paramA<10) {
			renderSubpartLambda.accept(-0.2);
		} else if (paramA==0) {
			renderSubpartLambda.accept(0.0);
		} else if (paramA>100) {
			renderSubpartLambda.accept(1.0);
		} else if (paramA>10) {
			renderSubpartLambda.accept(0.2);
		} else {
			renderSubpartLambda.accept(0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So I have defined renderSubpartLambda that receives single varying parameter and fill all other parameters that shares value over all calls. This is possible because Lambda function, unlike methods, have access to the local scope (parameters, local variables). Lambda is then executed from exact position withing condition blocks with only with single important parameter.

This technique is usable in all situations where it would be hard to define helper method because number of passed parameters would be too high. Btw. this solution is language independent – I have used it in JavaScript too.