Friday, January 29, 2021

Having fun with bzip2

  bzip2, an standard compression utility in Linux, Mac and friends has a very efficient compression ratio for low entropy files. I just tested to compress a big 89Gigabytes "all-white-spaces" file. The final compressed size was about 0.7Megabtyes, with a compression ratio of about x130.000. This is not very impressive from a mathematical point of view, since all the information could be packed in just 6 few bytes (a single byte for the white space plus 5 more bytes for the total size or around 16.000 million compression ratio). But the important thing is that bzip2 packs data in an standard format, and by just looking at the bz2 extensions, many software knows what to do with it.


 Now the funny part. 89 Gigabytes is much more that the storage capacity of most old/unattended servers and low end cloud servers, that curiously, are the main target of worms infecting the Internet. I have a personal web server and it is a bit frustrating checking that around 99% of visits are (were) attacks trying to find holes in some WordPress, php services that could be installed on the machine or just trying good luck searching for passwords files and crypto wallets.


 I was wondering what would happen if I uploaded my compressed 0.7Megabyte bz2 file, renamed it as "password.bz2", and redirected visits like /login, /wp-content, /backup, /administrator, /back/wallet.dat to it. The preliminary results looks to indicate that Internet worms like to download the bz2 file, but then they have some problems to "digest" the uncompressed 89 GB file. One day after installing the file, "non-polite" visits decreased to just 60% (from 95%+ one day before). Two days later, they just represented 40%. With some more tuning for forward-rules I guess results can improve.

Thursday, July 27, 2017

TXT rocks!

I've been involved in an open-source project for the last year or so called Interledger (The Internet of Ledgers).

Keeping up with the project progress is not an easy task since it's in active development and new ideas surge every week, interfaces change and many people work in parallel with different targets and perspectives. To make it more difficult most of the project is developed by the internal staff of Ripple, which I'm not part of, so getting out of sync is even easier. And to scale to new levels of difficulty, the Ripple guys have to keep the pace with all the fast-moving environment around them (block-chains, side-chains, banks, regulations,  ...) and some code like routing payments requires lot of research before getting stable (just notice that routing protocols in the Internet Protocol is still a work in progress decades later). Not happy with that, the time I can dedicate to it is just plain random.

There has been no few efforts to document everything around the project, with great progress to formalize around RFCs, but in such fast-moving development context documentation is always behind the code and still really needed to keep going.

I just noticed that keeping docs up to date with code would be a titans-work so I thought about an alternative. What about trying to group related info as close as possible and let our brain link the info into something that make our neurons work?
I needed something that visually could match related topics close to each other and simultaneously link to external links, as well as providing "goodies" for formatting text, tables and some minimal active tools help navigate more easily.
Since this is a software project I also wanted a clear distinction between the separate the different software cycle scenarios (documentation, development, testing, deployment,...)

I tried with different tools (CMS, Google Drive, ...) until I noticed that the best tool at hand was no other than plain TXT (with some spots of Javascript).


The result is available at:

https://earizon.github.io/txt_world_domination/.

(Update: 2023-02: the previous HTML version has been upgraded with the even lighter version using just TXT)

Saturday, January 21, 2017

A weekend theory about evolution of mammals. When the frog turned into a prince (and much more)

Many theories and hypothesis arise about where first mammals came from.

The general accepted main-stream theory claims that mammals evolved from reptilians and that reptilians, in turn, evolved from amphibians.

This blog post presents an alternative theory better matching many experimental facts.
I will try to convince the reader that "mammals evolved directly from amphibians, and the first mammal to arise in planet Earth was no other than a tiny 'not so cute' bat"
First of all, a warning. The reader might be convinced that the established theories about the evolution of mammals are beyond any doubt or dispute. Absolute truths set in stone, similar to Newton's laws in classical mechanics or the Dirac equation for relativistic quantum fields.
Nothing could be further from the truth. We know for certain that evolution is real, but the sequence of events that led from one species to another is based on evidence with little scientific rigor. Not because scientists lack rigor, but because of the limited tools and resources available to them.
A few bones hidden underground for thousands or millions of years and carbon-14 dating are all the available tools.
Add to this the fact that paleontology is not a science of great interest to industry, and so with scarce fundings.

Only museum exhibitions, some occasional Hollywood movie about dinosaurs, and some optimistic and curious researcher in a dimly lit room sustent this area of reseach.
Big mistakes and pitfalls are the rule and advances "accidental".:
Today we know that dinosaurs were covered in feathers, but for decades this was not the case.
More notably is the recent discovery that placental mammals, which for over a century were considered "incomplete" mammals, are actually "evolved" mammals (Females evolved to be able to abandon the gestating offspring in case of an attack by a predator, so that they could at least have a new opportunity in the future.).
**Theories about evolution cannot be replicated in a laboratory**. We only have a few samples buried millions of years ago underground. We cannot repeat millions of years of random evolution of species that we don't even know existed under habitat conditions that we can only guess at. In this sense, it is more like theorical work on the String theory used to unify Quantum Theory and Einstein's curved space ("gravity"). We do not have a laboratory to test it, and no matter how exact and precise theoretical physics is, even the brightest theorists end up lost in a sea of doubts. Perhaps it is just a crazy theory, and the correct explanation will come from a theory of quantum gravity loops. Without a laboratory to confirm the theory, we are only talking about more or less intelligent assumptions. (even if theorical physicists counts with many more tools, funds and budgets than paleontologists!!)
Today we know there was a mass extinction of dinosaurs due to the impact of a large meteorite, but for decades, it wasn't even clear if it was due to a meteorite, an epidemic, invasive mammals, or an ice age. Again, the fortuitous discovery of the remains of a large crater in Chicxulub, Yucatán, provided the definitive clue. If this crater had been hidden underwater, NASA satellites would not have been able to locate it, and we would still be lost in a pit of mystery.
Now, let's come back to the theory of bats as the first specie of mammals in Planet Earth. Where this arbitrary claim come from?. Do I have some rests of bones or some DNA analysis to probe it?. Of course, not. To arrive to it I just support myself in spots of deductive and inductive reasoning and starting with some evidence nobody will deny.

Simply put: "Bats fly!".

It could look a curiosity at first sight, but a very weird one. It's weird because there is no doubt than flying is something hard. Flying is difficult, very difficult. Flying requires lot of energy, lot of changes in the brain and lot of physiological changes in the body of a bat. It's also weird, extremely weird that bats are the only mammals that can fly.

Bats are closely related to rodents and in particular to their mouse cousins, up to the point that is quite normal to associate bats to flying mouses (at least for all of us not working in a Museum or Research Center). This is where some deductive reasoning takes place.

Darwin's theory of evolution explains how living beings evolve through *small changes*. Random *small changes* in the ADN provides some *adaptive advantage* that makes the new specie to survive. The words *small changes* and *adaptive advantage* are highlighted because here is where things starts to fail with the current theories:

 According to established theories bats evolve from rodents but this is very hard to explain with Darwin's theory of evolution. There is no small change that suddenly allows a mouse to start flying. There is no single change in the ADN that magically lets a rodent fly. Even if magically a mouse would be born with wings, its brain would not be adapted to flying. Even if magically a mouse would be born with wings and also magically its brain would change to let him fly its digestive system will not be adapted to consume all the energy needed to fly. Even if magically a mouse would be born with wings, with an adapted brain and a digestive system allowing it to fly, it will need changes to its breathing system, and some sort of mechanism not to loose heat throught its wings, and many other adaptations just because as already said, flying is hard to achieve, even for human engineers designing an airplane it's very, very complex (and humans count with the advantage of being able to burn tons of petrol to make an airplane fly, something forbidden to living beings).

Could it be the case that through thousands or hundreds of thousands or millions of years some species of  rodents could evolve through small changes until, at some point, they were able to fly?

  The problem with that hypothesis is that it goes directly against Darwin's theory of evolution.  All the *small changes* required for a bat to fly provide no *adaptive advantage* until such a bat actually flies. Quite the opposite a mouse with "big wings" but unable to fly will be doomed to die. It will not be able to move and will loose heat very fast. This is exactly the same for many other adaptive changes.

And so, if the evolutionary step driving from rodents to bats are hardly difficult to explain, what about the opposite? What if rodents evolved from bats?

Curiously this question is much easier to defend while respecting Darwin's theory of evolution of species. Maybe just at some point the bat's wings started to become atrophied or the bat augmented its weight or its metabolism didn't allow them to consume as much energy as needed to keep flying. Not being able to fly will be a disadvantage that could be *immediately*  be compensated by the fact that such a bat will waste much less energy by just "walking". This is something we have already observed in birds and specially in the now famous Albatross in the Galapagos Islands.

So let's assume the arrow of time moved forward from bats to rodents. What then? Where do bats came from, if not from rodents? What other mammal could evolve to the point of creating such curious flying mammal? They easy answer is:  NONE. 
The same arguments that lead us to the conclusion that rodents can't be the parents of bat would apply to any other mammal.

There is no such mammal. Bats are actually the first mammals living in Planet Earth.

Who was them the parent of first bats? Well, I have not a answer to this question. My time machine to travel 50 millions back in time and check for a definitive answer broke last week. Intuitions tells me that, with (high?) probability, some sort of flying frog were the direct ancestors of bats. I base this hyphotesis on the next matches:

- Both frogs and bats emit sound and they do with similar patterns (note: this claim was written around 2017, check for updates later on a few years a few paragraphs down for key discoveries around this). No other amphibian or reptilians have such a feature. Emitting sound as frogs and bats do require important changes and new "modules" in the brain to be able to control it.   This is an extremely sound coincidence for such small primitive creatures with small brains and in fact the audible sound emitted by bats resembles to a certain point to that of frogs (https://www.youtube.com/watch?v=ppLsu5Z2Np0)
- In general both species are much more active during the night.
- The physical appearance of flying frogs and bats have many coincidences, specially their "hypertrophied" hands-wings.
- Both have insects as main source of proteins.
- Size and weight match.

To hypothesize that a flying frog could at some point be able to "just fly" is not hard to believe and there are adaptive advantages in passing more and more time flying. It could be that at some point this flying frog could pass most of the time flying. This would trigger many fast evolutionary steps. It will first allow that flying amphibian to traverse many distances in search of food or just escape from predators with easy favoring their flying skills. Its lungs will grow fast to allow to breath more oxygen from the air and pass more time flying. Greater capacity to absorve great quantities of oxygen from air will quickly favor warm-blooded metabolism (Curiously the other warm-blooded species in animal kingdom apart from mammals are birds who also fly). With wam-blooded metabolism, carrying the foetus inside protected will provide another adaptive adavantage.

The animal's fur would protect it from the wind. At some point this flying frog changed and a first mammal, a primitive bat, was born!.



If a theory is to be taken seriously it must also have some predictive power. Let's examine what this theory can predict:

- If bats were actually the first mammals on Earth there must be many different subspecies of them after so many years of evolution. This is in fact true, and as today bats is the second more diversified specie in the mammal kingdom living in all sort of climates and places. Curiously they are only surpassed by rodents, that will be nothing more than adapted bats.

- If bats were actually the first mammals there must exists fossils where no other o very few other species of mammal actually exists. This is actually true, and fossils of bats have been found in places where other mammals were difficult to find.

- If all mammals come from bats there must be some trace easy to identify. This is not so evident, but in fact bats needs lot of brain power to control their wings. Curiously bats wings are nothing more than hands in newer mammals, and curiously many mammals have extraordinary skills to control their hands than no other terrestrial specie do have. Mammals brain also have a great power to understand the world in "three dimensions", something that could have appeared while bats learned to move in three dimensions.


And finally, as a gift for curious researches with no plans for the weekend, this is a non-yet-proved predictive fact of this theory. It's well known that bats use sound to localize and hunt insects. My hypothesis is that some (or many) species of frogs could be using that same mechanism to localize insects, and not just as a way for males to get the attention of females. It's even possible that they will be using the same frequencies and we were not noticing it just because we didn't even thought about it. The inflated vocal sac of the frog, full of sensory nerves, can be a very good tool to detect the echo of the croaking just put your hands in an inflated balloon to feel the sound with the touch.
Could it be that the bat's wings (their fingers with big membranes full of sensity nerves) are also used as part of their echolocalization system? I guess this is the case. Why settle just for the ears, when their finger-wings are some excellent parabollic (aka "directional") antennas.

Update 1, 2017-08-09: 
I'm enjoying summer's holidays now. Time for beach and caipirinhas in the sunny coast.... or even better, time for updating my theory on bats and mammals evolution.
I just landed by pure chance to a web page with a complete collection of bat-faces. The first thing that anyone will notice is how many distinct bat faces can be. But more interestingly and related to this post is the fact that many of those faces resemble many other different branches of mammals. Some fruit-bats clearly resemble to a lemur, an sub-specie of primate, that curiously have the same feeding habits that the bat it resembles to.
Please, I'm a bat! not a lemur


Then we have the Hammer-headed bat whose aspect is quite close to a primitive ruminant and again, another "random" coincidence, I read that those species of male bats  "possesses an enormous head for producing loud honking calls" like ruminants, and that they live in zones of Africa that match those of African ruminants with similar lek mating habits !!!

Why not speaking about the naked buldog bat, whose movements resemble those of a feline. Again new coincidences. Those naked bats are typical of Asia, where the first skulls of felines were found.

The face difference between some other bats and hedgehog (who are also insectivore) are hardly to distinguish.

In conclusion, we have a family of mammals, the bats, that share many physiological and behavioral characteristics with many other family of mammals (primates, ruminants, felines, rodents), with little resemblance between them. This point outs to bats as common denominator (or in evolution terms, as the root of evolution for mammals).

Update 2, 2017-08-09:
I also read on page 67 of this book that "the earliest known fossil of a primitive bat, an insectivorous species from the Eocene period was found in America. Bats had certainly existed for the previous 50 million or more years, but their evolutionary history is poorly known since their small, fragile skeletons do not lend themselves well to fossilization". This "fragile skeletons" explanation is difficult to sustain, considering that fossils for much more fragile structures have been found, even for bacteria.
I have a much simpler explanation. Fossils were in fact found, but they were confused with those of an amphibian (a frog or similar), since by just looking at the skeleton it would be impossible to know whether it was still a "frog" or a primitive "mammal".


Update 2, 2021-12-30:
More than 4 year ago I predicted that if bats had evolved from frogs it could also be possible for some type of frog to be using sounds to hunt their preys. Today I just got aware of this link speaking about a weird Torrent frog, able to listen sounds in the 128 kHz ultrasonic frequency, raising the question of whether frogs might use ultrasonics for echolocation, the method bats and dolphins use to find their way around.
Digging a little bit further I found this other link where it is written """(Torrent frog) Males have ear canals with recessed tympanic membranes at the end of the canals, like mammals but unlike all other anurans except for Huia cavitympanum (Feng et al. 2002). """ (yet another curious coincidence with mammals), ...
"Vomerine teeth are present " (like in bats),
...

Update 3, 2024-04-21:
Yet more "matches". A new article published by Ubiratã Ferreira Souza, Guilherme Augusto-Alves, Mariana Retuci Pontes, Lucas Machado Botelho, Edélcio Muscat & Luís Felipe Toledo, mention the discovery of a frog using ultrasounds as a defensive strategy. My guess is that such frog is just hunting "a la bat".

Update 4, 2025-05-03:
An article was recently published in the Proceedings of the Royal Society by Logan S. James, M. Teague O'Mara, Justin C. Touchon, Michael J. Ryan, Ximena E. Bernal and Rachel A. Page titled "The ontogeny of decision-making in an eavesdropping predator". They present their findings of fringe-lipped bats (Trachops cirrhosus) capacity to detect the acoustic advertisement calls of co-occurring anurans (frogs and toads!!!). Bats are able to learn, through the time, to detect the type of frog and choose to attach to palatalbe frogs while rejecting poisonous toads, based on the type of sound or acoustic cues emitted. The results offer the first evidence of developmental changes refining decision-making in an eavesdropping predator in the wild. "It's truly remarkable that these bats hunt using the calls of an entirely different group of animals (frogs) in the first place, and we have wondered for a long time how these bats acquire this unusual skill," said Logan James, STRI postdoctoral researcher and lead author of the study.
... (A little bit less remarkable after reading this blog post).

Saturday, October 22, 2016

Energy saving issues with Lubuntu (and how to fix it with powertop)

I'm a big fan of Lubuntu (Light Ubuntu), the Ubuntu without all bloated software since, on average, it saves up to 1 or 1.5 Gigas or RAM when compared to standard Ubuntu will of the fancy (and useless) 3D effects.

Something that annoys me anyway is that the default setup in Lubuntu (I ignore if that's the case in Ubuntu) is quite energy-hungry.

I use a Dell XPS 13 laptop equiped with brand new hardware that "theoretically" must work in silence most of the time, but when I just boot up Lubuntu and a couple of apps (Firefox, Eclipse) the fan starts to run at max speed.

The easy (patch) solution is to run next command:

sudo powertop

then go to the "Tunables" tab, and switch all from "Bad" to "Good", except most probably for the USB keyboard and mouse and the wifi or ethernet. (For those really concerned with the integrity of their HD data, don't swith also al SATA related stuff).

Actually, activating the power saving for the PCI Intel Core processor Graphics Controller is usually "good enough" to make the fan settle down, but switching on all the others makes no harm and our computer will be happier with us (don't forget that sooner than later IA equiped macro-computers will punish those poor humans that through the years tortured their indefense CPUs, so it's better to get friends as soon as possible before it's too late).

Friday, December 4, 2015

Swift got it closer, but still fails

Continuing my religious and long war against null beings.

I just read about Swift improvements to avoid null pointers. In Swift a variable can not be assigned a null (nil in Swift nomenclature) unless it's declared optional. And this nil is actually an object of a defined type with a presence in memory, not a pointer to a forbidden memory address (0 in practice).

Still, while Apple's guys got closer to a solution, they didn't get the point.While the solution proposed by Swift fixed the Null pointer exception, it doesn't fix all the semantic inconsistencies of using Nulls. A nil object in Swift is still something empty of information, and so the "information lost" is still present.

The solution to fix the problem was much, much simpler and much, much more effective:

- DO NOT ALLOW NULL VALUES IN THE LANGUAGE.
- FORCE THE DEVELOPER TO USE SENSIBLE DEFAULT VALUES OR RAISE AND EXCEPTION IF THAT'S NOT POSSIBLE!!!

See more about it http://chuletario.blogspot.com.es/2011/05/kill-null-killen-all.html).

Tuesday, June 30, 2015

Downloading youtube Videos with VLC (command line)


Ladies and gentlemen, we present you the fast and easy way to download Youtube videos using VLC and a shell script:

The script:

  # INPUT is the URL as seen in the browser
  INPUT="https://www.youtube.com/watch?v=...."
  
  # OUTPUT is any arbitrary file.
  OUTPUT="200-UpdatingApplication.mp4"
  
  vlc --intf dummy "${INPUT}" --sout=file/ts:${OUTPUT} vlc://quit


A problem appears if there are many related videos to download (for example a 50 video tutorial).
 Using Firefox I just select them all on the "right column" (related videos), right-click to select "see source code selected" and then clean the html to let only the input URL and the video title. 

Then a few Vim macros is all that needed to convert them in a shell script.

World Domination is an step closer now!

Tuesday, January 20, 2015

Science is not Politics


“Let’s be clear: the work of science has nothing whatever to do with consensus. Consensus is the business of politics. Science, on the contrary, requires only one investigator who happens to be right, which means that he or she has results that are verifiable by reference to the real world. In science consensus is irrelevant. What is relevant is reproducible results.” – Michael Crichton

Looks unfortunate that most software developers have forgot this point.
Many modern programming languages just try to reach a consensus instead of doing things right. Let's observe how Javascript, the most widely used language today still keeps "null" and "nondefined" types around even if science says they must be dropped (backward compatibility is just an excuse, not a reason).

(Edit 2015/02/13: ECMAScript 5 Strict Mode will throw a ReferenceError when trying to evaluate a non-existing variable). 

Thursday, December 11, 2014

Is that good or bad?

This is the type of achievement to hide in a CV :(

Edit (2015-01-05): New hit on Stackoverflow!

Friday, December 5, 2014

Obfuscating Python code


WARNING!!!:
Obfuscating code is probably a bad idea. It can have unpredicted consequences. Think twice before continuing


The script:
Next shell script will serve as reference to obfuscate Python code by compiling original files to .pyo while hiding the original source from py files.


#!/bin/sh
# DIR_L: directory list (module list)

DIR_L="pythonModule1 pythonModule2 pythonModule3"

CWD=`pwd`
for dirA in ${DIR_L}; do
    cd ${CWD}/${dirA}
    rm -f *pyc *pyo
    python -OO -m compileall .
    ls *py | while read f ; do
        # Create empty "file".py with same modification time
        #
that tmp (the renamed original "file".py used to
        # create the pyo file)
        mv $f tmp && touch -r tmp $f && rm tmp
    done
done



Explanation:
 Python will *always* compare the modification date of the *py file with the one hardcoded in the *pyo object. If it doesn't match, the pyo will be recreated.
Creating a pyo file and then removing the code in the original *py file will not work since once the code is removed (echo -n "" > myfile.py) the modification date is updated. Next run will update the pyo file from the empty py file.
 Removing the py file leaving only the pyo file will not work either, since python will ignore the pyo file if the matching py file is not present.

The quick-and-easy solution then is to use "touch" with the -r option. This combination will create an empty file and update the creation/modification timestamp of the new file taking as reference the file passed to "-r".  Since moving a file doesn't modify its modification timestamp a line similar to:

  mv myfile.py tmp && touch -r tmp myfile.py && rm tmp 

will create the empty myfile.py with a modification timestamp matching that of the myfile.pyo (created previously using python -OO -m compileall .)

While not shown in the script it's pretty clear that we must be working with a copy of the original sources. Otherwise they will be lost after obfuscation. Is up to the reader to choose its favourite way to do the copy. As a hint I use something like the next one-liner:

tar -C src_dir -cf - * | tar -C working_dir -xf -

Alternatives:
pyminifier  provides utilities to minify, obfuscate and compress Python code as well as a Python API to use it inside other Python code. Unfortunately in my own tests it was buggy with many cryptic errors about missing modules.

Notes:
touch is just available on UNIX-POSIX friendly systems. Probably it will also work on Windows with the help of cygwin, but it's not tested at all (and it will never be!).


Thursday, May 29, 2014

How much time does it takes to scan the entire Internet?

One week?, One month?


Extracted from https://github.com/robertdavidgraham/masscan

"This is the fastest Internet port scanner. It can scan the entire Internet in under 6 minutes, transmitting 10 million packets per second."

All you need is some good idea to start hacking the Internet and a 10Gbit/s symmetric link. Just ask your local carrier about it.


Sunday, May 4, 2014

Spontaneus symetry breaking of prime numbers.



Let's imagine for a moment that we start adding "+1" for each natural number. Whenever we reach a prime number we switch the sum from "+1" to "-1".  If prime numbers are randomly distributed we expect the total sum to oscillate around 0.
Take for example the first 20 numbers (in bold prime numbers, where we start switching back):

                                        | Total
    3       3                           |
  2   2   2   2                         |
1       1       1       1               |
------------------0---0---0--------------
                   -1      -1      -1   |
                             -2  -2  -2 |
                               -3       |
                                        |
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 |
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 |
    *   *   *       *   *       *   *   |



 Let's see what we get in practice.


Next python code simulate the previous process/algorithm/"thing":


  1 def isprime(n):
  2     n*=1.0
  3     if n%2==0 and n!=2 or n%3==0 and n!=3:
  4         return False
  5     for b in range(1,int((n**0.5+1)/6.0+1)):
  6         if n%(6*b-1)==0:
  7             return False
  8         if n %(6*b+1)==0:
  9            return False
 10     return True
 11
 12 START=1
 13 total=0
 14 sum = -1
 15 for END in xrange(5000000,30000001,5000000):
 16     totalNeg=0
 17     totalPos=0
 18        
 19     for i in xrange(START, END):
 20         total = total + sum
 21         if total > 0:
 22             totalPos += 1
 23         if total < 0:
 24             totalNeg += 1
 25         if isprime(i):
 26             sum  = -1 * sum
 27     START = END+1
 28    
 29     rat = totalPos*1./totalNeg
 30     if rat > 1:
 31        rat = 1./rat
 32     
 33     print total, total*1./END, totalPos, totalNeg, rat


Every 5000000 numbers we print some statistics (line 33).



In the program output, the first column prints the "total" variable, which shows the total sum at a given time. We expect such column to be evenly distributed between negative and positive numbers. The second column shows the ratio between the total sum and the current natural number, that we expect to be close to zero. The third column will show how many times the total sum was possitive, with the fourth column showing how many times it was negative, finally the fith column shows the ratio between the times the total sum was possitive and the time it was negative. We expect column 3 to be quite similar to column 4, and so fith column close to 1.


Let's see what our program shows in practice:

SUM    Current / SUM    
-1757  -0.00292833333333 90292  509554 0.177198

-3393  -0.00308454545455 90292 1009554 0.089437
-6197  -0.003873125      90292 1509554 0.059813
-9685  -0.0046119047619  90292 2009554 0.044931
-10401 -0.00400038461538 90292 2509554 0.035979


Not exactly the result I was waiting for. Intuition failed (as is always the case with prime numbers). The sum never oscillates and cross back to zero creating what scientifics will call an spontaneous break of symmetry.



Saturday, May 3, 2014

C++ or C--?


Copy&Paste from "Expert C programming, Deep secrets":

"If you think C++ is not overly complicated, just what is a protected abstract virtual base pure virtual private destructor, and when was the last time you needed one?"

In the mean time C is a great language with all its "buts" !

Update: 2015-03
Defective C++ is worth reading before adventuring into the C-- nightmare.

Wednesday, August 7, 2013

Asynchronous JS the easy way



The objective:
To be able to call MyWidget.redraw(onRedrawCallback,...) without worrying about the previous (initialization) state of our MyWidget instance.

The code:

  1 MyWidget = {
  2     template : false,
  3     myPreciousData : false,
  4     ...
  5     __load_template : function (url, dstVar, callback, callbackArgs)
  6     {
  7         ...
  8         onResponse : function (...) {
  9             if (callback) { callback(callbackArgs); }
 10         }
 11     },
 12     ...
 13     __get_data : function (callback, callbackArgs)
 14     {
 15         ...
 16         onResponse : function (...) {
 17             if (callback) { callback(callbackArgs); }
 18         }
 19     },
 20     ...
 21     redraw : function(callback, callbackArgs)
 22     {
 23         if (!MyWidget.template){
 24             MyWidget.__load_template( MY_TEMPLATE_URL , MyWidget.template, MyWidget.redraw /*"recursive*/ );
 25             return;
 26         }
 27         if (!MyWidget.myPreciousData){
 28             MyWidget.__get_data(MyWidget.redraw /*callback to our own function */, false, false);

 29             return;
 30         }
 31         if (! document.getElementById("myContainer") {
 32             MyWidget.__setUpContaier(MyWidget.redraw);

 33             return;
 34         }

 35         /* At this point all Object data (template, myPreciousData, container,...)
 36          * has been initialized. */
 37         ...
 38         if (callback) { callback(callbackArgs); }

 39     }...
 40 }
 41
 42 var postRedrawFunct = function (...) {
 43 }
 44
 45 }
 46 myGUIElment.onClick(MyWidget.redraw(postRedrawFunct, ...)); // Just call redraw.

Saturday, July 20, 2013

The war against bugs is not lost!


Extracted from "Professional Linux Kernel Architecture" (Wolfgang Mauerer):


For comparision of the CPU quality, here is the check_bugs routine of S390, Alpha, Extensa, H8300, v850, FRV, Blackfin, Cris, PA-RISC, and PPC64:

static void check_bugs(void)

The S390 kernel is among the most confident ones, as you can see in the following code:

include/asm-s390/bugs.h

static inline void check_busgs(void)
{
  /* s390 has no bugs ... */
}


Saturday, April 6, 2013

Emscripten: From C to Javascript.

From the emscripten wiki:

Emscripten is an LLVM to JavaScript compiler. It takes LLVM bitcode (which can be generated from C/C++ using Clang, or any other language that can be converted into LLVM bitcode) and compiles that into JavaScript, which can be run on the web (or anywhere else JavaScript can run).

Using Emscripten, you can

  • Compile C and C++ code into JavaScript and run that on the web 
  • Run code in languages like Python as well, by compiling CPython from C to JavaScript and interpreting code in that on the web

The list of ported C/C-- software is impresive. Even complex OpenGL software ports looks no problem for Emscripten (by translating to the equivalent WebGL).

Basically that means we can know use static compiled languages to generate complex (millions of lines of code) Web pages.

¡¡¡ And this technology works now !!!

 

Thursday, August 2, 2012

Defining a bash prompt similar to:
PS1="\u@\h\ [\$(git branch 2>/dev/null | grep ^\* | sed 's/\*/branch:/')]:\w\$ "
(where the blue text is the added extension to the existing Prompt -PS1 variable-) will automatically show on the prompt the active branch we are working on. Ex.:
earizon@desktop[branch: master]:~/myGitRepo$ git branch
* master
  branch1
  branch2
  branch3
earizon@desktop[branch: master]:~/myGitRepo$ git checkout branch2
Switched to branch 'branch2'
earizon@desktop[branch: branch2]:~/myGitRepo$ cd .. # <- exit git repo directory
earizon@desktop[]:~$ 

Saturday, July 21, 2012

Executing Firefox/Chrome as a restricted user in Ubuntu

Next follows a quick guide (aka, chuletario) to execute Firefox as an isolated user in Ubuntu (Probably will work with minor or none modifications in Fedora, Mandriva or even MacOSX). Executing as an isolated user will allow to protect (even more) our system from the risks of the Internet. A potencially dangerous remote attack using a flaw in our browser (or a flaw in the plugins installed in our browser or the application used to read mail attachements) will be minimized. A virus/worm/"whatever" will be blocked unless it manages not only to break the browser, but simultaneosly scale privileges using a flaw in our OS kernel (remember the maximum principle of security, "NO SYSTEM IS SECURE"). To protect our system just follow the next instructions:
  1. Create a new user with a command similar to:
    adduser internetBrowsing
    
  2. Using you favorite text editor (gedit, vim/gvim, nano, ...) write a script similar to the next one:
     
    #!/bin/bash
    xhost local:
    su -c "firefox 1>/dev/null 2>&1 &" internetBrowsing 
    
    xhost local: will allow local users access to the X session.
    Change 'firefox' by the name of your favorite browser (chrome, chromium-browser, opera, ...). (But don't forget that firefox is best than your favorite browser in such case :) ).
  3. Save it and mark it as executable by executing in a terminal:
    chmod u+x launchBrowser.sh
    
  4. Add our new user to the audio group to allow it access to sound card. Edit the file '/etc/group' (in a terminal execute
    sudo gedit /etc/group
    and add the new user internetBrowsing to the audio group. The /etc/group file must look similar to:
    cat /etc/group | grep firefox
    ...
    ...
    audio:x:29:pulse,internetBrowsing
    ...
    ...
    
    (WARN: Do not delete anything in this file, just add internetBrowsing to the audio group)
  5. Finally just execute the script in a terminal by typing:
    ./launchBrowser.sh
    
    or create a launcher in the desktop.

Saturday, January 7, 2012

The circle of observability

Source: http://www.youtube.com/watch?v=l7aQWoTRqKw

   +----->  PROFILING -----+       
   |         -top          |
   |         -oprofile     |
   |         -perf         |
   |                       |
   |     +---------+       |
   |     |SystemTap|       |
   |     +---------+       |
   |                       |
   |                       v
 DEBUGGING <------------- TRACING
  -gdb                    -strace
                          -ltrace
                          -ftrace