Archive for the 'Geeklife' Category

How to create a list that holds different object types using `void*` in C

Sunday, April 5th, 2015

I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out.

In this exercise I store elements of different types in a forward linked list.
In order to know what to dereference as I iterate through the list’s elements, I’ve put a “.type” field, which has an int value representing the type of the object stored.

The “.value” is simply a void*, which lets me store a pointer of any kind, and it works pretty well.

Here’s the code for your enjoyment, I hope this is useful to C apprentices.

The example shows how you can store native types like int, or more complex char* or even a struct person* (which is the more useful probably to your purposes)

It’s a good exercise to see the uses of the “address of” operator “&”, which is used to initialize pointers (the ‘&’ can also be used differently to create references, which I call in my mind as ‘aliases’, but this is not shown in this example)

I also play with a not so popular syntax to access a pointer’s sub-fields:

(*myPointer).structField == myPointer->structField

to teach you that the -> is a short hand for dereferencing a pointer and accessing one of its fields.

//                                                                                                                                                                                          
// An exercise to play with a struct that stores anything using a void* field.                                                                                                              
//                                                                                                                                                                                          

#include <stdio.h>

#define TRUE 1

int TYPE_INT = 0;
int TYPE_STRING = 1;
int TYPE_BOOLEAN = 2;
int TYPE_PERSON = 3;

struct node {
  struct node* next;
  int type;
  void* value;
};

struct person {
  char* name;
  int age;
};

int main(int args, char **argv) {

  struct person aPerson;
  aPerson.name = "Angel";
  aPerson.age = 35;

  // Define a linked list of objects.                                                                                                                                                       
  // We use that .type field to know what we're dealing                                                                                                                                     
  // with on every iteration. On .value we store our values.                                                                                                                                
  struct node nodes[] = {
    { .next = &nodes[1], .type = TYPE_INT    , .value=1                   },
    { .next = &nodes[2], .type = TYPE_STRING , .value="anyfing, anyfing!" },
    { .next = &nodes[3], .type = TYPE_PERSON , .value=&aPerson            },
    { .next = NULL     , .type = TYPE_BOOLEAN, .value=TRUE                }
  };

  // We iterate through the list                                                                                                                                                            
  for ( struct node *currentNode = &nodes[0]; currentNode;  currentNode = currentNode->next) {
    int currentType = (*currentNode).type;
    if (currentType == TYPE_INT) {
      printf("%s: %dn", "- INTEGER", (*currentNode).value); // just playing with syntax, same as currentNode->value                                                                        
    } else if (currentType == TYPE_STRING) {
      printf("%s: %sn", "- STRING", currentNode->value);
    } else if (currentType == TYPE_BOOLEAN) {
      printf("%s: %dn", "- BOOLEAN (true:1, false:0)", currentNode->value);
    } else if (currentType == TYPE_PERSON) {
        // since we're using void*, we end up with a pointer to struct person, which we *dereference                                                                                        
        // into a struct in the stack.                                                                                                                                                      
        struct person currentPerson = *(struct person*) currentNode->value;
        printf("%s: %s (%d)n","- TYPE_PERSON", currentPerson.name, currentPerson.age);
      }
  }

    return 0;
}

The output is this:

- INTEGER: 1
- STRING: anyfing, anyfing!
- TYPE_PERSON: Angel (35)
- BOOLEAN (true:1, false:0): 1

How to make a “foreach” function in JavaScript

Saturday, April 4th, 2015

I thought this would be a simple exercise in case of having to interview someone for a JavaScript position.

“How would you make your own ‘foreach’ in JavaScript”

I came up with the following solution:

// 
// collection: A list of objects.
// onElementIterationCallback: The function to be called on every element iterated
//    taking the following parameters:    foo(collection : [T], currentIndex : int)
function foreach(collection, onElementIterationCallback) {
    for (var i in collection) {
        if (collection.hasOwnProperty(i)) {
            onElementIterationCallback(collection[i], i);
        }
    }
}

This is how you’d use it:

var sumOfAges = 0;
var people = [ {name:"Angel", age:35},
               {name:"Paulina", age:33},
               {name:"Nicole", age:16}]

foreach(people, function (person, currentOffset) {
   console.log("("+ currentOffset + ") iterating on " + 
               person.name + ", age: " + person.age);
   sumOfAges += person.age; 
});

console.log(sumOfAges);

The expected output would be:

(0) iterating on Angel, age: 35
(1) iterating on Paulina, age: 33
(2) iterating on Nicole, age: 16
84

Hope you enjoyed, just a simple exercise of lists, creativity and callbacks.

Manifest on Internet’s Evolution

Wednesday, March 18th, 2015

(Forgotten draft from May 31st 2010)

I’m a little sad to see some of the paths the internet is taking lately. I personally think it’s enough about the infatuation that people have with “Social Networking”, enough, it’s boring and it makes us waste precious time as a race.

Technology is coming together for you to re-assess those technological ambitions that were not possible 10 years ago. Our networks are faster than ever, our home computers are several orders of magnitude more powerful, with multicore processing, gigs of RAM, powerful video cards, and what are we doing? Sending 140 chars at the time, and wasting time on Facebook a huge but simple friend database that can be resumed for external access to a simple 6 file “SDK”.

I write this (ongoing) manifest to inspire you to not waste your time on building the next social bullshit web “service”. I want you to think of yourself as the entrepreneur or scientist that truly changed the world for the better in a little way, not the one that made the entire world waste it’s time for you to make some bucks.

Everyone is in the Clouds, wake up, use those powerful CPUs
It’s like we forgot that we have powerful CPUs and hardware in our computers, like we forgot all the amazing technology we’ve created over the years and fell for the o-mighty-cloud. While at it we’re stuck with HTML5 and Javascript of all languages.

If we’re indeed going to rebuild and create new things for the browser, why the hell do we have to do it with such a limited set of technologies. Since I think we’ll be stuck in it, it’s time to create better IDEs and debugging tools for it, or start making those new browsers support the latest iterations in ECMA, to have proper Object Oriented support, a freaking binary primitive data type, threading and lower level I/O.

And why are we all buying this cloud crap, it’s like going back to mainframe/dummy terminal all over again, and paying for it. If things keep going this way, I might as well go back to a Pentium II with 64mb ram.

It’s about how we imagine the future
Think the future is not happening the way you thought it would be? Re-imagine, do something about it.

Stop cloning crap, build on top of it If you’re too late in the game
Competition is good, but you should recognize when you’re too late to enter the game unless you have something truly compelling and new to offer, on which case you might try to do business with the market leaders. For example, we don’t need another Twitter clone. Twitter was not the first on their space, Jaiku was there before (google even bought them) but they didn’t win. Remember what happened to Pwnce?

How to resize an EBS (xfs formatted) partition

Saturday, December 20th, 2014

First of all, create a snapshot of your EBS volume. Then out of that snapshot you will be able to create your new volume.

However, when you detach the old one from your instance and attach the new one, you will still see the old available space with df

look at my /dev/xvdf/ available space (after mounting the new EBS volume)

ubuntu@ip-10-47-167-74:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       16G  5.9G  9.1G  40% /
udev            7.4G   12K  7.4G   1% /dev
tmpfs           1.5G  176K  1.5G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            7.4G     0  7.4G   0% /run/shm
/dev/xvdf        20G   19G  1.7G  92% /media/ebs/data  <<< this one

still 20G, I mounted a 80G one!

This drive has been formatted to use an xfs file system. In order to resize it, this is the command I used:

sudo xfs_growfs -d /media/ebs/data

output should be something like this

ubuntu@ip-10-47-167-74:~$ sudo xfs_growfs -d /media/ebs/data
meta-data=/dev/xvdf              isize=256    agcount=4, agsize=1310720 blks
         =                       sectsz=512   attr=2
data     =                       bsize=4096   blocks=5242880, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 5242880 to 20971520

now let’s see the df -h output

ubuntu@ip-10-47-167-74:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       16G  5.9G  9.1G  40% /
udev            7.4G   12K  7.4G   1% /dev
tmpfs           1.5G  176K  1.5G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            7.4G     0  7.4G   0% /run/shm
/dev/xvdf        80G   19G   62G  23% /media/ebs/data

OnePlus One unboxing

Wednesday, September 10th, 2014

Charger and phone come in separate boxes.

Charger does not come with a cable. The phone does.

I guess it must be a statement for modularity and perhaps you get to buy only the accesories you need, if you need just a cable, you just buy the cable.

It’s a pretty power adapter, but not very functional, the contacts are not retractable like on many others.

The box was of really good quality material.

Custom shipping box for the phone, had a nice tab at the end of the rope used to open the box.

A white box, containing another box, good material again, but rather wasteful in my humble opinion.

Ta-da!

hopefully people will read the fine print and not get rid of this cover as it contains the devices IMEI and Serial number.

And this is the first Android device I have which I can’t open to remove the battery, so I’ll still be using my external battery for charging, hopefully the battery life will be as good as I expect as the phone didn’t come with a bunch of pre-loaded crap apps you can’t uninstall (dear AT&T and Samsung)

this material feels awesome, and the phone is pretty light.

and has a really cool looking USB cable.

I’m happy, now let’s hope I can find a rugged cover to protect it before it breaks, I tend to go running with my phones as I need gps tracking and like taking a picture here and there while I exercise.

First Impressions Lenovo Yoga Pro and Windows 8.1 with a 2 in 1 device.

Saturday, February 1st, 2014

After now almost 2 weeks of heavy duty use of this machine, I must say Windows 8.1 is not fully baked when it comes to its tiled/touch/app store experience, however it’s not the nightmare I expected.

The FrostWire 5.7.0. currently circulating on the Internet was built on this machine, the experience was quite pleasant as a workstation, and then I carried it around for the North American Bittorrent conference and during that time it was a very convenient tablet while I was doing all the social networking during the event.

WordPress: Cannot create directory error, got everything chmoded to 777?

Monday, January 27th, 2014

So you went as far as chmod’ing your entire folder structure to 777 (very unsafe), you’ve hacked wp/wp-admin/includes/file.php

return new WP_Error( 'mkdir_failed_ziparchive', __( get_current_user() . ' Could not create directory. ('.$_dir.')' )...

to print out exactly what directory it cannot create and what user is trying to create the folder, everything is correct, yet it won’t create the fucking folder?

the issue might be your vsftpd configuration!

Go to /etc/vsftpd.con and make sure that you have this setting uncommented:

write_enable=YES

restart your vsftpd (sudo service vsftpd restart) and try upgrading again, you’ll want to hit that ‘Donate Bitcoin’ button if I saved your ass today.

Cheers

building cgminer from source on OSX

Sunday, January 19th, 2014

so you cloned the cgminer repo from github to build on your OSX machine and you get this bullshit error

$ ./autogen.sh
readlink: illegal option -- f
usage: readlink [-n] [file ...]
usage: dirname path
touch: /ltmain.sh: Permission denied
Use of chdir('') or chdir(undef) as chdir() is deprecated at /usr/local/bin/autoreconf line 670.
Configuring...
./autogen.sh: line 10: /configure: No such file or directory

readlink works differently in OSX and the current version of the autogen.sh script seems like it wasn’t tested on OSX (wonder why didn’t they use a simple bs_dir=`pwd`, the answer is probably canonical paths and what not).

To keep moving along, open the autogen.sh script and just change the value of the bs_dir variable to the full real path of where you have cloned the cgminer source code.

then execute your autogen script, make sure to enable compilation flags for your ASIC hardware, in my case I remember seeing ‘icarus’ on a binary build of cgminer I tried before, so I did

./autogen.sh --enable-icarus

you might want to enable all of them if you’re not sure what hardware you have or you will have in the future as you may not like the joys of building software (check out the the README for all the –enable-xxx options available)

If you’re getting errors on your configuration script due to missing dependencies, I strongly recommend you use Homebrew to install these packages (if you are using Macports or Fink, I strongly suggest you completely remove that crap from your computer and go 100% with brew, it works really well if you’re building a lot of code on a regular basis):

brew install autoconf automake autoreconf libtool openssl curses curl

brew, at the point of this writing didn’t have libcurl, so that one you will have to download, ./configure, make and sudo make install yourself from here http://curl.haxx.se/download.html (I used version 7.34 when I did it)

after that the autogen script should work, and then you should be just one ‘make’ away from your goal.

AWS troubleshooting: how to fix a broken EBS volume (bad superblock on xfs)

Sunday, January 19th, 2014

As great as EBS volumes are on Amazon Web Services, they can break and not ever mount again, even though your data could still be there intact, a simple corruption on the filesystem structure can cause a lot of damage. On this post I teach you how to move all that data onto a new EBS drive, so keep calm and read slowly.

So, you try to mount your drive after some updates and you get an error like this on dmesg | tail:

[56439860.329754] XFS (xvdf): Corruption detected. Unmount and run xfs_repair

so you unmount your drive, invoke xfs_repair and you get this…

$ sudo xfs_repair -n /dev/xvdf
Phase 1 - find and verify superblock...
bad primary superblock - bad magic number !!!

attempting to find secondary superblock...
..........................................

and no good secondary superblock is found.

Don’t panic, this is what you have to do next to solve this issue:

1. Go to your AWS dashboard, EC2 section.
2. Click on “Volumes”
3. Find the broken volume.
4. Create a snapshot of the broken volume (this takes a while)
5. Create a new volume the same size (or larger than) your old drive out of the snapshot you just created (this takes a while)
6. Attach your new volume to the same EC2 instance (no need to reboot or anything), if the old drive was mapped to /dev/xvdf, the new one will be mapped to /dev/xvdg (see how the last letter increases alphabetically)

Now here’s a gotcha, Amazon will not create your new drive using the same file system type (xfs), for some reason it will create it using the ext2 filesystem.

$ sudo file -s /dev/xvdg
/dev/xvdg: Linux rev 1.0 ext2 filesystem data (mounted or unclean), UUID=2e35874f-1d21-4d2d-b42b-ae27966e0aab (large files)

Here you have two options:
1. Live with the new ext2 file system, make sure your /etc/fstab is updated to look something like this:
/dev/xvdg /path/to/mount/to auto defaults,nobootwait,noatime 0 0

or 2. copy the contents of your drive to a temporary location, usually inside /mnt which has plenty of space from that ephemeral drive the ec2 instances come to, and then mkfs.xfs the new volume, and then copy the contents back… (which what I did, as I chose to create a larger drive and the ext2 format that came on the new volume only recognized the size of the snapshot)

Hope this saved your ass, leave a note if I did.

Remember to never do any irreversible action until you have a disk snapshot, try your best to never lose data.

How much electricity does the Facebook app consume everyday by making phones vibrate with push notifications?

Monday, August 26th, 2013

My silly little goal is to convince Facebook to pre-configure its mobile apps so they don’t make phones vibrate by default and push silent notifications to mobile users.

Help me make an estimate, we need to know on average how many milliwatts the average phone will spend per notification, and an estimate of how many push notifications are received by smartphones worldwide from facebook.

Say a phone consumes 150 milliwatts per push notification, and in one minute alone facebook sends 1 million notifications, Facebook would be consuming the world about 9 Megawatts/hour. This would be just a number thrown out there since I don’t know for sure if that’s the average power consumed, nor I know how many notifications are received per minute, I bet it’s way more than 1 million per minute.

Would love the help from people who work at Facebook or who have stats on push notifications, as well as any engineer working with phone hardware at any major phone manufacturing company.

Twitter is also sending a lot of notifications to phones.

Turn off vibration on your Facebook app, you will save a considerable amount of battery every day.




  • Categories

  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
  • March 2010
  • February 2010
  • January 2010
  • December 2009
  • October 2009
  • September 2009
  • July 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007
  • February 2007
  • January 2007
  • December 2006
  • November 2006
  • October 2006
  • September 2006
  • August 2006
  • July 2006
  • June 2006
  • May 2006
  • April 2006
  • March 2006
  • February 2006
  • January 2006
  • December 2005
  • November 2005
  • October 2005
  • September 2005
  • August 2005
  • July 2005
  • June 2005
  • May 2005
  • April 2005
  • March 2005
  • February 2005
  • January 2005
  • December 2004
  • November 2004
  • October 2004