Wednesday, March 30, 2011

Groovy++ Mixin and Category

@Typed
package categoriestest

@Category(List)
@Typed
class Shuffler {
    def shuffleit() {
        def result = new ArrayList(this)
        Collections.shuffle(result)
        result
    }
}

// @Mixin(Shuffler)
@Typed
class Sentence extends ArrayList {
    Sentence(Collection initial) { super(initial) }
}

@Typed
class Main {
    static main(args) {
        def words = ["The", "quick", "brown", "fox"]
        
        Sentence.mixin Shuffler.class

        def sentence = new Sentence(words)
        println sentence.shuffleit()
    }
}

Main.main(null)

http://gppconsole.appspot.com/script/20001

Tuesday, March 29, 2011

sqLite

@Grapes([    
   @Grab(group='org.xerial', module='sqlite-jdbc', version='3.7.2'),
   @GrabConfig(systemClassLoader=true)
 ])
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
import java.sql.PreparedStatement
import groovy.sql.Sql
import java.text.SimpleDateFormat

String databasefileName = "testDB.db" // this will write file to your system

Class.forName("org.sqlite.SQLite")
try {
    Sql.newInstance("jdbc:sqlite:"+databasefileName,"org.sqlite.JDBC")
    connection = DriverManager.getConnection("jdbc:sqlite:" + databasefileName)
    executeCommand = connection.createStatement().&executeUpdate

    executeCommand("drop table if exists myTable")

    String ct = "create table myTable (col1 string, col2 date, col3 string, col4 int)"
    executeCommand(ct)

    prepStatment = connection.prepareStatement("insert into myTable values(?, ?, ?, ?)")
} 
catch(SQLException e) { System.err.println("sql: " + e.getMessage()); return }

//populate table
updateSqLiteDB(connection, prepStatment)

Sql sql = new Sql(connection)
//run sql select statement
sql.eachRow("select * from myTable") {
    print(" col1 = " + it.getString("col1").padRight(5))
    print(" col2 = " + it.getDate("col2"))
    print(" col3 = " + it.getString("col3").padRight(15))
    println(" col4 = " + it.getInt("col4"))
}

//close connection
try { 
    if(connection != null) 
      connection.close();
} 
catch(SQLException e) { 
    // connection close failed. 
    System.err.println("sql: " + e) 
} 

////////////////////////////////END OF MAIN/////////////////////////////////

static void updateSqLiteDB(def connection, def prepStatment) {
    try {
        100.times { i ->
            String valCol1 = i.toString()
            Date valCol2 = (new java.sql.Date(111,0,15)) + i
            String valCol3 = (i.toString()) * 5
            Integer valCol4 = i * i
            prepStatment.setString(1, valCol1)
            prepStatment.setDate(2, valCol2)
            prepStatment.setString(3, valCol3)
            prepStatment.setInt(4, valCol4)
            prepStatment.addBatch()
        }
        connection.setAutoCommit(false);
        prepStatment.executeBatch();
        connection.setAutoCommit(true);
    }
    catch(SQLException e) { System.err.println("sql batch: " + e.getMessage()) } 
}

Scrape HTML

Note: This scrape no longer works correctly -- such are the dangers of screen scraping! ;)


@Grapes([
    @Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2')
    ,@Grab(group='net.sourceforge.nekohtml', module='nekohtml', version='1.9.14')
    //,@Grab(group='org.htmlcleaner', module='htmlcleaner', version='2.2')
    ]
)

import org.ccil.cowan.tagsoup.* //TagSoup
import org.cyberneko.html.parsers.SAXParser //NekoHTML
import org.htmlcleaner.* //not in maven -- http://htmlcleaner.sourceforge.net/, http://dist.wso2.org/maven2/org/htmlcleaner/htmlcleaner/

def url = new URL("http://lifehacker.com")


println "*" * 15 + 'TAG SOUP' + "*" * 15
slurper = new XmlSlurper(new Parser())
url.withReader { reader ->
    html = slurper.parse(reader)
    println findLinks(html).join('\n')
}


println "*" * 15 + 'NekoHTML' + "*" * 15
def parser = new SAXParser()
parser.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment",true)
html = new XmlSlurper(parser).parseText(url.text)
println findLinks(html).join('\n')

/*
println "*" * 15 + 'HTMLCleaner' + "*" * 15
def cleaner = new HtmlCleaner()
def node = cleaner.clean(url)
def props = cleaner.getProperties()
def serializer = new SimpleXmlSerializer(props)
def xml = serializer.getXmlAsString(node)
def page = new XmlSlurper(false,false).parseText(xml)
println findLinks(page).join('\n')
*/


///  UTILS
Set findLinks(def root) {
    int cnt = 0
    def posts = root?.depthFirst()?.find { it.@id.text() == "splashPosts"}
    Set links = posts?.depthFirst()?.findAll { it.name().toLowerCase() == "a" && !it.@href.text().contains('/tag/') }.collect([]) { cnt++; it.@href.text() - '?skyline=true&s=i'} as Set
    println "found $cnt"
    return links.sort()
}

http://groovyconsole.appspot.com/script/448003

BONUS: CSS Selectors with JSoup

@Grapes( @Grab(group='org.jsoup', module='jsoup', version='1.6.1' ))
def doc = org.jsoup.Jsoup.connect("http://www.bing.com/search?q=web+scraping").get()
println 'start'
doc.select("#results h3 a").each { node ->
    println '-->' + node.text() + ' == ' + node.attr('href') 
}
println 'done'

BONUS: XPath Selectors with TagSoup

@Grapes( @Grab('org.ccil.cowan.tagsoup:tagsoup:1.2') ) 
import org.ccil.cowan.tagsoup.Parser;
import org.xml.sax.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.*;
import javax.xml.xpath.*

def urlString = "http://www.bing.com/search?q=web+scraping"
URL url = new URL(urlString);

XMLReader reader = new Parser();
//Transform SAX to DOM
reader.setFeature(Parser.namespacesFeature, false);
reader.setFeature(Parser.namespacePrefixesFeature, false);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, new InputSource(url.openStream())), result);

def xpath = XPathFactory.newInstance().newXPath()

//CSS selector: $('#results h3 a')
def results = xpath.evaluate( '//*[@id=\'results\']//h3/a', result.getNode(), XPathConstants.NODESET )

results.each { println it }
println 'done'

Roulette

//roulette gamble
result = 0

netGain = 0
POT = 50000
BET_MULTIPLY = 2.5

YEARS = 5
DAYS = 364
ROUNDS = 500

YEARS.times { it ->

DAYS.times {

money = POT
bet = 1

ROUNDS.times {
    int result = Math.round(Math.random() + 1)
    if (result == 1) { //win
        money += bet
        bet = 1
    } else if (result == 2) { //lose
        money -= bet
        bet = ((money >= bet * BET_MULTIPLY) ? bet * BET_MULTIPLY : 0)
    }
}

gain = Math.round(money) - POT
netGain += gain

}

println "\n yr#${it+1} NET TOTAL:" + netGain
}

http://groovyconsole.appspot.com/script/449006

nodeGraph GUI

@Grapes(
    // http://prefuse.org
    //@Grab(group='org.prefuse', module='prefuse', version='beta-20060220')
    @Grab(group='org.prefuse', module='prefuse', version='beta-20071021')
)
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants
import groovy.util.BuilderSupport
import prefuse.Constants
import prefuse.Display
import prefuse.Visualization
import prefuse.action.ActionList
import prefuse.action.RepaintAction
import prefuse.action.assignment.ColorAction
import prefuse.action.assignment.DataColorAction
import prefuse.action.layout.graph.ForceDirectedLayout
import prefuse.activity.Activity
import prefuse.controls.DragControl
import prefuse.controls.PanControl
import prefuse.controls.ZoomControl
import prefuse.data.Graph
import prefuse.data.Node
import prefuse.render.DefaultRendererFactory
import prefuse.render.LabelRenderer
import prefuse.util.ColorLib
import prefuse.visual.VisualItem

class PrefuseBuilder extends BuilderSupport {
    
    def graph
    def visualization
    
    void setParent(Object parent, Object child) {
        if (parent instanceof Node && child instanceof Node) {
            graph.addEdge(parent, child)
        }
    }
        
    Object createNode(Object name) {
        return createNode(name, null, null)
    }
    
    Object createNode(Object name, Object value) {
        return createNode(name, null, value)
    }
    
    Object createNode(Object name, Map attributes) {
        return createNode(name, attributes, null)
    }
    
    Object createNode(Object name, Map attributes, Object value) {
        def node = null
        if (name == 'node') {
            node = graph.addNode()
            node.setString("name", value)
            visualization.run("color")
        }
        if (name == 'graph') {
            graph = new Graph()
            graph.addColumn("name", String.class)
            visualization = new Visualization()
            visualization.add("graph", graph)
            def labelRenderer = new LabelRenderer("name")
            labelRenderer.setRoundedCorner(8, 8)
            visualization.setRendererFactory(new DefaultRendererFactory(labelRenderer))
            def fill = new ColorAction("graph.nodes", VisualItem.FILLCOLOR, ColorLib.rgb(190,190,255))
            def text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0))
            def edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200))
            def color = new ActionList()
            color.add(fill)
            color.add(text)
            color.add(edges)
            def layout = new ActionList(Activity.INFINITY)
            layout.add(new ForceDirectedLayout("graph", true))
            layout.add(new RepaintAction())
            visualization.putAction("color", color)
            visualization.putAction("layout", layout)
            def display = new Display(visualization)
            display.setSize(720, 500)
            display.addControlListener(new DragControl())
            display.addControlListener(new PanControl())
            display.addControlListener(new ZoomControl())
            display.setHighQuality(true)
            visualization.run("color")
            visualization.run("layout")
            node = display
        }
        return node
    }
}

def go = {
   def graph = new PrefuseBuilder().graph {
       node("Grand Parent") {
           node("Parent") {
               node("Child 1")
               node("Child 2") {
                   node("Baby 1")
                   node("Baby 2")
               }
           }
       }
   }
   
   // create a swing app using the Groovy SwingBuilder to display the graph
   def sb = new groovy.swing.SwingBuilder()
   sb.frame(id:"nodeFrame", size:[300,300], visible:true, resizable:true, title:'PrefuseBuilder Test') {
       widget(graph)
   }
   
   sb.nodeFrame.pack()
}

go()

http://groovyconsole.appspot.com/script/453001

Map/Reduce Constructs

.collect() & .inject():

def map1 = { it -> it > 5 ? it * 2 : it * 10 }
def reduce1 = { coll, i -> if (i > 29) coll << i; coll }

println ([1,2,3,4,5,6,7,8,11,88].collect(map1).inject([], reduce1))

def map2 = { it -> it.value *= 2; it }
def reduce2 = { coll, me -> String key = me.key[0]; coll[key] = coll[key] ?: 0; coll[key] += me.value; coll }

println ([a1:1,b1:2,a2:3,b2:4].collect(map2).inject([:], reduce2))

http://groovyconsole.appspot.com/script/450002

groovyWS

@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2') // may take a while to download all dependencies!
import groovyx.net.ws.WSClient

proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize()

result = proxy.CelsiusToFahrenheit(0)
println "You are probably freezing at ${result} degrees Farhenheit"

http://groovyconsole.appspot.com/script/451004

Updated (just for fun...)

@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient

proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize()

(-15..40).step(5) { i ->
    result = proxy.CelsiusToFahrenheit(i)
    println "${i} Celcius == ${result} Farhenheit"
}