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

Helpful XPath examples

A few XPath examples copied from XPath Syntax [w3schools.com]

Predicates
/bookstore/book[1] 	# Selects the first book element that is the child of the bookstore element. 
                        # Note: IE5 and later has implemented that [0] should be the first node, 
                        # but according to the W3C standard it should have been [1]!!
/bookstore/book[last()] 	# Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] 	# Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] 	# Selects the first two book elements that are children of the bookstore element
//title[@lang] 	# Selects all the title elements that have an attribute named lang

Selecting Unknown Nodes
/bookstore/* 	# Selects all the child nodes of the bookstore element
//* 	# Selects all elements in the document
//title[@*] 	# Selects all title elements which have any attribute

Selecting Several Paths
//book/title | //book/price  	# Selects all the title AND price elements of all book elements

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

#!/usr/bin/ruby

#file: ruby2html.rb 

require 'rubygems'
require 'syntax/convertors/html'
require 'projxslt' # <- this is my own class to do an XSLT transform 
require 'rexml/document'
include REXML

class Ruby2Html
  def initialize(rubyfile, htmlfile)
    code = File.read(rubyfile)
    convertor = Syntax::Convertors::HTML.for_syntax "ruby"
    code_html = convertor.convert(code)
    
    tempfile = '../temp/ruby2html.xml'
    xslfile = '../ruby2html/ruby2html.xsl'
    save_file(tempfile, code_html)
    
    px = Projxslt.new(tempfile, xslfile)
    buffer = px.transform()
    save_file(htmlfile, buffer)
    
  end
  
  def save_file(filename, buffer)
    file = File.new(filename, 'w')
    file.puts buffer
    file.close
  end
end

if __FILE__ == $0
  r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  puts 'completed'
end

file: ruby2html.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml"
                version="1.0">

  <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
          doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
          encoding="ISO-8859-1"/> 

	<xsl:template match="/">
	<xsl:element name="html">

        <head>
          <title>Sample code</title>
          <link rel="stylesheet" type="text/css" href="ruby2html.css" />
	</head>

	<body>
          <div id="wrap">
          <xsl:apply-templates />
          </div>
	</body> 

	</xsl:element>
	</xsl:template>

	<xsl:template match="pre">
	  <xsl:copy-of select="."/>
	</xsl:template>

</xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

Syntax-at-a-Glance for the C# programming language

// Copyright (C) 2001 StructureByDesign. All Rights Reserved.

// CLASS1.CS -- Syntax-at-a-Glance for the C# programming language.
// A quick code reference for programmers who work in many languages.
// Executable code, minimal comments document the essence of the language.


using System;
using System.Collections;
using System.IO;

namespace StructureByDesign.Syntax
{
public class Class1: Object
{
    public static int Main(string[] args)       // Entry point.
    {
        System.Console.WriteLine("Hello");
        Class2 aclass2 = new Class2();
        aclass2.run();
        return 0;
    }
}

interface Interface1
{
    void run();
}

class Class2: Class1, Interface1
{
    public const int CONSTANT = 1;          // Access not restricted, implicitly static.
    private int m_intPrivateField;          // Access limited to containing type.
    public Class2() : base()                // Constructor.
    {
        initialize();
    }
    protected void initialize()             // Object initialization.
    {                                       // Access limited to containing class or types derived.
        Number = 1;
    }
    protected int Number                    // Language property feature.
    {
        get
        {
            return m_intPrivateField;
        }
        set
        {
            m_intPrivateField = value;      // Implicit parameter.
        }
    }
    public void run()
    {
        anonymousCode();
        arrays();
        collections();
        comparison();
        control();
        filesStreamsAndExceptions();
        numbersAndMath();
        primitivesAndConstants();
        runtimeTyping();
        strings();
    }
    void anonymousCode()
    {
        Delegate adelegate = new Delegate(Run);
        adelegate();
    }
    delegate void Delegate();
    void Run()
    {
        Console.WriteLine("Run");
    }
    void arrays()
    {
        int[] arrayOfInts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        arrayOfInts[0] = 9;
        assert(arrayOfInts[0] == arrayOfInts[9]);

        String[] arrayOfStrings = new String[10];
        assert(arrayOfStrings[0] == null);
        assert(arrayOfStrings.Length == 10);

        arrayOfStrings = new String[] { "one", "two" };

        byte[,] arrayOfBytes = { {0,0,0},
                                 {0,1,2},
                                 {0,2,4}};
        assert(arrayOfBytes[2,2] == 4);
    }
    void collections()
    {
        IList ailist = new ArrayList();
        ailist.Add("zero"); ailist.Add("one"); ailist.Add("three");
        ailist[2] = "two";
        assert(ailist[2].Equals("two"));
        ailist.Remove("two");
        ((ArrayList)ailist).Sort();
        for(IEnumerator aie = ((ArrayList)ailist).GetEnumerator(); aie.MoveNext(); )
            ;
        foreach(String astring in ailist)
            ;

        IDictionary aidictionary = new Hashtable();
        aidictionary.Add("key", "value");
        assert(aidictionary["key"].Equals("value"));

        // Set not available.
    }
    void comparison()
    {
        int aint1 = 1;
        int aint2 = 2;
        int aint = 1;
        String astring1 = "one";
        String astring2 = "two";
        String astring = astring1;

        assert(aint == aint1);
        assert(aint1 != aint2);
        assert(astring == astring1);
        assert(astring1 == String.Copy("one"));         // For strings == is overloaded to compare values.
        assert(!astring1.Equals(astring2));
        assert(astring1.Equals(String.Copy("one")));

        astring = null;
        if (astring != null && astring.Length > 0)      // Conditional evaluation.
            assert(false);

        if (aint2 < 0 || 1 < aint2)
            assert(true);
    }
    void control()
    {
        if (true)
            assert(true);
        else
            assert(false);
        /////
        switch ('b') {
            case 'a':
                assert(false);
                break;
            case 'b':
                assert(true);
                break;
            default:
                assert(false);
                break;
        }
        /////
        for (int ai1 = 0; ai1 < 10; ai1++)
            assert(true);
        /////
        int ai = 0;
        while (ai < 10) {
            assert(true);
            ai++;
        }

        do
            ai--;
        while (ai > 0);

        for (int x = 0; x < 10; x++)        // Labeled break/continue not available.
            for (int y = 0; y < 10; y++)
                if (x == 9)
                    break;
                else
                    continue;
    }
    void filesStreamsAndExceptions()
    {
        FileInfo afileinfo = new FileInfo("list.txt");
        try {
            StreamWriter asw = new StreamWriter("list.txt");
            asw.WriteLine("line");
            asw.WriteLine("line");
            asw.Close();

            assert(afileinfo.Exists);

            StreamReader asr = new StreamReader("list.txt");
            String astringLine;
            while ((astringLine = asr.ReadLine()) != null)
                assert(astringLine.Equals("line"));
            asr.Close();
        } catch (IOException aexception) {
            System.Console.WriteLine(aexception.Message);
            throw new NotSupportedException();
        }
        finally {
            afileinfo.Delete();
        }
    }
    void numbersAndMath()
    {
        assert(Int32.Parse("123") == 123);
        assert(123.ToString().Equals("123"));

        assert(Math.PI.ToString("n3").Equals("3.142"));

        assert(Int32.MaxValue < Int64.MaxValue);

        assert(Math.Abs(Math.Sin(0) - 0) <= Double.Epsilon);
        assert(Math.Abs(Math.Cos(0) - 1) <= Double.Epsilon);
        assert(Math.Abs(Math.Tan(0) - 0) <= Double.Epsilon);

        assert(Math.Abs(Math.Sqrt(4) - 2) <= Double.Epsilon);
        assert(Math.Abs(Math.Pow(3,3) - 27) <= Double.Epsilon);

        assert(Math.Max(0,1) == 1);
        assert(Math.Min(0,1) == 0);

        assert(Math.Abs(Math.Ceiling(9.87) - 10.0) <= Double.Epsilon);
        assert(Math.Abs(Math.Floor(9.87) - 9.0) <= Double.Epsilon);
        assert(Math.Round(9.87) == 10);

        Random arandom = new Random();
        double adouble = arandom.NextDouble();
        assert(0.0 <= adouble && adouble < 1.0);
        int aint = arandom.Next(10);
        assert(0 <= aint && aint < 10);
    }
    enum Season: byte { Spring=0, Summer, Fall, Winter };

    void primitivesAndConstants()
    {
        bool abool = false;
        char achar = 'A';           // 16 bits, Unicode

        byte abyte = 0x0;           // 8 bits, unsigned, hex constant
        sbyte asbyte = 0;           // 8 bits, signed

        short ashort = 0;           // 16 bits, signed
        ushort aushort = 0;         // 16 bits, unsigned

        int aint = 0;               // 32 bits, signed
        uint aunit = 0;             // 32 bits, unsigned

        long along = 0L;            // 64 bits, signed
        ulong aulong = 0;           // 64 bits, unsigned

        float afloat = 0.0F;        // 32 bits
        double adouble = 0.0;       // 64 bits

        decimal adecimal = 0;       // 128 bits, financial calculations

        Season aseason = Season.Fall;
        assert((byte)aseason == 2);
    }
    void runtimeTyping()
    {
        assert(new int[] { 1 } is int[]);
        assert(new ArrayList() is ArrayList);

        assert((new ArrayList()).GetType() == typeof(ArrayList));
        assert(typeof(Int32) is Type);      // Type of primitive type.

        assert(Type.GetType("System.Collections.ArrayList") == typeof(ArrayList));
    }
    void strings()
    {
        String astring1 = "one";
        String astring2 = "TWO";

        assert((astring1 + "/" + astring2).Equals("one/TWO"));
        assert(astring2.ToLower().Equals("two"));   // Equals ignoring case not available.
        assert(astring1.Length == 3);
        assert(astring1.Substring(0,2).Equals("on"));
        assert(astring1[2] == 'e');
        assert(astring1.ToUpper().Equals("ONE"));
        assert(astring2.ToLower().Equals("two"));
        assert(astring1.CompareTo("p") < 0);
        assert(astring1.IndexOf('e') == 2);
        assert(astring1.IndexOf("ne") == 1);
        assert(astring1.Trim().Length == astring1.Length);

        assert(Char.IsDigit('1'));
        assert(Char.IsLetter('a'));
        assert(Char.IsWhiteSpace('\t'));
        assert(Char.ToLower('A') == 'a');
        assert(Char.ToUpper('a') == 'A');
    }
    private void assert(bool abool)
    {
        if (!abool)
            throw new Exception("assert failed");
    }
}
}

DELETE - SQL

// description of your code here

DELETE ... 
    [ FROM ... ] 
    [ ... JOIN ... ] 
    [ WHERE ... ] 

// FULL Syntax follows:
DELETE [ FROM ] 
    {
       [ database. ] [ owner. ] table_name 
         [
           WITH (  INDEX ( Index_1,   [ index_2,  ...,  n ] ) 
                      | FASTFIRSTROW 
                      | HOLDLOCK 
                      | PAGLOCK 
                      | READCOMMITTED 
                      | REPEATABLEREAD 
                      | ROWLOCK 
                      | SERIALIZABLE 
                      | TABLOCK 
                      | TABLOCKX 
                      [   ...   n  |  ...,  n ] 
                     )
       ]
     |
       OPENQUERY( server, 'query' ) 
     |
       OPENROWSET( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) 
     |
       view_name 
    }

    [
      FROM 
      {
          derived_table 
            [ [ AS ] table_alias ]
            [ ( column_alias_1,   [ column_alias_2,   ...,  n ]  )  ]
        |
          CONTAINSTABLE ( table, column  |  *, 'search_conditions' ) 
            [ [ AS ] table_alias ]
        |
          FREETEXTTABLE ( table, column  |  *, 'free_text_string' ) 
            [ [ AS ] table_alias ]
        |
          table_name [ [ AS ] table_alias ]
            [
               WITH (  INDEX ( Index_1,   [ index_2,   ...,  n ]  ) 
                          | FASTFIRSTROW 
                          | HOLDLOCK 
                          | NOLOCK 
                          | PAGLOCK 
                          | READCOMMITTED 
                          | READPAST 
                          | READUNCOMMITTED 
                          | REPEATABLEREAD 
                          | ROWLOCK 
                          | SERIALIZABLE 
                          | TABLOCK 
                          | TABLOCKX 
                          | UPDLOCK 
                          [ ...   n  |  ...,  n ] 
                         )
            ]
        |
          view_name [ [ AS ] table_alias ]
      }





      [
          INNER JOIN  |  LEFT [ OUTER ] JOIN  |  RIGHT [ OUTER ] JOIN 
            {
               derived_table [ ON search_conditions ]
             |
               OPENQUERY( server, 'query' ) [ ON search_conditions ]
             |
               OPENROWSET
                               ( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) [ ON search_conditions ]
             | 
               table_name [ ON search_conditions ]
             | 
               view_name [ ON search_conditions ]
            }
            [   ...,  n ]
          |
          CROSS JOIN  |  FULL [ OUTER ] JOIN 
            {
               derived_table 
             | 
               OPENQUERY( server, 'query' ) 
             |
               OPENROWSET
                               ( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) 
             | 
               table_name 
             | 
               view_name 
            }
            [   ...,  n ]
       ]
   ] 

   [
      {
         WHERE search_conditions 
       |
         WHERE CURRENT OF [ GLOBAL ] cursor_name 
       |
         WHERE CURRENT OF cursor_variable_name 
      }
         [
           OPTION (  FAST number_rows 
                          | FORCE ORDER 
                          | HASH GROUP 
                          | ORDER GROUP 
                          | HASH JOIN 
                          | LOOP JOIN 
                          | MERGE JOIN 
                          | KEEP PLAN 
                          | MAXDOP 
                          | ROBUST PLAN 
                          | CONCAT UNION 
                          | HASH UNION 
                          | MERGE UNION 
                          [   ...,  n ]
                        )
         ]
   ]

//Full explanation follows:

KEYWORDS Keywords are denoted with upper case letters. Obey the spelling.

variables All user-supplied variables are denoted with lower case letters.

..., n Signifies that there can be more than one value in a comma delimited list. Note that the dots and n are not part of the code and must not appear in the SQL query.

... n Signifies that there can be more than one value in a blank space delimited list. Note that the dots and n are not part of the code and must not appear in the SQL query.

{ } Signifies that all, or some portion, of the code elements between the braces are required elements and must appear in the SQL query. Note that these braces are not part of the code and must not appear in the SQL query.

[ ] Signifies that the code elements between the square brackets can optionally appear in the SQL query, but are not required. Note that these brackets are not part of the code and must not appear in the SQL query.

| The or symbol signifies that you may use only one of the code elements or values from the possible choices. Note that the or symbol is not part of the code and must not appear in the SQL query.

Visit Python Abstract Syntax Tree

Simplest AST visitor. More on this blog post :
http://www.biais.org/blog/index.php/2007/01/10/9-visit-python-abstract-syntax-tree

import compiler
 
class CodePrinter:
    def __init__(self):
        self.src = ''
 
    def visitName(self,t):
        self.src += t.name
 
    def visitConst(self,t):
        self.src += str(t.value)
 
    def visitStmt(self, t):
        for i in t:
            a = pretty_print(i)
            self.src += a + "\n"
 
    def visitAssName(self, t):
        self.src += t.name + " = "
 
def pretty_print(node):
    myvisitor = CodePrinter()
    # compiler.walk return the visitor instance : 2nd arg
    return compiler.walk(node, myvisitor).src

Syntax highlighting with vim & Ruby

From: http://www.ruby-forum.com/topic/64262

This snippet will convert source code files to syntax-colored html files.
usage: vim-syntax-highlighting.rb src.rb src.html



require 'tempfile'

$VERBOSE=nil
STDERR.reopen(Tempfile::new($$)) unless STDIN.tty?

fin, fout, _ = ARGV
fin = ((fin.nil? or fin == '-') ? STDIN : open(fin))
fout = ((fout.nil? or fout == '-') ? STDOUT : open(fout,'w+'))

ts = Tempfile::new($$), Tempfile::new($$)
ts[0].write fin.read
ts.each{|t| t.close}
command = %Q( vim -f +'syn on' +'set filetype=ruby' +'set background=light' +'run! syntax/2html.vim' +'w! #{ ts[1].path }' +'qa!' - < #{ ts[0].path } > /dev/null 2>&1 )
#command = %Q( vim -f +'syn on' +'set filetype=c' +'set background=dark' +'run! syntax/2html.vim' +'w! #{ ts[1].path }' +'qa!' - < #{ ts[0].path } > /dev/null 2>&1 )
system command
ts.each{|t| t.open; t.rewind}
fout.write(ts[1].read)
ts.each{|t| t.close!}

General Delimited Input in Ruby

In ruby there are several special literal notations:

%{blah}       # or %Q{blah} # same as "blah" but igornes " and '
%q{blah}      # same as 'blah' but no interpolation
%w{blah blah} # same as "blah blah".split
%r{blah}      # same as /blah/
%x{ls}        # same as `ls`

Latex2wiki

Translate a subset of LaTeX into MoinMoin wiki syntax.


#!/usr/bin/env python

#    Copyright (C) 2003, Maxime Biais <maxime@biais.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# $Id: latex2wiki.py,v 1.1.1.1 2004/03/14 18:31:50 max Exp $

import sys, re

def dummy(d):
    pass

NONE = "__@NONE@__"

tr_list = [
    (r"\\includegraphics.*{(.*)\.eps}", "attachment::%s.png", dummy),
    (r"\\caption{.*}", "", dummy),
    (r"\\label{.*}", "", dummy),
    (r"(.*)\\emph{(.*)}(.*)", """%s'''%s'''%s""", dummy),
    (r"\\item (.*)", " * %s", dummy),
    (r"\\begin{.*}", "", dummy),
    (r"\\end{.*}", "", dummy),
    (r"(.*)``(.*)''(.*)", "%s\"%s\"%s", dummy),
    (r"\\chapter{(.*)}", NONE, dummy),
    (r"\\paragraph{(.*)}", "==== %s ====", dummy),
    (r"\\subsubsection{(.*)}", "==== %s ====", dummy),
    (r"\\subsection{(.*)}", "=== %s ===", dummy),
    (r"\\section{(.*)}", "== %s ==", dummy),
    (r"(.*)\\fig{.*}(.*)", "%s suivant %s", dummy)
    ]

in_stream  = open(sys.argv[1], "r")
if len(sys.argv) < 3:
    out_stream = sys.stdout
else:
    out_stream = open(sys.argv[2], "w")


for i in in_stream.readlines():
    cur_write = 0
    for reg in tr_list:
        m = re.search(reg[0], i)
        if m:
            reg[2](i)
            cur_write = 1
            if reg[1] == NONE:
                break
            print >> out_stream, reg[1] % m.groups()
            break
    if not cur_write:
        out_stream.write(i)

A replacement for Ruby's File.join

File.join is ugly, there I've said it. So how about being able to replace this:

require File.join(LOAD_PATH, 'foobar')


With this:

require LOAD_PATH/:foobar


Trivial, really:

class String
  def /(o)
    File.join(self, o.to_s)
  end
end

Check the syntax of a bunch of PHP files all at once

Will find all files ending with 'php' and execute the syntax check of php for every found file. Useful if you quickly want to see which php file contains a parse error.

find ./ -type f -name \*.php -exec php -l {} \;
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS