Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

« Newer Snippets
Older Snippets »
Showing 1-10 of 5204 total  RSS 

Adding a file selection dialog window to a Ruby Maemo application

Run a Ruby Maemo application which displays the system's file selection dialog box.

   1  
   2  #! /usr/bin/env ruby
   3  #file: fileselection.rb
   4  
   5  #require 'gtk'
   6  require 'hildon'
   7  
   8  program = Hildon::Program.instance
   9  
  10  fs = Gtk::FileSelection.new('File Selection Example')
  11  fs.show
  12  
  13  Gtk.main
  14  

You can see from the output on the N800 [twitxr.com] as I viewed the File Selection Example dialog box'.

Resources:
- Adding a text entry box in a Ruby Maemo application [dzone.com]
- Ruby/Gtk Programming [sourceforge.net]

Adding a 2nd level menu to a Ruby Maemo application

Here is a script to run a Ruby Maemo application which has a scroll bar and a 2nd level menu box. The first level menu box would be application's control menu box.

   1  
   2  #! /usr/bin/env ruby
   3  #file: combo.rb
   4  
   5  #require 'gtk'
   6  require 'hildon'
   7  
   8  program = Hildon::Program.instance
   9  
  10  #window = Gtk::Window.new(Gtk::WINDOW_TOPLEVEL)
  11  window = program.add_window Hildon::Window.new
  12  
  13  combo = Gtk::Combo.new
  14  combo.set_popdown_strings(['http://www.netlab.co.jp/ruby/',
  15  			    'http://ruby.freak.ne.jp/'])
  16  combo.entry.set_text ''
  17  window.add(combo)
  18  combo.show
  19  window.show
  20  Gtk.main


You can see from the output on the N800 [twitxr.com] as I selected an item from the menu box'.

Resources:
- Adding a text entry box in a Ruby Maemo application [dzone.com]
- Ruby/Gtk Programming [sourceforge.net]

Adding a combo box to a Ruby Maemo application

Here is a script to run a Ruby Maemo application which has a combo box.

   1  
   2  #! /usr/bin/env ruby
   3  #file: combo.rb
   4  
   5  #require 'gtk'
   6  require 'hildon'
   7  
   8  program = Hildon::Program.instance
   9  
  10  #window = Gtk::Window.new(Gtk::WINDOW_TOPLEVEL)
  11  window = program.add_window Hildon::Window.new
  12  
  13  combo = Gtk::Combo.new
  14  combo.set_popdown_strings(['http://www.netlab.co.jp/ruby/',
  15  			    'http://ruby.freak.ne.jp/'])
  16  combo.entry.set_text ''
  17  window.add(combo)
  18  combo.show
  19  window.show
  20  Gtk.main


You can see from the output on the N800 [twitxr.com] as I selected an item from the combo box'.

Resources:
- Adding a text entry box in a Ruby Maemo application [dzone.com]
- エントリウィジェットとコンボウィジェット - Ruby/Gtk Programming [sourceforge.net]
- Hello World in Ruby/GTK [sourceforge.net]

Adding a text entry box in a Ruby Maemo application

Here is a script to run a Ruby Maemo application which has a text entry box. There's nothing special about this code other than it uses 'hildon' instead of Gtk.

The only code changes from the original Ruby GTK code was to comment out the gtk include file and the Gtk Window.new statement.

   1  
   2  #! /usr/bin/env ruby
   3  #file: entry.rb
   4  
   5  #require 'gtk'
   6  require 'hildon'
   7  
   8  program = Hildon::Program.instance
   9  
  10  #window = Gtk::Window.new(Gtk::WINDOW_TOPLEVEL)
  11  window = program.add_window Hildon::Window.new
  12  
  13  label = Gtk::Label.new('Name:')
  14  entry = Gtk::Entry.new
  15  entry.set_text('John')
  16  box = Gtk::HBox.new(false, 0)
  17  box.pack_start label, true, true, 5
  18  box.pack_start entry, true, true, 5
  19  label.show
  20  entry.show
  21  
  22  entry.signal_connect('activate') {|widget|
  23    print "Your name is #{entry.get_text}\n"
  24  }
  25  
  26  window.add(box)
  27  box.show
  28  window.show
  29  Gtk.main


You can see from the output on the N800 [twitxr.com] as I replaced the entry value 'John' with 'Jim'.

Resources:
- エントリウィジェットとコンボウィジェット - Ruby/Gtk Programming [sourceforge.net]
- Hello World in Ruby/GTK [sourceforge.net]

Get a random sampling of 10% of spec files to run

// If you have a huge spec suite that takes hours to run, you might want to just run a random sampling instead of the whole suite.

   1  
   2  Dir["spec/**/*_spec.rb"].sort_by { rand }.first(Dir["spec/**/*_spec.rb"].size / 10).join " "

Remove deleted files from git

http://www.jamesrobey.com/bash-script-to-remove-deleted-files-from-git/#comment-317
   1  git ls-files --deleted | xargs git rm

Create a Ruby Maemo application on the N800

Source: Nseries Workshop » Blog Archive » How to run Ruby on your N800/N810 [nseries.com]

<snip>
   1  
   2  #! /usr/bin/env ruby
   3  require 'hildon'
   4  
   5  if $0 == __FILE__
   6  GLib.application_name = 'Basic Application'
   7  
   8  program = Hildon::Program.instance
   9  window = program.add_window Hildon::Window.new
  10  
  11  window.signal_connect('delete_event') { Gtk.main_quit }
  12  
  13  window.add Gtk::Label.new('This is your N800, reporting for duty')
  14  
  15  window.show_all
  16  Gtk.main
  17  end

</snip>

Installation: If you have Ruby1.8 already installed on the N800 without libruby1.8, then uninstall it. Then proceed with installation of libruby1.8, ruby1.8, and ruby1.8-maemo.

The Ruby packages were downloaded from scottishclimbs.com

Resources:
Index of /maemo/repository/dists/chinook/free/binary-armel [scottishclimbs.com]

Here's a screenshot of the Ruby application running on the N800 [twitxr.com].

Exemple de flux RSS chez goodreads

Si on le parse en pur RSS, on n'obtient, grosso mode, que le tag description à la fin, qui est franchement moche, alors que goodreads ajoute plein de trucs vraiment utiles.

   1  
   2  <?xml version="1.0"?>
   3  <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
   4  	<channel>
   5  		<title>Nicolas's bookshelf: read </title>
   6  		<copyright><![CDATA[Copyright (C) 2008 Goodreads Inc. All rights reserved.]]>
   7  		</copyright>
   8  		<link><![CDATA[http://www.goodreads.com/review/list_rss/1156136?key=6e3f5ede71d718b58a0a4f72a9a630bb850e1a3b&shelf=]]></link>
   9      <atom:link href="http://www.goodreads.com/review/list_rss/1156136?key=6e3f5ede71d718b58a0a4f72a9a630bb850e1a3b&amp;shelf=" rel="self" type="application/rss+xml" />
  10  		<description><![CDATA[Nicolas's bookshelf: read ]]></description>
  11  		<language>en-US</language>
  12  		<lastBuildDate>Tue, 07 Oct 2008 02:37:44 -0700</lastBuildDate>
  13  		<ttl>60</ttl>
  14  		<image>
  15  			<title>Nicolas's bookshelf: read </title>
  16  			<link><![CDATA[http://www.goodreads.com/review/list_rss/1156136?key=6e3f5ede71d718b58a0a4f72a9a630bb850e1a3b&shelf=]]></link>
  17  			<width>144</width>
  18  			<height>41</height>
  19  			<url>http://www.goodreads.com/images/layout/gr_logo_144.jpg</url>
  20  		</image>
  21  	<item>
  22  		<guid>http://www.goodreads.com/review/show/26192996?utm_medium=api&amp;utm_source=rss</guid>
  23  		<pubDate>Tue, 07 Oct 2008 02:37:44 -0700</pubDate>
  24  		<title>
  25  			<![CDATA[Le Samouraï virtuel]]>
  26  		</title>
  27  		<link>
  28  		  http://www.goodreads.com/review/show/26192996?utm_medium=api&amp;utm_source=rss
  29  		</link>
  30  		<book_image_url>
  31  		  <![CDATA[http://photo.goodreads.com/books/1170278409s/45281.jpg]]>
  32  		</book_image_url>
  33  		<book_small_image_url>
  34  		  <![CDATA[http://photo.goodreads.com/books/1170278409s/45281.jpg]]>
  35  		</book_small_image_url>
  36  		<book_medium_image_url>
  37  		  <![CDATA[http://photo.goodreads.com/books/1170278409m/45281.jpg]]>
  38  		</book_medium_image_url>
  39  		<book_large_image_url>
  40  		  <![CDATA[http://photo.goodreads.com/books/1170278409l/45281.jpg]]>
  41  		</book_large_image_url>
  42  		<author_name><![CDATA[Neal Stephenson]]></author_name>
  43  		<book_id><![CDATA[45281]]></book_id>
  44  		<isbn><![CDATA[2253072214]]></isbn>
  45  		<user_name><![CDATA[Nicolas]]></user_name>
  46  		<user_rating><![CDATA[5]]></user_rating>
  47  		<user_read_at><![CDATA[07/00]]></user_read_at>
  48  		<user_date_added><![CDATA[Tue, 07 Oct 2008 02:37:44 -0700]]></user_date_added>
  49  		<user_date_created><![CDATA[Thu, 03 Jul 2008 04:59:31 -0700]]></user_date_created>
  50  		<user_shelves><![CDATA[combat, cyberpunk, top, voyage]]></user_shelves>
  51  		<user_review><![CDATA[Commencons tout de suite avec le cyberpunk. Alors que je lisais cette oeuvre une polémique assez vive agitait le forum à propos de la définition du cyberpunk. Or il se trouve que justement, le samouraï virtuel illustre parfaitement ce qu’est le cyberpunk : sur un terrain connu, l’état démocratique américain a abandonné ses prérogatives à des sociétés privées, dont la MAFIA qui ne se définit plus comme telle puisque la notion même d’état a complètement explosée. C’est là qu’on trouve la plus vive illustration du cyberpunk selon moi : non pas dans la présence d’implants, ou d’une matrice dont la réalité future n’est finalement qu’une extrapolation logique de l’existence d’Internet, mais bien dans l’explosion de la notion d’état pour un retour à un tribalisme, mais modifié par la transnationnalité qu’impose logiquement la mondialisation des échanges de culture.
  52  <br/>
  53  <br/>C’est à mon avis ça la vraie base de toutes les oeuvres cyberpunk : une négation de l’état, mais pas des structures sous-jacentes : la justice, le commerce sont toujours présents dans ces oeuvres, mais ne sont plus organisées sur un territoire physique continu, mais plutôt sur un territoire composé d’une mosaïque d’implantation, ce qui me fait soudainement penser aux mosaiques d’implantations de colons juifs en Palestine. Ne seraient-elles pas finalement une préfiguration d’un monde cyberpunk (ouah le troll !) ?
  54  <br/>
  55  <br/>Passons maintenant à l’autre point fondateur de ce roman : les Nams-Shubs, les En et la multiplication des langues. Là, je n’ai toujours que des questions. En effet, s’il est vrai que le langage conditionne non seulement notre façon de penser, mais également notre façon de penser, n’est-il pas effectivement envisageable de supposer, comme le fait l’auteur, qu’il existe une langue qui serait finalement l’équivalent de l’assembleur informatique : un langage dont le niveau est tel que son utilisation donne une puissance incroyable à celui qui le connait, mais qui n’existe qu’en tant que couche de base dont toues les autres langages se servent.
  56  <br/>
  57  <br/>Je n’ai qu’un très léger vernis philosophique, mais ne peut-on penser que ce langage serait le meilleur moyen de passer de notre monde à celui des idées, finalement un moyen de transformer au mieux les idées en réalités ? Sur ces quelques idées, j’aimerais bien l’avis éclairé des NooGurus, et de tous les autres penseurs du forum…]]></user_review>
  58  
  59  		<average_rating><![CDATA[6.00]]></average_rating>
  60  		<book_published><![CDATA[1992]]></book_published>
  61  		<description>
  62  			<![CDATA[
  63  	    <a href="http://www.goodreads.com/book/show/45281.Le_Samoura_virtuel?utm_medium=api&amp;utm_source=rss"><img alt="Le Samouraï virtuel" src="http://photo.goodreads.com/books/1170278409s/45281.jpg" /></a><br/>
  64  			
  65  			author: Neal Stephenson<br/>
  66  			name: Nicolas<br/>
  67  			average rating: 6.00<br/>
  68  			book published: 1992<br/>
  69  			rating: 5<br/>
  70  			read at: 07/00<br/>
  71  			date added: 10/07/08<br/>
  72  			shelves: combat, cyberpunk, top, voyage<br/>
  73  			review: <br/>Commencons tout de suite avec le cyberpunk. Alors que je lisais cette oeuvre une polémique assez vive agitait le forum à propos de la définition du cyberpunk. Or il se trouve que justement, le samouraï virtuel illustre parfaitement ce qu’est le cyberpunk : sur un terrain connu, l’état démocratique américain a abandonné ses prérogatives à des sociétés privées, dont la MAFIA qui ne se définit plus comme telle puisque la notion même d’état a complètement explosée. C’est là qu’on trouve la plus vive illustration du cyberpunk selon moi : non pas dans la présence d’implants, ou d’une matrice dont la réalité future n’est finalement qu’une extrapolation logique de l’existence d’Internet, mais bien dans l’explosion de la notion d’état pour un retour à un tribalisme, mais modifié par la transnationnalité qu’impose logiquement la mondialisation des échanges de culture.
  74  <br/>
  75  <br/>C’est à mon avis ça la vraie base de toutes les oeuvres cyberpunk : une négation de l’état, mais pas des structures sous-jacentes : la justice, le commerce sont toujours présents dans ces oeuvres, mais ne sont plus organisées sur un territoire physique continu, mais plutôt sur un territoire composé d’une mosaïque d’implantation, ce qui me fait soudainement penser aux mosaiques d’implantations de colons juifs en Palestine. Ne seraient-elles pas finalement une préfiguration d’un monde cyberpunk (ouah le troll !) ?
  76  <br/>
  77  <br/>Passons maintenant à l’autre point fondateur de ce roman : les Nams-Shubs, les En et la multiplication des langues. Là, je n’ai toujours que des questions. En effet, s’il est vrai que le langage conditionne non seulement notre façon de penser, mais également notre façon de penser, n’est-il pas effectivement envisageable de supposer, comme le fait l’auteur, qu’il existe une langue qui serait finalement l’équivalent de l’assembleur informatique : un langage dont le niveau est tel que son utilisation donne une puissance incroyable à celui qui le connait, mais qui n’existe qu’en tant que couche de base dont toues les autres langages se servent.
  78  <br/>
  79  <br/>Je n’ai qu’un très léger vernis philosophique, mais ne peut-on penser que ce langage serait le meilleur moyen de passer de notre monde à celui des idées, finalement un moyen de transformer au mieux les idées en réalités ? Sur ces quelques idées, j’aimerais bien l’avis éclairé des NooGurus, et de tous les autres penseurs du forum…<br/>
  80  			]]>
  81  		</description>
  82  	</item>
  83  </channel>
  84  </rss>

IP Range To Cidr Convertor C Code

// C Code to convert a given Ip range to CIDR notation.

   1  
   2  /* rangeToCidr.c - Convert Ip ranges to CIDR */
   3  
   4  /*
   5  modification history
   6  --------------------
   7  01a,17sep08,karn written
   8  */
   9  
  10  /* includes */
  11  
  12  #include<stdio.h>
  13  #include<unistd.h>
  14  #include<string.h>
  15  #include<math.h>
  16  #include<errno.h>
  17  #include <sys/socket.h>
  18  #include <netinet/in.h>
  19  #include <arpa/inet.h>
  20  
  21  /* defines */
  22  //#define DBG
  23  #ifdef DBG
  24  #define DEBUG(x) fprintf(stderr,x)
  25  #else
  26  #define DEBUG
  27  #endif /* DBG */
  28  
  29  #define IP_BINARY_LENGTH 32+1  /* 32 bits ipv4 address +1 for null */
  30  #define IP_HEX_LENGTH    10   
  31  #define MAX_CIDR_MASK    32
  32  #define MAX_CIDR_LEN     18+1   /*255.255.255.255/32*/
  33  
  34  /* Forward declaratopms */
  35  void rangeToCidr(uint32_t from ,uint32_t to,
  36                   void (callback)(char *cidrNotation));
  37  int ipToBin(uint32_t ip , char * pOut);
  38  
  39  void printNotation(char *cidrNotation);
  40  
  41  /* Globals */
  42  
  43  
  44  /*******************************************************************************
  45  *
  46  * ipToBin - convert an ipv4 address to binary representation 
  47  *           and pads zeros to the beginning of the string if 
  48  *           the length is not 32 
  49  *           (Important for ranges like 10.10.0.1 - 20.20.20.20 )
  50  *
  51  * ip   - ipv4 address on host order
  52  * pOut - Buffer to store binary.
  53  *
  54  * RETURNS: OK or ERROR 
  55  */
  56  
  57  int ipToBin(uint32_t ip , char * pOut)
  58      {
  59      char hex[IP_HEX_LENGTH];
  60      int i;
  61      int result=0;
  62      int len;
  63      char pTmp[2];
  64      int tmp;
  65      /*
  66       * XXX: Could use bit operations instead but was easier to debug
  67       */
  68      char binMap[16][5] = { 
  69                          "0000","0001","0010","0011", "0100",
  70                          "0101","0110","0111","1000", "1001",
  71                          "1010","1011","1100", "1101","1110","1111",
  72                          };
  73      pTmp[1]=0x0;
  74      memset(hex,0x0,sizeof(hex));
  75      len=sprintf(hex,"%x",ip);
  76  
  77      for(i=0;i<len;i++)
  78          {
  79  
  80          /* Ugly but to use strtol , we need the last byte as null */
  81          pTmp[0]=hex[i];
  82  
  83          errno = 0;
  84          tmp = strtol(pTmp, 0x0, 16);
  85  
  86          /* Should not happen */
  87          if (errno != 0)
  88              {
  89              memset(pOut,'0',IP_BINARY_LENGTH -1);
  90              DEBUG ("strtol failed for hex 0x%s\n",pTmp);
  91              return -1;
  92              }
  93  
  94          result+=sprintf(pOut+result,"%s",binMap[tmp]);
  95          }
  96  
  97          DEBUG("bits %u printed for ip address for hex len %u\n",result,len);
  98          /* if length is not 32 , pad the start with zeros*/
  99  
 100      if(result < IP_BINARY_LENGTH-1)
 101          {
 102          char pSwap[IP_BINARY_LENGTH];
 103          strncpy(pSwap,pOut,IP_BINARY_LENGTH);
 104          memset(pOut,'0',IP_BINARY_LENGTH);
 105          strncpy(pOut+IP_BINARY_LENGTH-1-result,pSwap,result);
 106          DEBUG("corrected length to 32\n");
 107          }
 108  
 109      else if (result > IP_BINARY_LENGTH-1)
 110          return -1;
 111  
 112      /* Success */
 113      return 0;
 114      }
 115  
 116  /*******************************************************************************
 117  *  main : 
 118  * 
 119  *  arg1 : Start Ip Address
 120  *  arg2 : End Ip address
 121  */
 122  
 123  int main (int argc,char **argv)
 124      {
 125      long fromIp, toIp;
 126      struct in_addr addr;
 127      if(argc !=3 )
 128          {
 129          printf("Usage: %s <from> <to>\n",argv[0]);
 130          return(0);
 131          }
 132  
 133      /* All operation on host order */   
 134      if (inet_aton(argv[1],&addr) == 0)
 135          goto error;
 136      fromIp = ntohl(addr.s_addr);
 137  
 138      if (inet_aton(argv[2],&addr) ==0)
 139          goto error;
 140      toIp = ntohl(addr.s_addr);
 141  
 142      rangeToCidr(fromIp,toIp,printNotation);
 143  
 144      return 0;
 145  error:
 146      printf("Invalid Argument\n");
 147      return -EINVAL;
 148      }
 149  
 150  
 151  /*******************************************************************************
 152  *
 153  * rangeToCidr - convert an ip Range to CIDR, and call 'callback' to handle
 154  *               the value. 
 155  *
 156  * from     - IP Range start address
 157  * to       - IP Range end address
 158  * callback - Callback function to handle cidr.
 159  * RETURNS: OK or ERROR 
 160  */
 161  
 162  void rangeToCidr(uint32_t from ,uint32_t to,
 163                   void (callback)(char *cidrNotation))
 164      {
 165      int     cidrStart = 0;
 166      int     cidrEnd = MAX_CIDR_MASK - 1;
 167      long    newfrom;
 168      long    mask;
 169      char    fromIp[IP_BINARY_LENGTH];
 170      char    toIp[IP_BINARY_LENGTH];
 171      struct  in_addr addr;
 172      char    cidrNotation[MAX_CIDR_LEN];
 173  
 174      memset (fromIp,0x0,sizeof(fromIp));
 175      memset (toIp,0x0,sizeof(toIp));
 176  
 177      if ( ipToBin(from,fromIp) != 0 ) 
 178          return;
 179      if ( ipToBin(to,toIp) != 0 )
 180          return;
 181  
 182      DEBUG ("from %lu to %lu\n", from,to);
 183      DEBUG("from %s\n",fromIp);
 184      DEBUG("to   %s\n",toIp);
 185  
 186      if(from < to )
 187          {
 188  
 189          /* Compare the from and to address ranges to get the first
 190           * point of difference
 191           */
 192  
 193          while(fromIp[cidrStart]==toIp[cidrStart])
 194              cidrStart ++;
 195          cidrStart = 32 - cidrStart -1 ;
 196          DEBUG("cidrStart is %u\n",cidrStart);
 197  
 198          /* Starting from the found point of difference make all bits on the 
 199           * right side zero 
 200           */
 201  
 202          newfrom = from >> cidrStart +1  << cidrStart +1 ;        
 203  
 204          /* Starting from the end iterate reverse direction to find 
 205           * cidrEnd
 206           */ 
 207          while( fromIp[cidrEnd] == '0' && toIp[cidrEnd] == '1')
 208              cidrEnd --;
 209  
 210          cidrEnd = MAX_CIDR_MASK - 1 - cidrEnd;
 211          DEBUG("cidrEnd is %u\n",cidrEnd);
 212  
 213          if(cidrEnd <= cidrStart)
 214              {
 215              /* 
 216               * Make all the bit-shifted bits equal to 1, for
 217               * iteration # 1.
 218               */
 219              
 220              mask = pow (2, cidrStart ) - 1;
 221              DEBUG("it1 is %lu \n",newfrom | mask );
 222              rangeToCidr (from , newfrom | mask, callback);
 223              DEBUG("it2 is %lu \n",newfrom | 1 << cidrStart);
 224              rangeToCidr (newfrom | 1 <<  cidrStart ,to ,callback);
 225              }
 226          else
 227              {
 228              addr.s_addr = htonl(newfrom);
 229              sprintf(cidrNotation,"%s/%d", 
 230                      inet_ntoa(addr), MAX_CIDR_MASK-cidrEnd);
 231              if (callback != NULL)
 232                  callback(cidrNotation);
 233              }
 234          }
 235  
 236      else
 237          {
 238          addr.s_addr = htonl(from);
 239          sprintf(cidrNotation,"%s/%d",inet_ntoa(addr),MAX_CIDR_MASK);
 240          if(callback != NULL)
 241              callback(cidrNotation);
 242          }
 243      }
 244  
 245  /*******************************************************************************
 246  *
 247  * printNotation - This is an example callback function to handle cidr notation. 
 248  *
 249  * RETURNS:
 250  */
 251  
 252  void printNotation(char *cidrNotation)
 253      {
 254      printf("%s\n",cidrNotation);
 255      }

Default merb datamapper database.yml file


   1  
   2  # This is a sample database file for the DataMapper ORM
   3  :development: &defaults
   4    :adapter: mysql
   5    :database: merb-blog
   6    :username: root
   7    :password: 
   8    :host: localhost
   9  
  10  :test:
  11    <<: *defaults
  12    :database: sample_test
  13  
  14  :production:
  15    <<: *defaults
  16    :database: sample_production
  17  
« Newer Snippets
Older Snippets »
Showing 1-10 of 5204 total  RSS