Just my way to use ES6 promises

I like JavaScript promises. But I'm not too crazy about the ES6 way (see MSDN) where you get the resolve and reject as parameter of a function:

            function doSomethingAsync() {
                return new Promise(function(resolve, reject) {
                    callAsncCode(xyz, function(result) {
                        if(<result is ok>) {
                            resolve(someData);
                        }
                        else {
                            reject();
                        }
                    });
                });
            }
        
I would rather have something like this:
            function doSomethingAsync() {
                var promise = <gimme a promise>
                callAsncCode(xyz, function(result) {
                    if(<result is ok>) {
                        promise.resolve(someData);
                    }
                    else {
                        promise.reject();
                    }
                });

                return promise;
            }
        
To get this I always have this small ES6 class in my tool belt:
            class SimplePromise {
                constructor() {
                    const self = this;
                    this._promise = new Promise(function(resolve, reject) {
                        self._resolve = resolve;
                        self._reject = reject;
                    });
                }

                resolve(data) {
                    this._resolve(data);
                }

                reject(data) {
                    this._reject(data);
                }

                promise() {
                    return this._promise;
                }
            }
        
Now my code looks like this:
            function doSomethingAsync() {
                var promise = new SimplePromise();
                callAsncCode(xyz, function(result) {
                    if(<result is ok>) {
                        promise.resolve(someData);
                    }
                    else {
                        promise.reject();
                    }
                });

                return  promise.promise();
            }
        
Not everyone may like it. I do.

Functional If/Else

Functional if in Javascript

What about this functional if/else version for Javascript?

            function _if(boolean, trueBody) {
                if(boolean) {
                    trueBody();
                }

                function _else(falseBody) {
                    if(!boolean) {
                        falseBody();
                    }
                }

                return {
                    else: _else
                }
            }
        
It can now now be used like this:
            _if(booleanExpression, function() {
                // if body
            }).else(function() {
                // else body
            });
        
Now you have an if/else body with local scope.

The Dark Matter Of Numbers

For years Iā€™m contemplating about a countable subset of R, bigger than Q:
The set of numbers which can be determined with a finite number of characters.
This set (I call it R- or sub-transcendental numbers) is obviously countable.

  • What are the properties of R-?
  • What are the properties of R \ R- (I call it R+): A number of R+ cannot be described with a finite number of characters (in no way). You cannot grasp a number in R+ (if you could, it would be in R-)

See here the beginning of a paper (not too serious) in which I try to formalise my thoughts.

More is coming up.

Installing Git 1.9.2 On Google Compute Engine With CentOS

Install Git 1.9.2 on CentOS on Google Compute Engine

I just installed Git 1.9.2 on a Google Compute Engine virtual machine running CentOS.
These were the steps which led to success:
At first I followed the steps from Jonathan Mark Smith for Git 1.8.2:
	  yum install gettext-devel expat-devel curl-devel zlib-devel openssl-devel
	  cd /usr/local/src
	  wget https://www.kernel.org/pub/software/scm/git/git-1.9.2.tar.gz
	  tar xzvf git-1.9.2.tar.gz
	  cd git-1.9.2
	  make prefix=/usr/local all
	  make prefix=/usr/local install
        
But I got an error saying something like 'Can't locate ExtUtils/MakeMaker.pm'.
Shoot!
Google to my rescue I found a great post on Mad Coder's Blog with the following advice:
	  yum install perl-devel
        
Now I ran the last two make commands again and I was fine.
	  make prefix=/usr/local all
	  make prefix=/usr/local install
        

Primefaces DataTables with in table editing (row mode) and single selection

Select rows via mouse clicks in Primefaces DataTables while in row edit mode

We use Primefaces DataTables with in table editing in row edit mode and single selection mode.
<p:dataTable id="..." var="..." value="..." rowKey="..."
    selection="..." selectionMode="single" editable="true">

	<p:column headerText="Options" style="width:50px">
        <p:rowEditor />  
    </p:column>
        			
    <p:column headerText="...">
        <p:cellEditor>
            <f:facet name="output">
                <h:outputText value="..." />
            </f:facet>
            <f:facet name="input">
                <p:inputText value="..." label="..."/>
            </f:facet>
        </p:cellEditor>
    </p:column>

    ...
</p:dataTable>
        
But we faced some problems with the row selection via mouse click in a row.
In columns with cellEditors it worked quite poorly.
The reason of this poor behaviour lies in the Primefaces JavaScript code
It does not process the clicks on cells with cell editors, because these cells contains a "div", which are not recognized by the "onRowClick" method of the DataTable object.
To see this you have to create a Primefaces jar with non minified JavaScript code as explained in a great blog post from Rudy De Busscher.
Armored with this and a Firebug it's easy to find that in
META-INF/resources/primefaces/primefaces.js
the div-element, which is used in the columns with cell editors, is blocked in the 'onRowClick' method of the DataTable:
            if($(event.target).is('td,span:not(.ui-c)) {
                ...
            }
        
Just add it an you are fine.
            if($(event.target).is('td,span:not(.ui-c),div.ui-cell-editor-output')) {
                ...
            }
        

Lost in the Git Orcus (Part 3)

Now with packs!

--amending my last post, I changed the script to search for lost files in the git dungeon.
It now searches all packed objects too (again based on stackoverflow.com from willkil)
The parameters have not changed. See my last post for a short description. You can find the script on GitHub.
There is also an even smaller script, which gets you rid of all the branches the search script may have created.
(Btw.: I changed the hashbang from /opt/local/bin/perl (OS X) to /usr/bin/perl (Linux). You may change it to what fits for you.)
#!/usr/bin/perl

my $type = $ARGV[0]; # 'tree' or 'blob'?
my $pattern = $ARGV[1]; # filename to search for as regex
my $createBranches = $ARGV[2]; # 'y' if you want to create branches (only when search for 'tree')

##################################################################
# find all objects (blobs, trees, commits, tags) in .git/objects
##################################################################

my %AllSha1;

# scan the packed and non-packed files
my @AllFiles = `find .git/objects/`;
for my $f (@AllFiles) {
	if($f =~ /([0-9a-f][0-9a-f])\/([0-9a-f]{38})/) {
        # non-packed
		my $sha1 = $1 . $2;
		$AllSha1{$sha1} = 1;
	}
	elsif($f =~ /idx$/) {
	    # packed 
        my @IndexContent = `git show-index < $f`;
        for my $indexLine (@IndexContent) {
            my @IndexLineParts = split(/ /, $indexLine);
            my $sha1 = $IndexLineParts[1];
    		$AllSha1{$sha1} = 1;
        }
	}
}

##################################################################
# find all trees or blobs containing the pattern
##################################################################

my $ctr = 0;
for my $foundSha1 (keys %AllSha1) {
	chomp $foundSha1;
	next if length($foundSha1) == 0;
	my $t = `git cat-file -t $foundSha1`;
	chomp $t;

	if($t eq $type) {

		my @Lines = `git cat-file -p $foundSha1`;
		for my $line (@Lines) {
			if($line =~ /$pattern/) {
				$ctr++;
				printf "found $type: %s\n", $foundSha1;
				if($type eq 'tree' && $createBranches eq 'y') {
					my $branchName = sprintf "found/%03s", $ctr;
					printf "created branch: %s\n", $branchName;
					my $commitSha1 = `git commit-tree $foundSha1 -m "found $pattern"`;
					`git branch $branchName $commitSha1`;
				}
				last;
			}
		}
	}
}
        

Lost in the Git Orcus (Part 2)

UPDATE: There is a new post about a much improved version of this script: Lost in the Git Orcus (Part 3)

Find lost files deep deep in the catacombs of Git

Last year I posted a script to find lost files deep in the .git/objects folder.
But the way I chose was not the smartest:
It scanned all tree objects for a given file name (or pattern) and searched for commits pointing to this tree.
But since only the root tree has a commit pointing to it the script could only find files in the root folder.

That was dumb from my side. So I fixed it and made it much simpler:

  • It searches for trees or blobs containing the given pattern (it could also search for commits or tags if you wanted to)
  • It it finds a blob it just logs it out
  • If it finds a tree it creates a commit pointing to it via 'git commit-tree' and a branch pointing to this tree
Searching for the contents of blobs may be necessary. E.g. if the file you are searching for never made it into a commit, but was part of the index (and therefore could be somewhere in the object store if the gc has not already removed it).

The script

The script has 3 parameters:
  1. The object type to search in. Can be 'tree', 'blob', 'tag' or 'commit'
  2. The pattern to search for
  3. 'y' if you want to create commits and branches (only when type='tree')
The script is super simple, has no bells and zero whistles. So feel free to --amend it.
You can also find it on Github (in its newest version)

Possible improvements

Galore!
Just some examples:
  • Make it more convenient: Use options, print a help text, ...
  • Search also in the pack file
  • To make it faster: Search at first in the reflog of the HEAD and the branches
  • ...
I will implement the second bullet above soon. Stay tuned!
#!/opt/local/bin/perl

my $type = $ARGV[0]; # 'tree' or 'blob'?
my $pattern = $ARGV[1]; # filename to search for as regex
my $createBranches = $ARGV[2]; # 'y' if you want to create branches (only when search for 'tree')

##################################################################
# find all objects (blobs, trees, commits, tags) in .git/objects
##################################################################

my @AllFiles = `find .git/objects/`;
my @AllSha1 = ();

for my $object (@AllFiles) {
	if($object =~ /([0-9a-f][0-9a-f])\/([0-9a-f]{38})/) {
		my $sha1 = $1 . $2;
		push(@AllSha1, $sha1);
	}
}

##################################################################
# find all trees or blobs containing the pattern
##################################################################

my $ctr = 0;
for my $foundSha1 (@AllSha1) {
	chomp $foundSha1;
	my $t = `git cat-file -t $foundSha1`;
	chomp $t;

	if($t eq $type) {

		my @Lines = `git cat-file -p $foundSha1`;
		for my $line (@Lines) {
			if($line =~ /$pattern/) {
				$ctr++;
				printf "found $type: %s\n", $foundSha1;
				if($type eq 'tree' && $createBranches eq 'y') {
					my $branchName = sprintf "found/%03s", $ctr;
					printf "created branch: %s\n", $branchName;
					`git commit-tree $foundSha1 -m "found $pattern" | xargs -I{} git branch $branchName {}`;
				}
				break;
			}
		}
	}
}
        

CDI and Generic Reflection

Recently I tried to solve a problem regarding CDI.
Let me explain:

The Situation

There are interfaces extending a base interface:

    public interface BaseInterface {
    ...
    }

    public interface InterfaceA extends BaseInterface {
    ...
    }

    public interface InterfaceB extends BaseInterface {
    ...
    }

    // and many more

    public interface InterfaceX extends BaseInterface {
    ...
    }

Now I want a CDI producer injecting proxies for any sub-interface of the BaseInterface
To let the producer find its @Injects I define a @Qualifier.
Something like this:

    @Qualifier
    public @interface ProxyProducer {
    }

    ...

    public class Consumer {

        @Inject
        @ProxyProducer
        InterfaceA proxyForInterfaceA;

        @Inject
        @ProxyProducer
        InterfaceB proxyForInterfaceB;

        ...
    }

    ...

    public class Producer {

        @Produces
        @ProxyProducer
        BaseInterface produceProxy(InjectionPoint ip) {
            Class injectionPointClass = (Class) ip.getType();
            proxy = createDynamicProxy(injectionPointClass);
            return proxy;
        }

        BaseInterface createDynamicProxy(Class interfaceClass) {
            // create and return dynamic proxy
        }
    }


The Problem

Too bad! It does not work.
Producer and consumer will not find each other.
Even the @ProxyProducer qualifier does not convince the CDI container to match producer and injection point.

The Solution (at least the best I've found yet)

I saw this Stackoverflow about reading generic type parameters via reflection and came to the following solution:.
The BaseInterface gets as a generic parameter its own sub interfaces:
    public interface BaseInterface<T extends BaseInterface> {
    ...
    }

    public interface InterfaceA extends BaseInterface<InterfaceA> {
    ...
    }

    public interface InterfaceB extends BaseInterface<InterfaceB> {
    ...
    }

    ...
The @Inject attributes are defined as a BaseInterface with the sub interface we need the proxy for as the generic parameter.
    public class Consumer {

    @Inject
    @ProxyProducer
    BaseInterface<InterfaceA> proxyForInterfaceA;

    @Inject
    @ProxyProducer
    BaseInterface<InterfaceB> proxyForInterfaceB;

    ...
    }
Now the producer can read the type parameter and create a proxy for it:
    public class Producer {

        @Produces
        @ProxyProducer
        BaseInterface produceProxy(InjectionPoint ip) {
            Class<?> injectionPointClass = (Class<?>) ip.getType();
            Class<?> interfaceClassToCreateProxyFor =
                (Class<?>) ((ParameterizedType) injectionPointClass.getGenericSuperclass()).getActualTypeArguments()[0];

            proxy = createDynamicProxy(interfaceToCreateProxyFor);
            return proxy;
        }

        BaseInterface createDynamicProxy(Class interfaceClass) {
            // create and return dynamic proxy
        }
    }

Since producer and injection point are now of the same type BaseInterface the CDI container will match them together.

If anybody has a better solution please let me know.

Lost in the Git Orcus

UPDATE: There is a new post about a much improved version of this script: Lost in the Git Orcus (Part 3)

The Problem

Recently I lost a file in the Git orcus (aka './git/objects').
I knew it had been there some time ago.
But now it was gone and the Git on-board tools ('rev-list', 'fsck', 'reflog', ...) didn't help.
They showed a lot of dangling commits, trees and blobs but not the file I was searching for.

The Solution (maybe not the best)

I was doomed to dive into the .git/object-slough.
Based on a shell script on stackoverflow.com from willkil
I created a small Perl script:
  • It has one command line argument: the file to search for (as a regex).
  • In the first phase it looks into each tree object and checks whether it contains the file.
  • In the second phase it looks into each commit object and checks whether it points to one of the tree objects found in phase 1.
  • At last it creates a branch ('found/0', 'found/1', ...) for each commit found in phase 2.
  • It does not look into packed objects.
Here is the script:

#!/opt/local/bin/perl

my $pattern = $ARGV[0]; # filename to search for as regex

##################################################################
# find all objects (blobs, trees, commits, tags) in .git/objects
##################################################################

my @AllFiles = `find .git/objects/`;
my @AllSha1 = ();

for my $object (@AllFiles) {
	if($object =~ /([0-9a-f][0-9a-f])\/([0-9a-f]{38})/) {
		my $sha1 = $1 . $2;
		push(@AllSha1, $sha1);
	}
}

##################################################################
# find all trees containing the file
##################################################################

my @FoundTrees = ();

for my $treeSha1 (@AllSha1) {
	chomp $treeSha1;
	my $type = `git cat-file -t $treeSha1`;
	chomp $type;

	if($type eq "tree") {

		my @Lines = `git cat-file -p $treeSha1`;
		for my $line (@Lines) {
			if($line =~ /$pattern/) {
				printf "found tree: %s\n", $treeSha1;
				push(@FoundTrees, $treeSha1);
				break;
			}
		}
	}
}

##################################################################
# find all commits pointing to one of the trees found above
##################################################################

my @FoundCommits = ();

for my $commitSha1 (@AllSha1) {
	chomp $commitSha1;
	my $type = `git cat-file -t $commitSha1`;
	chomp $type;

	if($type eq "commit") {

		my @Lines = `git cat-file -p $commitSha1`;
		for my $line (@Lines) {
			for my $foundTreeSha1 (@FoundTrees) {
				if($line =~ /$foundTreeSha1/) {
					printf "found commit: %s\n", $commitSha1;
					push(@FoundCommits, $commitSha1);
					break;
				}
			}
		}
	}
}

##################################################################
# create a branch for each commit found
##################################################################

my $i = 0;
for my $foundSha1 (@FoundCommits) {
	my $branchName = "found/" . $i;
	`git branch $branchName $foundSha1`;
	printf "branch created: %s pointing to %s\n", $branchName, $foundSha1;
	$i++;
}


  • Be aware! This script creates a branch for each commit to a tree with the file you're searching for. Could be some!!!
  • Possible improvement: Only create a branch for the most recent commit (or track the chain of commits and search for the head of it)

The Question

Isn't there an easier way? Let me know!