Never been to DZone Snippets before?

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

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

Using simple top-down CSS menus.

The sample HTML and CSS file demonstrates a simple top-down navigational menu which displays the sub menu when the mouse hovers over the main menu item.

   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml-strict.dtd">
   4  <html xmlns:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
   5    <head>
   6      <link rel="stylesheet" type="text/css" href="rollover.css"/>
   7    </head>
   8    <body>
   9      <div id="nav">
  10        <ul>
  11          <li><a href="menu1/">Menu 1</a>
  12            <ul>
  13            <li><a href="menu1/sub1.html">Submenu 1.1</a></li>
  14            <li><a href="menu1/sub2.html">Submenu 1.2</a></li>
  15            </ul>
  16          </li>
  17          <li><a href="menu2/">Menu 2</a>
  18            <ul>
  19            <li><a href="menu2/sub1.html">Submenu 2.1</a></li>
  20            <li><a href="menu2/sub2.html">Submenu 2.2</a></li>
  21            </ul>
  22          </li>
  23        </ul>
  24      </div>
  25    </body>
  26  </html>
  27  


   1  
   2  #nav ul {
   3    padding: 1em;
   4    margin: 0;
   5    background: #fff;
   6  }
   7  
   8  #nav ul ul {
   9    display: none;
  10  }
  11  
  12  #nav ul li {
  13    list-style-type: none;
  14    position: relative;
  15    margin: 0;
  16    display: inline;
  17  }
  18  
  19  #nav ul li:hover > ul {
  20    display:block;
  21    position:absolute;
  22    top: 100%;
  23    left: 0%;
  24    background-image: url(/images/fix_ie_hover.gif); /* IE7 bugfix */
  25  }

Here's what the CSS menu [twitxr.com] looks like in the web page.

[PHP] A simple error function for everyday use...

... It uses the php function "error_log".
   1  
   2  define("PATH_LOG","./log/");
   3  
   4  function error($line,$method,$class,$system_error,$user_error = "",$date = "",$log = true,$show = true) {
   5  	if (empty($date)) {
   6  		$date = date('r');
   7  	}
   8  	
   9  	if (empty($user_error)) {
  10  		$user_error = $system_error;
  11  	}
  12  	
  13  	
  14  	$error = "$date - $method at $line - $system_error\n";
  15  	
  16  	if ($log == true) {
  17  		error_log($error,3,PATH_LOG."$class.log");
  18  	}
  19  	
  20  	if ($show == true) {
  21  		echo "<div class=\"error\">$user_error</div>";
  22  	}
  23  
  24  	return true;
  25  }
  26  
  27  
  28  //Example
  29  class Test {
  30  	private showError true;
  31  	
  32  	public function __construct() {
  33  		$test = false;
  34  		
  35  		if ($test === false) {
  36  			error(__LINE__,__METHOD__,__CLASS__,"sys error blub","There are internal problems. Sorry for that.","",true,$this->showError);
  37  		}
  38  	}
  39  }
  40  
  41  $test = new Test();

Run TCPServer as a simple Web server

A TCPServer accepts incoming TCP connections. Here is a Web server that listens on a given port and returns the time.

   1  
   2  require 'socket'
   3  port = (ARGV[0] || 80).to_i
   4  server = TCPServer.new('localhost', port)
   5  while (session = server.accept)
   6    puts "Request: #{session.gets}"
   7    session.print "HTTP/1.1 200/OK\r\nContent-type: text/html\r\n\r\n"
   8    session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
   9    session.close
  10  end

This code was copied from Programming Ruby: The Pragmatic Programmer's Guide [rubycentral.com] while looking for information on Ruby CGI global variables.

CSS *true* centering

This will truely center something in CSS. Not tested in IE, knowing IE, it will burn in flames.

   1  
   2  #center-me { /* There can be only one Centerlander! */
   3    height: 100%;
   4    display: table !important;
   5    margin: auto;
   6  }
   7  
   8  #center-me > * {
   9    display: table-cell !important; /* Don't touch me! I MEAN IT! DON- ... don't touch me. Really, don't touch me. */
  10    vertical-align: middle !important;
  11  }


   1  
   2  <div id="center-me">
   3    <h1>I'm centered!</h1>
   4  </div>

Simple way to check command line arguments in a C program

A simple way to check command line arguments.

Author: Joana Matos Fonseca da Trindade
Date: 2008.02.25

   1  
   2  #include <stdio.h>
   3  #include <stdlib.h>
   4  #include <string.h>
   5  
   6  /* minimum required number of parameters */
   7  #define MIN_REQUIRED 2
   8  
   9  /* display usage */
  10  int help() {
  11     printf("Usage: myprogram [-s <arg0>] [-n <arg1>] [-true]\n");
  12     printf("\t-s: a string a\n");
  13     printf("\t-n: a number\n");
  14     printf("\t-true: a single parameter\n");
  15  
  16     return 1;
  17  }
  18  
  19  /* main */
  20  int main(int argc, char *argv[]) {
  21     if (argc < MIN_REQUIRED) {
  22        return help();
  23     }
  24     int i;
  25  
  26     /* iterate over all arguments */
  27     for (i = 1; i < (argc - 1); i++) {
  28         if (strcmp("-s", argv[i]) == 0) {
  29            /* do something with it */ 
  30            printf("string = %s\n", argv[++i]);
  31            continue;
  32         }
  33         if (strcmp("-n", argv[i]) == 0) {
  34            /* do something with it. for example, convert it to an integer */
  35            printf("number = %i\n", atoi(argv[++i]));
  36            continue;
  37         }
  38         if (strcmp("-true", argv[i]) == 0) {
  39            printf("true activated\n");
  40            continue;
  41         }
  42         return help();
  43     }
  44     return 0;
  45  }

A simple XSLT example

Produce a list of filenames using XML and XSLT

file: dir.xsl
   1  
   2  <?xml version="1.0"?>
   3  
   4  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   5        
   6      <xsl:template match="dir">
   7      <div id="articles">
   8        <ul>
   9        <xsl:apply-templates select="records/file"/>
  10        </ul>
  11      </div>
  12      </xsl:template>
  13      
  14      <xsl:template match="records/file">
  15        <li><xsl:value-of select="."/></li>
  16      </xsl:template>
  17      
  18  </xsl:stylesheet>


file: dir.xml
   1  
   2  <dir>
   3    <summary>
   4      <directory>./</directory>
   5    </summary>
   6    <records>
   7      <file type='xml'>mjournal.xml</file>
   8      <file type='rb'>projxmlhelper.rb</file>
   9      <file type='rb'>feedpopulated.rb</file>
  10      <file type='rb'>squrl_handler.rb</file>
  11      <file type='cgi'>snurl.cgi</file>
  12      <file type='cgi'>dynalert.cgi</file>
  13      <file type='rb'>password_handler.rb</file>
  14      <file type='rb'>category.rb</file>
  15      <file type='rb'>gwd.rb</file>
  16      <file type='cgi'>new-journal-entry.cgi</file>
  17    </records>
  18  </dir>


then transforming the XML with the command 'xsltproc dir.xsl dir.xml' produces the following:
output:
   1  
   2  <div id='articles'>
   3    <ul>
   4      <li>mjournal.xml</li>
   5      <li>projxmlhelper.rb</li>
   6      <li>feedpopulated.rb</li>
   7      <li>squrl_handler.rb</li>
   8      <li>snurl.cgi</li>
   9      <li>dynalert.cgi</li>
  10      <li>password_handler.rb</li>
  11      <li>category.rb</li>
  12      <li>gwd.rb</li>
  13      <li>new-journal-entry.cgi</li>
  14    </ul>
  15  </div>

Using XMPP4R-Simple to check for activity.

Using XMPP4R--Simple these Ruby code snippets show a user's status change and any messages they may have sent you since the last time.

   1  
   2  # user1 changes their status to away
   3  jabber.presence_updates do |friend, old_presence, new_presence|
   4    puts "Received presence update from #{friend.to_s}: #{new_presence}"
   5  end
   6  
   7  # user1 sends the message "do you like Tofu?"
   8  jabber.received_messages do |message|
   9    puts "Received message from #{message.from}: #{message.body}"
  10  end
  11  


Reference: http://xmpp4r-simple.rubyforge.org/

Sending a message using XMPP and Ruby

This Ruby code shows how to send an instant message through XMPP [wikipedia.org] using XMPP4R [gna.org]. Source code origin: Ruby and XMPP/Jabber Part 2: Logging in and sending simple messages [famundo.com].

Preparation
- Installed eJabberd on my Gentoo server
- Created 2 user accounts using Pidgin Internet Messenger on my Ubuntu desktop.
- Tested sending messages using Jabber Instant Messaging (Gabber) and Pidgin Internet Messenger.

Installation
   1  gem install xmpp4r

What we will need
   1  
   2  require 'rubygems'
   3  require 'xmpp4r'
   4  include Jabber

Logging in
   1  
   2  jid = JID::new('yourname@yourdomain.com/Testing')
   3  password = 'yourpassword'
   4  cl = Client::new(jid)
   5  cl.connect
   6  cl.auth(password)

Sending a simple message
   1  
   2  to = "user2@yourdomain.com"
   3  subject = "XMPP4R test"
   4  body = "Hi, this is my first try from XMPP4R!!!"
   5  m = Message::new(to, body).set_type(:normal).set_id('1').set_subject(subject)
   6  cl.send m

References:
- Building a Twitter Agent with Ruby and Rails [rubyinside.com]
- http://gentoo-wiki.com/Ejabberd

* update 15:45 18-Feb-08 *
Here's a simpler example I found from Liminal Existence: Announcing Jabber::Simple [romeda.org]

sudo gem install xmpp4r-simple
   1  
   2  require 'xmpp4r-simple'
   3  
   4  jabber = Jabber::Simple.new('yourname@yourdomain.com', 'yourpassword')
   5  jabber.deliver("user1@yourdomain.com", "Hey! I'm thinking of going Vegetarian - Any suggestions?")


see also: IM Integration With XMPP4r : Part 2 [rubyfleebie.com]

PHP Copyright Updater

// PHP Copyright Updater
// by Evan Walsh
// NothingConcept.com

This code will automatically change the copyright on your site as the year changes. Tested and approved by me.

Just call this in one of your PHP files by including the file with this code in it:

   1  
   2  <?php
   3  //Licensed under the GPL v2
   4  //by Evan Walsh of nothingconcept.com
   5  function copyright($site,$year) {
   6      $current = date(Y);
   7      if($year == $current) { $eyear = $year; }
   8      else { $eyear = "$year - $current"; }
   9      echo "All content &copy; $eyear $site";
  10  }
  11  ?>


Example: <?php include('functions.php'); ?>

Then place <?php copyright("Sitename","2007"); ?> or something similar in the place you want the copyright to display.

Simple as that.

RSS Reader - Reads Name and URL into HashMap

// description of your code here
// RSS reader for web reads them into HashMap

   1  
   2  
   3  
   4  /**
   5   * Created by IntelliJ IDEA.
   6   * User: Rapid
   7   * Date: Oct 9, 2006
   8   * Time: 3:18:23 PM
   9   * To change this template use File | Settings | File Templates.
  10   */
  11  import java.net.URL;
  12  import java.util.Iterator;
  13  import java.util.HashMap;
  14  
  15  import com.sun.syndication.feed.module.Module;
  16  import com.sun.syndication.feed.synd.SyndEntry;
  17  import com.sun.syndication.feed.synd.SyndFeed;
  18  import com.sun.syndication.io.SyndFeedInput;
  19  import com.sun.syndication.io.XmlReader;
  20  
  21  /**
  22   * Reads and prints any RSS/Atom feed type. Adopted from the example by the
  23   * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
  24   *
  25   */
  26  public class FeedReader {
  27  
  28  
  29      HashMap hm = null;
  30      String[][] rss = null ;
  31      SyndFeedInput input ;
  32      URL feedUrl;
  33      SyndFeed feed ;
  34      int count =-1;
  35  
  36  
  37      public HashMap readRSS(String url) {
  38          boolean readOk = false;
  39  
  40              try {
  41  
  42                  hm = new HashMap();
  43  
  44                 feedUrl  = new URL(url);
  45  
  46                  input  = new SyndFeedInput();
  47                   feed = input.build(new XmlReader(feedUrl));
  48  
  49                  System.out.println("Title: " + feed.getTitle());
  50                  System.out.println("Author: " + feed.getAuthor());
  51                  System.out.println("Description: " + feed.getDescription());
  52                  System.out.println("Pub date: " + feed.getPublishedDate());
  53                  System.out.println("Copyright: " + feed.getCopyright());
  54                  System.out.println("Modules used:");
  55  
  56  
  57  
  58                  String metaRSS = "Title: " + feed.getTitle() + "\n" +
  59                  "Author: " + feed.getAuthor()  + "\n" +
  60                   "Description: " + feed.getDescription()  + "\n" +
  61                   "Pub date: " + feed.getPublishedDate()  + "\n" +
  62                   "Copyright: " + feed.getCopyright() ;
  63  
  64  
  65  
  66  
  67                  rss = new String[ feed.getEntries().size()][2];
  68  
  69  
  70                  System.out.println("Titles of the " + feed.getEntries().size() +
  71                                     " entries:");
  72                  for (final Iterator iter = feed.getEntries().iterator();
  73                       iter.hasNext();)
  74                  {
  75  
  76  
  77  
  78  
  79  
  80  
  81                      rss[++count][0] =      ((SyndEntry)iter.next()).getTitle().toString();
  82  
  83  
  84  
  85  
  86                  }
  87                  count = -1 ;
  88                  for (final Iterator iter = feed.getEntries().iterator();
  89                       iter.hasNext();)
  90                  {
  91  
  92                     rss[++count][1] =      ((SyndEntry)iter.next()).getUri().toString();
  93                  }
  94  
  95  
  96                  if (feed.getImage() != null)
  97                  {
  98                      System.out.println("Feed image URL: " +
  99                                         feed.getImage().getUrl());
 100                  }
 101  
 102                  readOk = true;
 103                  hm.put( feed.getTitle(), rss);
 104              }
 105              catch (Exception ex) {
 106                  ex.printStackTrace();
 107                  System.out.println("ERROR: " + ex.getMessage());
 108              }
 109  
 110  
 111          String[][] rs = (String[][])hm.get("LinuxInsider");
 112  
 113            System.out.println("************************");
 114          for( int i=0; i<rs.length; i++){
 115  
 116              System.out.println( rs[i][0]);
 117               System.out.println( rs[i][1]);
 118  //             System.out.println( rs[i][2]);
 119          }
 120          if (! readOk) {
 121              System.out.println();
 122              System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
 123              System.out.println("The first parameter must be the URL of the feed to read.");
 124              System.out.println();
 125          }
 126  
 127          return hm;
 128      }
 129  
 130  }
« Newer Snippets
Older Snippets »
Showing 1-10 of 19 total  RSS