Rough Book

random musings of just another computer nerd

if-else in bAdkOde

I was talking to my CSE 200 (my first CS class at ASU) professor Richard Whitehouse about bAdkOde and he (rightly) pointed out that it didn’t have an explicit selection statement. He also said that unless I wanted it to be really ugly I’d need to have a selection statement. However, since I was going for ugly I figured that I’d just emulate the operation of an if and an if-else with the existing while statement.

If you know assembly, then you know that a while is simply a set of statements wrapped with a conditional branch at the top and a backwards branch at the bottom (or in other words, an if with a goto at the end. A do-while is simply a set of statements with a conditional branch (at the bottom) that branches to the top of the loop. In fact, in assembly programming there really aren’t any for loops or while loops. These keywords are simply abstractions and syntactic sugar. In bAdkOde, you can implement an if with the existing while statement if you explicitly make it break out of the loop. For example, let’s say that we want to check whether the user entered the character “0″:

?a
-48a
# print a line break
"10
# if a is zero
{=a
 # print the string "zero"
 "122"101"114"111"10
 # set the a register to a non-zero value so that we can break out of the loop
 >1a
}

I knew there was a way to implement an if-else with just while statements but I didn’t remember exactly how. Then my friend and co-worker Juan reminded me that I needed two variables. In our case, we need to use two registers:

?a
-48a
# copy the value of a into b
>ab
"10
# if a is zero
{=a
 # print the string "zero"
 "122"101"114"111"10
 # set the a register to a non-zero value so that we can break out of the loop
 >1a
}
# if the top loop failed, it means that b (which holds the same value as a) is
# non-zero and so we can enter this block.
# if the top loop was successful, it means that b (which holds the same value
# as a) is zero and so we won't enter this block. Hence, the second block acts
# as an 'else'
{!b
 # print the string "non-zero"
 "110"111"110"45"122"101"114"111"10
 # zero out the b register
 >0b
}

Yes, quite ugly. But that’s what I’m going for! :)

Popularity: unranked [?]

December 16, 2009 Posted by | Programming and Development, Projects | , , , , , , , , , , , , | Leave a Comment

bAdkOde: An Esoteric Language

I’ve added another project to the projects page. It’s called bAdkOde, an interpreter for an esoteric language that I designed. The very first incarnation of bAdkOde was written in Java and I actually posted it (or made a blog entry about it) over 8 years ago. For some reason I took it down. Probably because I stopped working on it. Anyway, I redesigned the language and wrote an interpreter for it in Perl about 4 or 5 years ago. I finally got around to posting it. Check out the project page for more details. Let me know what you think.

Popularity: unranked [?]

December 13, 2009 Posted by | Java, Perl, Programming and Development, Projects | , , , , , , , , , , | Leave a Comment

JSTL, instanceof, and hasProperty

I’ve been doing a little bit of JSTL over the past week, especially custom tags. I’ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard tag library. The standard tag library is still pretty useful when it comes to building custom tags. Since it’s not straight Java, it forces you think really hard about your logic. You don’t want to put any business or application logic in your tag, and you want to restrict everything to view or presentation logic. A side effect of it not being Java is that if you want to do anything extremely complicated, you’re probably better off writing the tag in Java (making sure that you don’t let any business logic creep in).

While writing my own custom tag, I noticed that although instanceof is a reserved word in the JSTL EL (expression language), it is not supported as an operator. The reason I wanted to use the instanceof operator is that I have an attribute that could either be a List or a Map and depending on the type, I wanted to do different things.

Another thing I was trying to do, was to inspect the incoming object to see if it had a certain property (reflection). JSTL uses reflection so that you can access the properties of an object via dot notation, if they follow the JavaBean naming-convention. However, there was no way for me to see if an object had a certain property. To solve both these problems, I wrote my own JSTL functions.
Read more »

Popularity: 9% [?]

December 4, 2009 Posted by | Java, Programming and Development, Web | , , , , , , , , , | 6 Comments

Performance testing using The Grinder

About a month ago at work, I was trying out a bunch of different performance-testing tools to figure out which one to use to performance-test our software. I ended up discovering a tool called The Grinder which uses Jython to build performance-testing scripts that you can then use to test your application. I even built a little framework in Jython to make the test scripts more modular and reusable. Over the next few days I’ll be publishing three articles (this one included) that talk about Grinder.

Introduction

In this article I’ll go over installing and setting up Grinder. I am not going to go into too many details since my aim is to provide information that will enable you to have Grinder up and running quickly. If you want more information, you can look at the rather thorough Grinder User Guide. At the end of this guide, you’ll know how to install and set up grinder, record a test, modify (and/or parameterize) it, start running it through the console, and record data from the test. Note: The instructions in this guide relate to a Linux environment. You can run Grinder in Windows; the set-up is not much different. The only differences will be in installation locations and shell scripts. If you want more information about setting up Grinder in a Windows environment, please take a look here.
Read more »

Popularity: 32% [?]

July 27, 2009 Posted by | Java, Jython, Programming and Development, Python | , , , , , , , , | 22 Comments

Running the JavaFX 1.1 SDK on Linux

This is an update to my instructions on running the JavaFX 1.0 SDK on Linux. Those instructions do not work on the dmg image for the 1.1 version of the SDK.

Mike (thanks Mike!) posted a comment on that blog mentioning a small change that needed to be made. To get JavaFX 1.1 on Linux, first follow the steps in the original guide. When you need to mount the dmg, you need to provide an offset. So instead of the original command, do the following:

vivin@dauntless ~
$; sudo mount -o loop,offset=$((1024*17)) -t hfsplus javafx_sdk-1_0-macosx-universal.dmg.out javafx

The dmg should be mounted now.

Popularity: 1% [?]

April 30, 2009 Posted by | Java, Linux, Programming and Development | , , , , , , , , , , , , | Leave a Comment

Creating a custom SELECT tag with OPTGROUP in Grails

I’ve recently started working with Groovy on Grails at work. Groovy is a dynamic language that runs on the JVM (Java Virtual Machine), and Grails is a high-productivity open-source web-application framework that leverages the Groovy language. Grails follows the “convention over configuration” principle, taking away a lot of the grunt work that goes into creating web applications. It also uses proven technology like Hibernate and Spring with a consistent interface. You can have a Grails app up and ready to go with only a few lines of code. This high productivity is also due to the fact that Grails uses Groovy, which is a dynamic language and is much more expressive than Java. Finally, because Groovy runs on the JVM, it has full access to Java’s rich API.

Groovy comes with a number of built-in tags which allow you to quickly create forms, form controls, or any number of other HTML constructs or elements. However, I noticed that Groovy didn’t provide a built-in tag to build a SELECT that includes OPTGROUPs. OPTGROUPs allow you to group options within a drop-down select-box. But this problem can be solved because Groovy supports the creation of custom tags. After reading a bunch of documentation and looking at a few examples, I was able to create my own SELECT tag that supports OPTGROUPs. Here is an example of the usage of the tag:

<g:selectWithOptGroup name = "song.id"
                      from = "${Song.list()}"
                      optionKey = "id"
                      optionValue = "songName"
                      groupBy = "album" />

And the code to implement this tag:

import org.springframework.beans.SimpleTypeConverter
import org.springframework.web.servlet.support.RequestContextUtils as RCU
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler

class MyAppTagLib {

    def selectWithOptGroup = {attrs ->
        def messageSource = grailsAttributes.getApplicationContext().getBean("messageSource")
        def locale = RCU.getLocale(request)
        def writer = out
        def from = attrs.remove('from')
        def keys = attrs.remove('keys')
        def optionKey = attrs.remove('optionKey')
        def optionValue = attrs.remove('optionValue')
        def groupBy = attrs.remove('groupBy')
        def value = attrs.remove('value')
        def valueMessagePrefix = attrs.remove('valueMessagePrefix')
        def noSelection = attrs.remove('noSelection')
        def disabled = attrs.remove('disabled')
        Set optGroupSet = new TreeSet();
        attrs.id = attrs.id ? attrs.id : attrs.name

        if (value instanceof Collection && attrs.multiple == null) {
            attrs.multiple = 'multiple'
        }

        if (noSelection != null) {
            noSelection = noSelection.entrySet().iterator().next()
        }

        if (disabled && Boolean.valueOf(disabled)) {
            attrs.disabled = 'disabled'
        }

        // figure out the groups
        from.each {
            optGroupSet.add(it.properties[groupBy])
        }

        writer << "<select name=\"${attrs.remove('name')}\" "
        // process remaining attributes
        outputAttributes(attrs)
        writer << '>'
        writer.println()

        if (noSelection) {
            renderNoSelectionOption(noSelection.key, noSelection.value, value)
            writer.println()
        }

        // create options from list
        if (from) {
            //iterate through group set
            for(optGroup in optGroupSet) {
                writer << " <optgroup label=\"${optGroup.encodeAsHTML()}\">"
                writer.println()

                from.eachWithIndex {el, i ->
                    if(el.properties[groupBy].equals(optGroup)) {

                        def keyValue = null
                        writer << '<option '

                        if (keys) {
                            keyValue = keys[i]
                            writeValueAndCheckIfSelected(keyValue, value, writer)
                        }

                        else if (optionKey) {
                            if (optionKey instanceof Closure) {
                                keyValue = optionKey(el)
                            }

                            else if (el != null && optionKey == 'id' && grailsApplication.getArtefact(DomainClassArtefactHandler.TYPE, el.getClass().name)) {
                                keyValue = el.ident()
                            }

                            else {
                                keyValue = el[optionKey]
                            }

                            writeValueAndCheckIfSelected(keyValue, value, writer)
                        }

                        else {
                            keyValue = el
                            writeValueAndCheckIfSelected(keyValue, value, writer)
                        }

                        writer << '>'

                        if (optionValue) {
                            if (optionValue instanceof Closure) {
                                writer << optionValue(el).toString().encodeAsHTML()
                            }

                            else {
                                writer << el[optionValue].toString().encodeAsHTML()
                            }

                        }

                        else if (valueMessagePrefix) {
                            def message = messageSource.getMessage("${valueMessagePrefix}.${keyValue}", null, null, locale)

                            if (message != null) {
                                writer << message.encodeAsHTML()
                            }

                            else if (keyValue) {
                                writer << keyValue.encodeAsHTML()
                            }

                            else {
                                def s = el.toString()
                                if (s) writer << s.encodeAsHTML()
                            }
                        }

                        else {
                            def s = el.toString()
                            if (s) writer << s.encodeAsHTML()
                        }

                        writer << '</option>'
                        writer.println()
                    }
                }

                writer << '</optgroup>'
                writer.println()
            }
        }
        // close tag
        writer << '</select>'
    }

    void outputAttributes(attrs) {
        attrs.remove('tagName') // Just in case one is left
        attrs.each {k, v ->
            out << k << "=\"" << v.encodeAsHTML() << "\" "
        }
    }

    def typeConverter = new SimpleTypeConverter()
    private writeValueAndCheckIfSelected(keyValue, value, writer) {
        boolean selected = false
        def keyClass = keyValue?.getClass()
        if (keyClass.isInstance(value)) {
            selected = (keyValue == value)
        }
        else if (value instanceof Collection) {
            selected = value.contains(keyValue)
        }
        else if (keyClass && value) {
            try {
                value = typeConverter.convertIfNecessary(value, keyClass)
                selected = (keyValue == value)
            } catch (Exception) {
                // ignore
            }
        }
        writer << "value=\"${keyValue}\" "
        if (selected) {
            writer << 'selected="selected" '
        }
    }

    def renderNoSelectionOption = {noSelectionKey, noSelectionValue, value ->
        // If a label for the '--Please choose--' first item is supplied, write it out
        out << '<option value="' << (noSelectionKey == null ? "" : noSelectionKey) << '"'
        if (noSelectionKey.equals(value)) {
            out << ' selected="selected" '
        }
        out << '>' << noSelectionValue.encodeAsHTML() << '</option>'
    }

    private String optionValueToString(def el, def optionValue) {
        if (optionValue instanceof Closure) {
            return optionValue(el).toString().encodeAsHTML()
        }

        el[optionValue].toString().encodeAsHTML()
    }
}

This is my very first attempt and so I’m sure some not-so-best practices abound. Feedback and comments are welcome.

Update

  • Previously, the tag wouldn’t pass through extra attributes that were defined. This has been fixed.
  • My previous version didn’t take into account a bunch of stuff that Grails’ actual SELECT tag does. I was able to find the Grails implementation here. I modified it to take into account OPTGROUPs.

Popularity: 5% [?]

February 11, 2009 Posted by | Groovy on Grails, Programming and Development | , , , , , , | 3 Comments

Running the JavaFX 1.0 SDK on Linux

The JavaFX 1.0 SDK was released today. I’ve played with the preview SDK, so I was pretty excited to try out the 1.0 SDK. Inexplicably, and this was the case with the preview SDK as well, Sun hasn’t released a version of the SDK for Linux. However, this wasn’t a problem because it was possible to run the Mac version of the Preview SDK on Linux. The preview SDK came in the form of a zip, but the 1.0 SDK comes in the form of a dmg, so I was initially stumped. But I’ve figured out how to get the Mac version of the SDK to work on Linux. It’s a little more complicated than getting the preview SDK to work, but it works!

The thing about dmg files is that you can easily mount them on Linux since they are essentially stored in the HFS Plus filesystem format. So I immediately set about trying to mount it:

vivin@dauntless ~
$ mkdir javafx

vivin@dauntless ~
$ sudo mount -o loop -t hfsplus javafx_sdk-1_0-macosx-universal.dmg javafx
[sudo] password for vivin:
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

Hmm… ok, that wasn’t what I expected, so I tried to see what type of file it was:

vivin@dauntless ~
$; file javafx_sdk-1_0-macosx-universal.dmg
javafx_sdk-1_0-macosx-universal.dmg: bzip2 compressed data, block size = 100k

Ok, so it look’s like it’s a bzipped file. All we need to do then, is bunzip it and mount it:

vivin@dauntless ~
$ bunzip2 javafx_sdk-1_0-macosx-universal.dmg
bunzip2: Can't guess original name for javafx_sdk-1_0-macosx-universal.dmg -- using javafx_sdk-1_0-macosx-universal.dmg.out

bunzip2: javafx_sdk-1_0-macosx-universal.dmg: trailing garbage after EOF ignored

vivin@dauntless ~
$ sudo mount -o loop -t hfsplus javafx_sdk-1_0-macosx-universal.dmg.out javafx

vivin@dauntless ~
$ ls javafx
javafx_sdk-1_0.mpkg

Awesome! So we were able to get the dmg mounted. Now all we need to do is find were the SDK lives. After going through the dmg, I found out that the SDK is stored in a compressed (gzipped) file. You can find it at <mountpoint>/javafx_sdk-1_0.mpkg/Contents/Packages/javafxsdk.pkg/Contents/Archive.pax.gz. Copy this file into another working directory (or wherever you want your SDK to reside. I put mine in /usr/local):

vivin@dauntless ~/working
$ cp ~/javafx/javafx_sdk-1_0.mpkg/Contents/Packages/javafxsdk.pkg/Contents/Archive.pax.gz .

vivin@dauntless ~/working
$ gunzip Archive.pax.gz

vivin@dauntless ~/working
$ file Archive.pax
Archive.pax: ASCII cpio archive (pre-SVR4 or odc)

When I gunzipped the file, I got Archive.pax, and I wasn’t sure what to do with it. So I ran file on it and discovered that it was a cpio file. Some quick Googling and man-page perusal later:

vivin@dauntless ~/working
$ cpio -i <Archive.pax
65687 blocks

vivin@dauntless ~/working
$ ls
Archive.pax  COPYRIGHT.html  lib          profiles     samples     src.zip                      timestamp
bin          docs            LICENSE.txt  README.html  servicetag  THIRDPARTYLICENSEREADME.txt

vivin@dauntless ~/working
$ bin/javafx

Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -d32          use a 32-bit data model if available

    -d64          use a 64-bit data model if available
    -client	  to select the "client" VM
    -server	  to select the "server" VM
    -hotspot	  is a synonym for the "client" VM  [deprecated]
                  The default VM is server,
                  because you are running on a server-class machine.

    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A : separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose[:class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -jre-no-restrict-search
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                    see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument

As you can see, you now have a working JavaFX 1.0 SDK on your Linux box!

Popularity: 1% [?]

December 4, 2008 Posted by | Java, Linux, Programming and Development | , , , , , , , , , , , , | 5 Comments

JavaFX: The New Hotness

I went to JavaOne a few months ago. It was a pretty neat experience and I learnt a lot of cool things. One of the things Sun was touting was the JavaFX family of technologies. It allows you to create RIA (Rich Internet Applications) using JavaFX Script, a domain-specific language built on top of Java. The demos were pretty impressive and it looks like Sun’s answer to Flash and Silverlight. I went to a few JavaFX sessions and I signed up for the preview SDK, which came out a few weeks ago. Since then, I’ve been playing around with the language to see what it can do. The language is pretty neat and being dynamic, has some pretty cool features like closures, list comprehension, lazy/incremental evaluation (through binding), and triggers. In addition, it uses a declarative model (although you can still use the traditional model) for describing a GUI. The API provides Swing components, but I believe the intent is to completely move away from that and use only JavaFX GUI components.

Calendar widget

Using a language that is only in preview is pretty interesting. The API is unfinished and the language isn’t completely mature, but this is to be expected. That being said, it still looks promising and seems to be a very capable and expressive language. Also, seeing as it is built on top of Java, you have access to all of Java’s rich API in addition to the numerous third-party Java libraries and API’s that are out there. I’ve been playing around with it for the last week or so and I was able to write a small calendar widget. It simply shows a month view for the current month, with the current date highlighted. I haven’t had much experience with writing GUIs in Java, so it took me a while to figure it all out. I shamelessly stole the colour gradient background from one of the demos in the preview SDK. The only issue I have right now is the load-time of the widget. It seems to take a while when you load it first. I don’t know if it has to do with the way I coded it or not. I’m pretty sure I’m not doing it the best way, but I expect to get better once I get more familiar with the language.

Here’s a screenshot of the widget running on Firefox 3 on my Ubuntu laptop (the theme is a Leopard theme):

Calendar widget

I have more details on the project page.

Popularity: 1% [?]

August 24, 2008 Posted by | Java, Programming and Development | , , , , , , , , , , , | 3 Comments

Some more stuff from

What’s going on? Sorry for this spree of Journal Entries. I haven’t used a computer in over 3 weeks and I was having withdrawal symptoms – and now that I have access to one (with the bare minimum of utilities) I’m a little hyper. By the way, here’s a link to the Java SSH Client that I mentioned. It’s pretty neat. I was able to fix my page from here.

How are things here… hmm… HARD. As luck would have it, I’m in a really hard company – G Company and they’re BIG on PT (Physical Training). To give you an example, last Wednesday we did a 4 mile company run in 100+F and 60% Humidity. Yeah, so I’m getting my ass kicked. But I haven’t fallen out of any runs yet. And I’m not going to either.

That’s pretty much it. Classes are boring ass hell – all about filling out forms. It’s easy but BORING. I keep nodding off. Must stop doing that! But other than that, its just all about getting used to the routine. I’m pretty sure I can do it. It’s definitely easier than Basic Training. You have a lot more freedom, but you have to be responsible too.

Well that’s pretty much it. I might be here next week. See y’all then!

Popularity: 1% [?]

June 23, 2002 Posted by | AIT, Army, Java, Military | , , , , , , , | Leave a Comment

Java SSH Client

Don’t worry about the journal entry. I fixed it! I’m just sooo good. Check out MindTerm :) . It’s a Java SSH Client Applet for IE. It’s real good! I used that to get to the database… cool huh??

See you all next week!

Popularity: 1% [?]

June 22, 2002 Posted by | AIT, Army, Java, Military | , , , , , , , | Leave a Comment

All original content on these pages is fingerprinted and certified by Digiprove