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 11-20 of 21 total

Simple w3c Validator

// This function will return either a true or false (boolean) value, whether a certain site contains valid code based on w3 standards. Requires the Snoopy PHP class.
// Could be used in many situations where a simple "is valid" or "is not valid" result is required.

<?php
function w3Valid($url) {
	require("Snoopy.class.php");
	$snoopy = new Snoopy;

	$snoopy->fetchtext("http://validator.w3.org/check?uri=" . $url . "&output=soap12");
	$validator_output = $snoopy->results;

	if(preg_match("/false/", $validator_output)) {
		return false;
	} else {
		return true;
	}
}

?>

Amazon REST API for newLISP

;; (amazon-op "Operation=ItemSearch&SearchIndex=Books&ItemPage=1&Keywords=Cloud+Atlas&Respon\
seGroup=Request,Small")
;;
;; (amazon-op "Operation=SimilarityLookup&ItemId=1400063795,0812966929&SimilarityType=Random\
&ResponseGroup=Request,Large")
;; (amazon-op "Operation=SimilarityLookup&ItemId=1400063795,061873516X,0812966929&Similarity\
Type=Random&ResponseGroup=Request,Small")

;;  (setq x (xml-digest (amazon-op "Operation=ItemLookup&ItemId=0375507256&ResponseGroup=Req\
uest,Similarities,ListmaniaLists")))
;; Using x get a list of listmanias for an item
;;  (map (lambda (x) (x 1 2 2)) (1 -1 (x (chop (ref 'ListmaniaLists  x)))))

;; (setq y (amazon-op "Operation=ListLookup&ListType=Listmania&ListId=R21LV6VJEZ794O&Respons\
eGroup=ListFull"))
;; Using y get a list of ISBNs from a listmania
;; (map (lambda(x) (x 4 1 2 )) (8 -1 ( (y (chop (ref 'Lists y)) ) 2))) ; gives list of ISBNs\
 from the listmania

;; get a list of listmania details from a list of listmanias.
;;  (setq z   (map (lambda (x) (xml-digest (amazon-op (append "Operation=ListLookup&ListType\
=Listmania&ListId=" x "&ResponseGroup=ListFull"))))  (map (lambda (x) (x 1 2 2)) (1 -1 (x (c\
hop (ref 'ListmaniaLists  x))))))  )
;;
;; get a list of ISBNs from all of the listmanias for the item
;; (setq z (flat (map (lambda(y) (map (lambda(x) (x 4 1 2 )) (8 -1 ( (y (chop (ref 'Lists y)\
) ) 2))) ) z)))
;;

;; get item info for all the ISBNs from all listmanias related to the original item
;; (setq w (map (lambda (x) (xml-digest (amazon-op (append "Operation=ItemLookup&ItemId=" x)\
)))  (unique z)))

;; get a list of pair (title,author) from w above.
;; (map (lambda (x) (list ((x (chop (ref 'Title x))) 1)  (if (ref 'Author x)((x (chop (ref '\
Author x)))1) "???"))) w)

(define (amazon-op params)
  (get-url (append 
"http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&&AWSAccessKeyId=YOUROWNKEY&" params)))

(define (xml-digest result)
  (xml-type-tags nil nil nil nil)
  (setq xresult (xml-parse result (+ 1 2 4 8 16))))

library mashup

// description of your code here

;; combine APIs and other web available bibliographic data.
;; Use amazon, LibraryThing, and OCLC Worldcat.
;; Get ISBN numbers for a book by searching author and title.
;; Get the list of available ISBNs from different sources.
;; Get "tags" available for a book from LibraryThing for
;; a given book.
;; etc.
;;
;; N.B. A person from LibraryThing.com posted a comment
;; regarding this program, indicating that the tag cloud data
;; is copyrighted. 
;;
;; Here's the quoted message:
;;
;; Tim's message: "And it's fine here, as a test, and probably in other 
;; contexts where it could be considered "fair use" under copyright. 
;; But--unlike the thingISBN service and some other LibraryThing 
;; APIs--LibraryThing's tag clouds are not free for public use, 
;; outside of the RSS feeds and widgets we provide. 
;; We're not sure how and under what license to 
;; release them when we do."
;;
;; So, I wrote this for fun.  If I were you I wouldn't run it, just read
;; the code.  :-)
;;


(define (search-worldcat title author)
  (setq title (replace " " title "+"))
  (setq author (replace " " author "+"))
  (get-url (append "http://worldcatlibraries.org/search?q=ti:" title "+au:" author "&qt=advanced")))

(setq oclc-url-1-pattern {<div class="name"><a href=})

(define (oclc-url-1 str)
  (setq loc (find oclc-url-1-pattern str))
  (setq loc (+ loc (length oclc-url-1-pattern)))
  (setq loc (+ 1 loc))
  (setq loc-end (find ">" (loc -1 str)))
  (setq loc-end (- loc-end 1))
  (setq loc-url (loc loc-end str))
  (println (append "http://worldcatlibraries.org" loc-url))
  (get-url (append "http://worldcatlibraries.org" loc-url)))

(setq oclc-isbn-pattern "<strong>ISBN: </strong>")

(define (find-isbn str)
  (setq loc (find oclc-isbn-pattern str))
  (setq loc (+ loc (length oclc-isbn-pattern)))
  (setq loc-end (find "</li>" (loc -1 str)))
  (loc loc-end str))

(define (thing-isbn isbn)
  (xml-type-tags nil nil nil nil)
  (setq isbn-data 
      (xml-parse (get-url  
          (append "http://www.librarything.com/api/thingISBN/" isbn)))))

(define (get-isbn-list isbn-data)
  (setq indexer (ref "isbn" isbn-data))
  (nth-set 2 indexer 2)
  (setq num-isbns (length  (isbn-data 0)))
  (setq isbn-list '())
  (for (idx (first (1 indexer))  (- num-isbns 1))
        (push (isbn-data (first (0 indexer)) idx (first (2 indexer))) isbn-list -1))
   isbn-list)

(define (add-explorer-path)
   (env "PATH" (append (env "PATH" ) ";c:\\program files\\internet explorer")))

(define (show-amazon-isbn isbn)
   (process (append "iexplore " "http://www.amazon.com/exec/obidos/ASIN/"
           isbn )))


(define (get-librarything-isbn isbn)
    (get-url (append "http://librarything.com/isbn/" isbn)))

(define (get-librarything-tagsection str)
    (setq loc (find "Tags used" str ))
    (setq mystr (loc -1 str))
    (setq loc-end (find "</div>" mystr))
     (0 loc-end mystr))

(define (get-librarything-taglist mystr)
    (setq tags-list '())
    (while (setq tag-loc (find "/tag/" mystr))
        (setq tag-loc-end (find "target=" (tag-loc -1 mystr)))
        (push ((+ tag-loc 5) (- tag-loc-end 7) mystr) tags-list -1)
        (setq mystr ((+ tag-loc tag-loc-end ) -1 mystr)))
    tags-list)

(define (show-librarything-tag tag)
   (process (append "iexplore " "http://www.librarything.com/tag/"
           tag )))

Download recent flickr pictures with ruby and the flickr api

// To make this work, you need to get your own flickr api key.
// Get one here: http://www.flickr.com/services/api/misc.api_keys.html
// Other than that, just plug and chug and have fun!
// The "b" in "wb" in the second open method may not be necessary in
// non-windows environments.

require 'open-uri'
require 'rexml/document'

open('http://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=YOUR_KEY_HERE') { |f|
    doc = REXML::Document.new f.read
    i = 0
    doc.elements.each("rsp/photos/photo") { |element|
        if i < 3
            open("images/file" << i.to_s << ".jpg", "wb").
                write(open("http://static.flickr.com/" << \
                element.attributes["server"] << "/" << \
                element.attributes["id"] << "_" << \
                element.attributes["secret"] << "_o.jpg").read)
        else
            break
        end
        i = i + 1
    }
}

puts "Done!"

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

A Client For the XML-RPC Servlet

// When combined with the Apache XML-RPC library this code
// will let you call the servlet in the snippet "An XML-RPC
// Servlet". Of course, since XML-RPC is pretty ubiquitous
// you can also use this code to call servers in dozens of
// other languages as well.

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcClient;

public class XMLRPCTestClient {
    private static final String serverAddress = 
	"http://localhost:8080/lol/remoteapi";
    private static Log log = LogFactory.getLog(XMLRPCTestClient.class);
    
    /** Creates a new instance of XMLRPCTestClient */
    public XMLRPCTestClient(String address) {
        try {
            XmlRpcClient xmlrpc = new XmlRpcClient(address);

            Vector params = new Vector();
            params.addElement("Hello World! Hello!");

            try {
                // this method returns a string
                String result = (String) xmlrpc.execute("echo.echo", params);
                System.out.println(result);
            } catch (Exception e) {
                log.error("The remote procedure call failed.", e);
            }
        } catch (java.net.MalformedURLException mue) {
            log.error(
                "The address given for the XML-RPC interface is bad: " + address);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLRPCTestClient xmlRPCTestClient = new XMLRPCTestClient(
            serverAddress);
    }
}

An XML-RPC Servlet

// This depends upon the Apache XML-RPC library.

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcServer;

public class XmlRpcServlet extends HttpServlet {
    public class EchoHandler {
        public String echo(String input) {
            return input;
        }
    }
	
    private XmlRpcServer server = new XmlRpcServer();

    private static Log log = LogFactory.getLog(XmlRpcServlet.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
        server.addHandler("echo", new EchoHandler());
	}

	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        byte[] result = server.execute(request.getInputStream());
        
        response.setContentType("text/xml");
        response.setContentLength(result.length);
        
        OutputStream output = response.getOutputStream();
        output.write(result);
        output.flush();
    }
}


// The following needs to be added to your web.xml file to
// expose the servlet so it may be called remotely.
  <servlet>
    <servlet-name>XmlRpcServlet</servlet-name>
    <servlet-class>XmlRpcServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>XmlRpcServlet</servlet-name>
    <url-pattern>/remoteapi</url-pattern>        
  </servlet-mapping>    

get-version-ex API

REBOL [
    Title:   "Get Windows Version"
    File:    %get-version-ex.r
    Author:  "Gregg Irwin"
    Email:   greggirwin@acm.org
    Version: 0.0.1
    Date:    23-sep-2003
    Purpose: {
        Shows how to call Windows GetVersonEx function.
    }
    library: [
        level:    'intermediate
        platform: 'windows
        type:     [function how-to]
        domain:   [external-library win-api]
        tested-under: [view/pro 1.2.8.3.1 on W2K]
        support:  none
        license:  none
        see-also: none
    ]
]


; The credit for this technique of dealing with fixed char arrays
; in structs belongs to Pekr and Cyphre. I just modded the idea a
; bit for my own uses.
make-elements: func [name count type /local result][
    if not word? type [type: type?/word type]
    result: copy "^/"
    repeat i count [
        append result join name [i " [" type "]" newline]
    ]
    to block! result
]

kernel.dll: load/library %kernel32.dll


OSVERSIONINFOEXA: make struct! OSVERSIONINFOEXA-def: compose/deep [
    dwOSVersionInfoSize [integer!]  ; DWORD
    dwMajorVersion      [integer!]  ; DWORD
    dwMinorVersion      [integer!]  ; DWORD
    dwBuildNumber       [integer!]  ; DWORD
    dwPlatformId        [integer!]  ; DWORD
    (make-elements 'szCSDVersion 128 #"@")  ; TCHAR
    wServicePackMajor   [short]     ; WORD
    wServicePackMinor   [short]     ; WORD
    wSuiteMask          [short]     ; WORD
    wProductType        [char!]     ; BYTE
    wReserved           [char!]     ; BYTE
] none
OSVERSIONINFOEXA/dwOSVersionInfoSize: length? third OSVERSIONINFOEXA

GetLastError: make routine! [return: [integer!]] kernel.dll "GetLastError"

GetVersionEx: make routine! compose/deep/only [
    lpVersionInformation    [struct! (OSVERSIONINFOEXA-def)] ;LPOSVERSIONINFO
    return:     [integer!]  ;BOOL
] kernel.dll "GetVersionExA"

get-version: has [res] [
    res: GetVersionEx OSVERSIONINFOEXA
    either 0 = res [none][OSVERSIONINFOEXA]
]

; test call
print either res: get-version [
    [
        "Major:" res/dwMajorVersion newline
        "Minor:" res/dwMinorVersion newline
        "Build:" res/dwBuildNumber  newline
        "SP.Major:" res/wServicePackMajor   newline
        "SP.Minor:" res/wServicePackMinor   newline
        "Suite"   mold res/wSuiteMask    newline
        "Product" mold res/wProductType  newline
        "Version:" to-string copy/part at third OSVERSIONINFOEXA 21 128
    ]
][
    ["Call failed: " GetLastError]
]

free kernel.dll

halt

Win API drive info functions

REBOL []

win-drive: context [
    win-lib:  load/library %kernel32.dll

    null-buff: func [
        {Returns a null-filled string buffer of the specified length.}
        len [integer!]
    ][
        head insert/dup make string! len #"^@" len
    ]

    int-struct: make struct! [
        value   [integer!]
    ] none

    ; If all the requested information is retrieved,
    ; the return value is nonzero.
    GetVolumeInformation: make routine! compose/deep [
        RootPathName [string!]      ;LPCTSTR  address of root directory of the
                                    ;         file system
        VolumeNameBuffer [string!]  ;LPTSTR address of name of the volume
        VolumeNameSize   [integer!] ;DWORD  length of lpVolumeNameBuffer
        VolumeSerialNumber [struct! [(first int-struct)]]  ;LPDWORD// address of volume serial number
        MaximumComponentLength [struct! [(first int-struct)]] ;LPDWORD
                                       ;// address of system's maximum
                                       ;// filename length
        FileSystemFlags [struct! [(first int-struct)]]     ; LPDWORD// address of file system flags
        FileSystemNameBuffer [string!] ;LPTSTR // address of name of file system
        FileSystemNameSize [integer!]  ;DWORD  // length of FileSystemNameBuffer
        return: [integer!]
    ] win-lib "GetVolumeInformationA"


    get-volume-info: func [
        {Returns a block with volume-name, serial number, max. filename
        length, flags, and file system name if successful; otherwise NONE.}
        /with root
        /local vol-name file-sys-name ser-num max-filename-length flags res
    ][
        vol-name: null-buff 260
        file-sys-name: null-buff 260
        ser-num: make struct! int-struct [0]
        max-filename-length: make struct! int-struct [0]
        flags: make struct! int-struct [0]
        root: copy/part to-local-file either with [root][what-dir] 3
        res: GetVolumeInformation root
            vol-name length? vol-name
            ser-num max-filename-length flags
            file-sys-name length? file-sys-name

        either res <> 0 [
            reduce [trim vol-name ser-num/value max-filename-length/value flags/value trim file-sys-name]
        ][
            none
        ]
    ]

]

print mold win-drive/get-volume-info
print mold win-drive/get-volume-info/with %/d/
print mold win-drive/get-volume-info/with %/e/
print mold win-drive/get-volume-info/with %/f/
;print mold win-drive/get-volume-info/with %/a/

halt

Del.icio.us API with python

Taken from del.icio.us-py usage here.
>>> import delicious
>>> # add a post, user and passwd must be valid values for del.icio.us
>>> delicious.add('user', 'passwd', 'url', 'description', 'tag1 tag2', 
                  'extended', '2004-12-31T13:59:59Z')
True
>>> posts = delicious.get('user', 'passwd', count = 1)
>>> # posts is a list containing the post objects, these are dicts
>>> print posts
[{'url': u'url', 'dt': u''2004-12-31T13:59:59Z'', 'extended': u'extended', 
  'description': u'description', 'tags': 'tag1 tag2'}]
>>> posts[0]["tags"]
'tag1 tag2'
>>> delicious.delete('user', 'passwd', 'url')
True
>>>

>>> d = delicious.DeliciousAPI("user", "passwd")
>>> # DeliciousAPI offers all features of the API, see the docs for more
>>> posts = d.posts_all()                 # get all posts by user
>>> posts = d.posts_recent(tag = "tag1", count = 12)
>>> len(posts), type(posts)
(12,  <type 'dict'>)
>>> 

>>> d = delicious.DeliciousNOTAPI()
>>> # DeliciousNOTAPI offers access to features of delicious, that are not 
      accessible via its api
>>> posts = d.get_posts_by_user("username)
>>> posts = d.get_posts_by_tag("tag")
>>>
« Newer Snippets
Older Snippets »
Showing 11-20 of 21 total