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

ProjectX client-side code

This Ruby code uses a unified XML format to create a password record on a web server. It's intended to be run as a batch file which gets called from another Ruby application called maintain_projectx which gets called from a cronjob.

In this example the password is stored on the server not for authentication but simply to provide a reminder service in the event the user forgets it.

require 'net/http'
require 'rexml/document'
include REXML

class ProjectXClient
  attr :doc
  def initialize(raw_url)
    url = URI.escape(raw_url)
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    @doc = Document.new(xml_data)
  end
  
end

if __FILE__ == $0

  xml_project = <<PROJECT
  <project name='password'>
    <method name='create'>
      <params>
        <param var='password' val='p6789c'/>
        <param var='title' val='hotmail'/>
      </params>
    </method>
  </project>
PROJECT
  
  pxc = ProjectXClient.new("http://yourdomain.com/p/projectx.cgi?xml_project=" + xml_project)
  doc = pxc.doc
  puts doc
    
end


output -what's returned from the server is an XML response containing a result. The result echos the method executed and the output from that method, which in this instance is the xml record node 'entry'.
<result method='rtn_create'>
  <append id='19367'>
    <entry id='19367'>
      <password>p6789c</password>
      <title>hotmail</title>
      <description/>
    </entry>
  </append>
</result>


Getting Started With WWW::Mechanize

This Ruby code uses WWW:mechanize to act like a web browser.

 require 'rubygems'
 require 'mechanize'

 agent = WWW::Mechanize.new
 page = agent.get('http://google.com/')


Refer to the documentation at http://mechanize.rubyforge.org/mechanize/. Then gem install mechanize, and try running the code in an irb session.

output (extract):
=> #<WWW::Mechanize::Page
 {url #<URI::HTTP:0xfdbbbb286 URL:http://www.google.com/>}
 {meta}
 {title "Google"}
 {iframes}
 {frames}
 {links
  #<WWW::Mechanize::Page::Link
   "Images"
   "http://images.google.com/imghp?hl=en&tab=wi">
  #<WWW::Mechanize::Page::Link
   "Maps"
   "http://maps.google.com/maps?hl=en&tab=wl">
  #<WWW::Mechanize::Page::Link
   "News"
   "http://news.google.com/nwshp?hl=en&tab=wn">
  #<WWW::Mechanize::Page::Link
   "Shopping"
   "http://www.google.com/prdhp?hl=en&tab=wf">
  #<WWW::Mechanize::Page::Link
   "Gmail"
   "http://mail.google.com/mail/?hl=en&tab=wm">

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");
    }
}
}

Reading an xml file from a URL and saving it locally

// description of your code here
This code reads an xml file, modifys an element and saves the file locally.
require 'net/http'
require 'rexml/document'

url = 'http://www.example.com/journal080907.xml'

element_name = ARGV[0] # basic_category
xpath = ARGV[1] # eg.'entries/entry'
file = ARGV[2] # eg. 'journal080907.xml'
element_value = ARGV[3] # 'ruby'

file = File.new(file,'w')
# get the XML data as a string
xml_data = Net::HTTP.get_response(URI.parse(url)).body

# extract event information
doc = REXML::Document.new(xml_data)
docx = doc

node = docx.elements[xpath]
element = node.elements[element_name]
puts element.text
element.text = 'ruby'
file.puts docx

Acceder a la fecha en la que una foto fue tomada en VB .NET

//Función a la que se le pasa el archivo jpg o jpge y devuelve la fecha en la que fue tomada

    Public Function ObtieneFecha(ByVal RutaArchivo As String) As Date

        Dim image As New Bitmap(RutaArchivo)
        Dim propItems As System.Drawing.Imaging.PropertyItem() = image.PropertyItems

        Dim encoding As New System.Text.ASCIIEncoding

        For i As Integer = propItems.GetLowerBound(0) To propItems.GetUpperBound(0)
            If propItems(i).Id.ToString = "36868" Then
                Dim strAux1() As String = Split(encoding.GetString(propItems(i).Value), " ")
                Dim strAux2() As String = Split(strAux1(0), ":")
                Dim strAux3() As String = Split(strAux1(1), ":")
                Return CDate(strAux2(0) & "/" & strAux2(1) & "/" & strAux2(2) & " " & strAux3(0) & ":" & strAux3(1) & ":" & strAux3(2))
            End If
        Next
        image.Dispose()
    End Function

Python - getFile Internet

// Scaricare un file dalla rete

package get.file.example;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class GetFileExample
{
	public GetFileExample()
	{
		try
		{
			byte[] bite = new byte[2048];
			int read;
			URL url = new URL("http://switch.dl.sourceforge.net/sourceforge/pys60miniapps/FlickrS60_src_v0.1b.tar.bz2");
			
			BufferedInputStream bis = new BufferedInputStream(url.openStream());
			FileOutputStream fos = new FileOutputStream("/tmp/file.tar.bz2");
			
			while((read = bis.read(bite))>0)
			{
				fos.write(bite, 0, read);
				System.out.println("--");
			}
			
			fos.close();
			bis.close();
			
			System.out.println("FINE");
			
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args)
	{
		new GetFileExample();
	}
}

Use the del.icio.us API via HTTPS from Ruby

Found at http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

require 'net/https'
require "rexml/document"

username = "" # your del.icio.us username
password = "" # your del.icio.us password

resp = href = "";
begin      
  http = Net::HTTP.new("api.del.icio.us", 443)
  http.use_ssl = true
  http.start do |http|
    req = Net::HTTP::Get.new("/v1/tags/get", {"User-Agent" => 
        "juretta.com RubyLicious 0.2"})
    req.basic_auth(username, password)
    response = http.request(req)
    resp = response.body
  end     
  #  XML Document
  doc = REXML::Document.new(resp)    
  # iterate over each element <tag count="200" tag="Rails"/>
  doc.root.elements.each do |elem|
    print elem.attributes['tag']  + " -> " + elem.attributes['count'] + "\n"
  end
  
rescue SocketError
  raise "Host " + host + " nicht erreichbar"
rescue REXML::ParseException => e
  print "error parsing XML " + e.to_s
end

Removing accents in NET 2.0 with C#

Removing accents in NET 2.0

static string UrlSanitize(string url)
{
	url = Regex.Replace(url, @"\s+", "-");
	string stFormD = url.Normalize(NormalizationForm.FormD);
	StringBuilder sb = new StringBuilder();
 
	for (int ich = 0; ich < stFormD.Length; ich++)
	{
		UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
		if (uc != UnicodeCategory.NonSpacingMark)
		{
			sb.Append(stFormD[ich]);
		}
	}
 
	return (sb.ToString());
}

conectarte a una base de datos con .net

// description of your code here

SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;

String s = null;
Product prod = null;

try
{
	conn = new SqlConnection("Provider=SQLOLEDB;SERVER=sissql2;UID=sa;PWD=AlfaRoma440;DATABASE=genericatest2");

	s = " ";


	cmd = new SqlCommand(s,conn);
	dr = cmd.ExecuteReader();
	// lleno el objeto producto

	while( dr.Read())
	{

	}


}
catch (Exception ex)
{
	// poner el manejo de errores	
}
finally
{
	dr.Close();
	conn.Close();
}
dr.Close();
conn.Close();
return prod;
}

URI Parse

// description of your code here

require 'net/http'
res = Net::HTTP.get_response(URI.parse('http://www.example.com'))
print res.body
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS