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 17 total  RSS 

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.

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

#center-me { /* There can be only one Centerlander! */
  height: 100%;
  display: table !important;
  margin: auto;
}

#center-me > * {
  display: table-cell !important; /* Don't touch me! I MEAN IT! DON- ... don't touch me. Really, don't touch me. */
  vertical-align: middle !important;
}


<div id="center-me">
  <h1>I'm centered!</h1>
</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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* minimum required number of parameters */
#define MIN_REQUIRED 2

/* display usage */
int help() {
   printf("Usage: myprogram [-s <arg0>] [-n <arg1>] [-true]\n");
   printf("\t-s: a string a\n");
   printf("\t-n: a number\n");
   printf("\t-true: a single parameter\n");

   return 1;
}

/* main */
int main(int argc, char *argv[]) {
   if (argc < MIN_REQUIRED) {
      return help();
   }
   int i;

   /* iterate over all arguments */
   for (i = 1; i < (argc - 1); i++) {
       if (strcmp("-s", argv[i]) == 0) {
          /* do something with it */ 
          printf("string = %s\n", argv[++i]);
          continue;
       }
       if (strcmp("-n", argv[i]) == 0) {
          /* do something with it. for example, convert it to an integer */
          printf("number = %i\n", atoi(argv[++i]));
          continue;
       }
       if (strcmp("-true", argv[i]) == 0) {
          printf("true activated\n");
          continue;
       }
       return help();
   }
   return 0;
}

A simple XSLT example

Produce a list of filenames using XML and XSLT

file: dir.xsl
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>


file: dir.xml
<dir>
  <summary>
    <directory>./</directory>
  </summary>
  <records>
    <file type='xml'>mjournal.xml</file>
    <file type='rb'>projxmlhelper.rb</file>
    <file type='rb'>feedpopulated.rb</file>
    <file type='rb'>squrl_handler.rb</file>
    <file type='cgi'>snurl.cgi</file>
    <file type='cgi'>dynalert.cgi</file>
    <file type='rb'>password_handler.rb</file>
    <file type='rb'>category.rb</file>
    <file type='rb'>gwd.rb</file>
    <file type='cgi'>new-journal-entry.cgi</file>
  </records>
</dir>


then transforming the XML with the command 'xsltproc dir.xsl dir.xml' produces the following:
output:
<div id='articles'>
  <ul>
    <li>mjournal.xml</li>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>snurl.cgi</li>
    <li>dynalert.cgi</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
    <li>new-journal-entry.cgi</li>
  </ul>
</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.

# user1 changes their status to away
jabber.presence_updates do |friend, old_presence, new_presence|
  puts "Received presence update from #{friend.to_s}: #{new_presence}"
end

# user1 sends the message "do you like Tofu?"
jabber.received_messages do |message|
  puts "Received message from #{message.from}: #{message.body}"
end



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
gem install xmpp4r

What we will need
require 'rubygems'
require 'xmpp4r'
include Jabber

Logging in
jid = JID::new('yourname@yourdomain.com/Testing')
password = 'yourpassword'
cl = Client::new(jid)
cl.connect
cl.auth(password)

Sending a simple message
to = "user2@yourdomain.com"
subject = "XMPP4R test"
body = "Hi, this is my first try from XMPP4R!!!"
m = Message::new(to, body).set_type(:normal).set_id('1').set_subject(subject)
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
require 'xmpp4r-simple'

jabber = Jabber::Simple.new('yourname@yourdomain.com', 'yourpassword')
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:

<?php
//Licensed under the GPL v2
//by Evan Walsh of nothingconcept.com
function copyright($site,$year) {
    $current = date(Y);
    if($year == $current) { $eyear = $year; }
    else { $eyear = "$year - $current"; }
    echo "All content &copy; $eyear $site";
}
?>


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



/**
 * Created by IntelliJ IDEA.
 * User: Rapid
 * Date: Oct 9, 2006
 * Time: 3:18:23 PM
 * To change this template use File | Settings | File Templates.
 */
import java.net.URL;
import java.util.Iterator;
import java.util.HashMap;

import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * Reads and prints any RSS/Atom feed type. Adopted from the example by the
 * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
 *
 */
public class FeedReader {


    HashMap hm = null;
    String[][] rss = null ;
    SyndFeedInput input ;
    URL feedUrl;
    SyndFeed feed ;
    int count =-1;


    public HashMap readRSS(String url) {
        boolean readOk = false;

            try {

                hm = new HashMap();

               feedUrl  = new URL(url);

                input  = new SyndFeedInput();
                 feed = input.build(new XmlReader(feedUrl));

                System.out.println("Title: " + feed.getTitle());
                System.out.println("Author: " + feed.getAuthor());
                System.out.println("Description: " + feed.getDescription());
                System.out.println("Pub date: " + feed.getPublishedDate());
                System.out.println("Copyright: " + feed.getCopyright());
                System.out.println("Modules used:");



                String metaRSS = "Title: " + feed.getTitle() + "\n" +
                "Author: " + feed.getAuthor()  + "\n" +
                 "Description: " + feed.getDescription()  + "\n" +
                 "Pub date: " + feed.getPublishedDate()  + "\n" +
                 "Copyright: " + feed.getCopyright() ;




                rss = new String[ feed.getEntries().size()][2];


                System.out.println("Titles of the " + feed.getEntries().size() +
                                   " entries:");
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {






                    rss[++count][0] =      ((SyndEntry)iter.next()).getTitle().toString();




                }
                count = -1 ;
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {

                   rss[++count][1] =      ((SyndEntry)iter.next()).getUri().toString();
                }


                if (feed.getImage() != null)
                {
                    System.out.println("Feed image URL: " +
                                       feed.getImage().getUrl());
                }

                readOk = true;
                hm.put( feed.getTitle(), rss);
            }
            catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("ERROR: " + ex.getMessage());
            }


        String[][] rs = (String[][])hm.get("LinuxInsider");

          System.out.println("************************");
        for( int i=0; i<rs.length; i++){

            System.out.println( rs[i][0]);
             System.out.println( rs[i][1]);
//             System.out.println( rs[i][2]);
        }
        if (! readOk) {
            System.out.println();
            System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }

        return hm;
    }

}

RSS Reader - simple with Main

// description of your code here
//Reads rss from given url



/**
 * Created by IntelliJ IDEA.
 * User: Rapid
 * Date: Oct 9, 2006
 * Time: 3:18:23 PM
 * To change this template use File | Settings | File Templates.
 */
import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * Reads and prints any RSS/Atom feed type. Adopted from the example by the
 * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
 *
 */
public class FeedReader1 {

    public static void main(final String[] args) {
        boolean readOk = false;
        if (args.length == 1) {
            try {
                final URL feedUrl = new URL(args[0]);

                final SyndFeedInput input = new SyndFeedInput();
                final SyndFeed feed = input.build(new XmlReader(feedUrl));

                System.out.println("Title: " + feed.getTitle());
                System.out.println("Author: " + feed.getAuthor());
                System.out.println("Description: " + feed.getDescription());
                System.out.println("Pub date: " + feed.getPublishedDate());
                System.out.println("Copyright: " + feed.getCopyright());
                System.out.println("Modules used:");
                for (final Iterator iter = feed.getModules().iterator();
                     iter.hasNext();)
                {
                    System.out.println("\t" + ((Module)iter.next()).getUri());
                }
                System.out.println("Titles of the " + feed.getEntries().size() +
                                   " entries:");
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {
                    System.out.println("\t" +
                                       ((SyndEntry)iter.next()).getTitle());
                    
                }
                if (feed.getImage() != null)
                {
                    System.out.println("Feed image URL: " +
                                       feed.getImage().getUrl());
                }

                readOk = true;
            }
            catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("ERROR: " + ex.getMessage());
            }
        }

        if (! readOk) {
            System.out.println();
            System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }
    }
}

Simple Permutation //JavaScript Function



[UPDATED CODE AND HELP CAN BE FOUND HERE]


example

var a = ["A", "B", "C", "D"], j = permute(a);
document.write(
    "<h2>", a.join(" - "), " = ", j.length, "</h2>",
    j.join("<br />")
);


code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/permute [v1.0]

permute = function(v, m){ //v1.0
    for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
    for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
        ++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
    for(r = new Array(q); ++p < q;)
        for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i],
            x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
            for(x[3][i] = x[2][i], f = 0; !f; f = !f)
                for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
    return r;
};
« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS