//src: http://blog.bloidonia.com/post/18073244930/whats-new-in-groovy-1-8-6-the-collate-method
//v1.8.6+//
def list = 1..10
def listInFours = list.collate( 4 )
assert listInFours == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ] ]
def listInFours2 = list.collate( 4, false )
// Notice the [ 9, 10 ] remainder has been dropped
assert listInFours2 == [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]
def gridList = list.collate( 3 ).collate( 2 )
assert gridList == [ [ [1, 2, 3], [4, 5, 6] ],
[ [7, 8, 9], [10] ] ]
def mph = [ 10, 26, 30, 32, 27, 14, 19, 22, 40, 14 ]
def window = mph.collate( 3, 1, false )
assert window == [ [10, 26, 30],
[26, 30, 32],
[30, 32, 27],
[32, 27, 14],
[27, 14, 19],
[14, 19, 22],
[19, 22, 40],
[22, 40, 14] ]
def windowAvg = window*.sum()*.intdiv( 3 )
assert windowAvg == [22, 29, 29, 24, 20, 18, 27, 25]
def items = [ 'ham', 30, 'cheese', 20, 'steak', 95 ]
def itemMap = items.collate( 2 ).collectEntries()
assert itemMap == [ ham:30, cheese:20, steak:95 ]
def range = 1..20
def (odds,evens) = range.collate( 2 ).transpose()
assert odds == (1..19).step( 2 ) // odd numbers 1 - 19
assert evens == (2..20).step( 2 ) // even numbers 2 - 20
Wednesday, February 29, 2012
collate
Monday, February 27, 2012
Regex look-ahead/behind syntax
//http://groovy.codehaus.org/Regular+Expressions
def r = /e+/
def str = 'me cheese please'
def m = str =~ r
assert m.size() == 5
println m*.toString() //[e, ee, e, e, e]
/////////////////////////////
def r = /(This boy) is/
def str = 'This boy is 10. This boy wants chocolate. This boy is tall.'
def m = str =~ r
assert m.size() == 2
assert m.collect { it[1] } == ['This boy','This boy']
/////////////////////////////
assert "abc".replaceAll(/(a)(b)(c)/, "\$1\$3") == 'ac' //back references
/////////////////////////////
//http://www.regular-expressions.info/captureall.html
r = /((?:abc|123)+).*?/
str = '123abc 123abc123'
m = str =~ r
assert m.size() == 2
println m*.toString()
print m[0][1..-1]
println m[1][1..-1]
/////////////////////////////
//password of 8 characters long and two non-letters
def r1 = /.*[^a-zA-Z].*[^a-zA-Z].*(?<=.{7})/ //look-behind ?<=
assert 'abc' !=~ r1
assert 'abcde12' !=~ r1
assert 'abcdef12' ==~ r1
assert 'abc1defgggg2' ==~ r1
assert 'abc1defgggg' !=~ r1
//word is foo$wrd*, store $wrd*
def wrd = 'bar'
def r2 = /foo((?=$wrd)[\w]+)/ //look-ahead ?=
def foo = "foo${wrd}hellow"
assert foo ==~ r2
def m = foo =~ r2
assert m[0][1] == "${wrd}hellow" // note: $wrd not consumed by check, is stored in result
foo = 'foohellow' // no $wrd
assert foo !=~ r2
//ADVANCED/////////////////////////////
def churnText(String text) {
def points = [[k: ~/(N|n)orth(E|e)ast(ern)?/ , v:'NE'],
[k: ~/(?>(N|n)orth(W|w)est(ern|:)?)(?! Territories)/ , v:'NW'],
[k: ~/(S|s)outheast(ern)?/ , v:'SE'],
[k: ~/(?>(S|s)outh(\s)?(W|w)est(ern)?)(?! Hill| Bend)/ , v:'SW'],
[k: ~/(?>(N|n)orth(ern)?|Upstate)(?! Carolina| Dakota| Platte| Neck| Mariana Islands| Bay|ridge)/ , v:'N' ],
[k: ~/(E|e)ast(ern)?/ , v:'E' ],
[k: ~/(?>(S|s)outh(ern|side)?)(?! Carolina| Dakota)/ , v:'S' ],
[k: ~/(?!(?<=George ))(?>(W|w)est(ern| of the)?)(?! Virginia| Palm Beach)/ , v:'W' ],
[k: ~/(?>(C|c)entral|Center|Middle|the middle section of the)(?!town| Peninsula| Tennessee|ia)/ , v:'C' ]]
points.each {p ->
def matcher = (text =~ p.k)
text = matcher.replaceAll(p.v)
println "p.v: ${p.v} text: $text"
}
}
churnText('Northwest Virginia')
println '='*40
churnText('NorthWestern Territories')
println '='*40
churnText('East George West')
return
Thursday, February 23, 2012
Swing Notification Popup
//see: http://groovy.codehaus.org/GUI+Programming+with+Groovy
import groovy.swing.*
import java.awt.*
import javax.swing.*
import javax.swing.border.*
import groovy.util.slurpersupport.NodeChild as Node
public class Notify {
def sb = new SwingBuilder()
public static void main(String[] args) {
// creates and displays itself
new Notify(args)
}
public Notify(String[] args){
// arg is path to xml message file,
// will be deleted after popup displayed
if (args.size() != 1) return
String appTitle = ".:. Notification .:."
String filePath = args[0]
Color backgroundColor = Color.yellow
Border emptyBorder = BorderFactory.createMatteBorder(5, 5, 5, 5, backgroundColor)
Toolkit tk = Toolkit.getDefaultToolkit()
Dimension screenSize = tk.getScreenSize()
final int WIDTH = screenSize.width
final int HEIGHT = screenSize.height
int w = WIDTH / 2
int h = HEIGHT / 2
int x = (WIDTH / 2) - (w / 2)
int y = (HEIGHT / 2) - (h / 2) - 50
Font fontSubject = new Font("Serif", Font.PLAIN, 24)
Font fontMessage = new Font("Serif", Font.PLAIN, 16)
//generate frame//
sb.dialog(id:"popupBox", title:appTitle, visible:true, alwaysOnTop:true, defaultCloseOperation:JFrame.DISPOSE_ON_CLOSE, resizable:false, location:[x, y], size:[w, h])
{
borderLayout()
label(id:"subject", constraints:BorderLayout.NORTH, horizontalAlignment:JTextField.CENTER, font:fontSubject, "SUBJ")
panel(constraints:BorderLayout.CENTER){
gridLayout(cols:1, rows:1, hgap:1, vgap:1)
scrollPane(border:emptyBorder) {
textArea(id:"message", editable:false, lineWrap:true, wrapStyleWord:true, font:fontMessage, "MESG")
}
}
}
def frame = sb.popupBox
//decorate frame color//
def cp = frame.contentPane
cp.background = backgroundColor
sb.message.background = cp.background
//populate frame data//
File xmlFile
Node root
try {
xmlFile = new File(filePath)
root = new XmlSlurper().parse(xmlFile)
//println root.getClass().name
}
catch (Exception) {
xmlFile = new File("")
root = new XmlSlurper().parseText('''
Error
Sorry, file path or XML syntax error.
''')
}
sb.subject.text = root.subject.text() // if not found, subject UI label is hidden
sb.message.text = root.message.text() ?
root.message.text().replaceAll('\\\\n', System.getProperty( "line.separator" )) :
'Sorry, empty notification.'
//display form//
frame.show()
try {
xmlFile.delete()
} catch (Exception ignore) {}
}
}
Thursday, February 16, 2012
Shell/Command line execution
//def cmd = "cmd /C dir"
def cmd = ["cmd","/C","dir g*.bat"] // more flexible format
//Groovyish Java//
Runtime r = Runtime.runtime
Process p = r.exec(cmd.toArray(new String()))
BufferedReader inp = new BufferedReader(new InputStreamReader(p.getInputStream()))
while (line = inp.readLine()) { println line }
//Groovy!//
println cmd.execute().text
Friday, February 10, 2012
Colt - Random Number Generators
/*
* see: http://acs.lbl.gov/software/colt/
*/
@Grapes(
@Grab(group='colt', module='colt', version='1.2.0')
)
import cern.jet.random.*
println Binomial.staticNextInt(500,0.5d)
println ChiSquare.staticNextDouble(10.0d)
println Exponential.staticNextDouble(1.0d)
println ExponentialPower.staticNextDouble(1.0d)
println Normal.staticNextDouble(10.0d,1.0d)
println Poisson.staticNextInt(100.0d)
println Uniform.staticNextDoubleFromTo(1.0d,100.0d)
println VonMises.staticNextDouble(10.0d)
Apache Commons Collections
@Grapes(
@Grab(group='commons-collections', module='commons-collections', version='3.2.1')
)
import org.apache.commons.collections.*
import org.apache.commons.collections.map.*
import org.apache.commons.collections.bidimap.*
IterableMap map1 = [a:1, b:2] as HashedMap
map1.each {
print it.key
println it.value
}
OrderedMap map = new LinkedMap()
map.with {
put("FIVE", "5")
put("SIX", "6")
put("SEVEN", "7")
assert firstKey() == "FIVE"
assert nextKey("FIVE") == "SIX"
assert nextKey("SIX") == "SEVEN"
}
BidiMap bidi = new TreeBidiMap()
bidi.with {
put("SIX", "6")
assert get("SIX") == "6"
assert get("SIX") == "6"
assert getKey("6") == "SIX"
removeValue("6")
assert getKey("SIX") == null
put("ONE", "1")
}
BidiMap inverse = bidi.inverseBidiMap() // returns a map with keys and values swapped
assert inverse.getKey("ONE") == "1"
Buffer buffer = new UnboundedFifoBuffer()
buffer.with {
add("ONE")
add("TWO")
add("THREE")
assert remove() == "ONE"
assert remove() == "TWO"
}
Bag bag = new HashBag()
bag.with {
add("ONE", 6) // add 6 copies of "ONE"
remove("ONE", 2) // removes 2 copies of "ONE"
assert getCount("ONE") == 4
}
Trove - high speed regular and primitive collections
/*
* see: http://trove.starlight-systems.com/
*/
@Grapes(
@Grab(group='net.sf.trove4j', module='trove4j', version='3.0.2')
)
import gnu.trove.set.*
import gnu.trove.set.hash.*
import gnu.trove.list.*
import gnu.trove.list.array.*
import gnu.trove.list.linked.*
import gnu.trove.map.*
import gnu.trove.map.hash.*
//Most Trove classes start with the letter "T" to indicate that they're part of the Trove library.
THashSet s = new THashSet()
100.times { i ->
s.add ((i / 2).toInteger())
}
assert s.size() == 50
assert s.contains(0)
TIntArrayList a = new TIntArrayList()
100.times { i ->
a.add ((i / 3).toInteger())
}
assert a.size() == 100
assert a.get(0) == 0
TIntLinkedList l = new TLinkedList()
100.times { i ->
l.add ((i / 4).toInteger())
}
assert l.size() == 100
assert l.get(0) == 0
THashMap m = new THashMap()
m['a'] = 1
m.b = 2
assert m.a == 1
Subscribe to:
Posts (Atom)