Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

A Java method that converts seconds to minutes and seconds

If you happen to need something like this, here’s some source code for a Java method that converts seconds in time to a String formatted as minutes and seconds:

private static String convertSecondsToMinutesAndSeconds(int secondsInput) {
    int minutes = secondsInput / 60;
    int seconds = secondsInput % 60;
    return String.format("%02d:%02d", minutes, seconds);
}

Feel free to use that code as a pointer in the right direction of a solution to this problem, but if you don’t already see the problem(s) here, it may help to know that this is actually a really crappy method.

Years ago I would have written that method like that and not given it a second thought, but as a programmer you (hopefully) continue to get wiser, and especially with a lot of exposure to functional programming lately, I now see that as a poor method. The question is, do you know why? If you don’t, I encourage you to think about all of the problems with this method/function. As a hint, there is more than one problem with it.

Android - “Freemarker NoClassDefFoundError TextBlock” error message

I don’t remember the exact error message, but if you’re trying to use FreeMarker with Android and you get an error that says something like “Freemarker - NoClassDefFoundError TextBlock”, the root cause of the problem seems to be that FreeMarker uses the java.beans library under the hood, and the Android version of Java does not implement this. As a result, FreeMarker won’t work with Android, at least not without some modifications, as of January, 2016.

I wish I could give you more details, but I’ve moved on from FreeMarker, and I’m looking at other templating libraries for my Android application.

Android - How to view LogCat output from the command line

From time to time I have a problem with Android Studio where it won’t show the logcat output of an app I’m trying to debug. I haven’t been able to figure out why that is, so what I do instead is look at my logcat output from my command line.

As a short tip, if you want to see Android LogCat output from your command line, just run this adb command from your Unix/Linux command line:

adb logcat

When you're developing an Android app, it's a good idea to keep this command open and running in a separate window, though of course you can also see this output in the Eclipse or Android Studio LogCat view.

Note that this command may not work if you have multiple devices connected, such as an Android emulator and a physical Android device connected on a USB port. But if you have one or the other it seems to work just fine.

RPI FAQ: How can I see what services are configured to run at startup on a Raspberry Pi? (Raspbian)

To see which services are configured to run at startup on a Rasperry Pi (Raspian) — and also see their current startup status — issue this Linux service command:

sudo service --status-all

The service man page describes what this command does:

service --status-all runs all init scripts, in alphabetical order, with the status command

On my Raspberry Pi (RPI) that command produces a long list of output that looks like this:

[ ? ]  alsa-utils
[ - ]  bootlogs
[ ? ]  bootmisc.sh
[ ? ]  cgroup-bin
[ ? ]  checkfs.sh
[ ? ]  checkroot-bootclean.sh
[ - ]  checkroot.sh
[ - ]  console-setup
[ + ]  cron
[ + ]  dbus
[ ? ]  dphys-swapfile
[ ? ]  fake-hwclock
[ - ]  hostname.sh
[ ? ]  hwclock.sh

The symbols between the brackets are read like this:

  • + means the service is running
  • - means the service is not running
  • ? means the service does not allow status as a command

In a related note, the runlevel command shows the current “run level” of your system:

$ runlevel
N 2

That output shows that the system is running at Run Level 2. The /etc/inittab file shows the meaning of the run levels:

# Runlevel 0 is halt.
# Runlevel 1 is single-user.
# Runlevels 2-5 are multi-user.
# Runlevel 6 is reboot.

In summary, if you wanted to see which of your RPI/Linux services are currently running (or not running) I hope this is helpful. Please see the page I linked to for more information.

How to size (or resize) application windows in AppleScript

AppleScript FAQ: How can I size or resize an application window using AppleScript?

To resize an application window with AppleScript, use a command like this:

tell application "Safari"
    set bounds of front window to {300, 30, 1200, 900}
end tell

That command tells the Safari browser to have the following size and location properties:

  • x = 300
  • y = 30
  • width = 1200
  • height = 900

When using this command, x and y correspond to the desired location of the application window, and those values represent where you want the upper-left corner of the window to be located.

I just used that code in a little script, and I can confirm that it works properly.

How to run a multiline AppleScript script from a Unix shell script (osascript)

This little example shows the syntax of how to run some AppleScript/osascript from a Unix shell script on a Mac OS X system:

#!/bin/sh

osascript <<EOF
tell application "Safari"
  close window 1
end tell
EOF

Just put your AppleScript in between the EOF parts, save it to a file, make the file executable, and this gives you a nice way to run a multiline AppleScript script from a shell script.

Here’s another example of what this looks like:

#!/bin/sh

osascript <<EOF
tell application "Safari" to activate
tell application "Safari"
    set bounds of front window to {300, 30, 1600, 1100}
end tell
EOF

How to close a Mac OS X app from a shell script (or command line)

If you ever need to close a Mac OS X application (gracefully) from the Mac Terminal command line or from a shell script, I can confirm that this command works:

osascript -e 'quit app "Safari"'

I use that command from a Mac/Unix shell script to close the Safari browser in an automation script I’m writing, and it works fine. Just replace Safari in that command with the name of the application you want to close.

A Scala shell script to move your mouse cursor

I’m currently trying to automate a GUI task, and as a part of that, one thing I need to do is move the mouse cursor.

In short, the solution I came up with was to write a Scala shell script that uses the Java Robot class to move the mouse. Here’s the source code for my script, which I named MoveMouse.sh:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

import java.awt.Robot

if (args.length != 2) {
    Console.err.println("Usage: MoveMouse x y")
    System.exit(1)
}

val x = args(0).toInt
val y = args(1).toInt

val robot = new Robot
robot.mouseMove(x, y)

You run the script like this:

$ MoveMouse.sh 5 10

That moves your mouse cursor to a position where the x-coordinate is 5 and the y-coordinate is 10. This is in the upper-left corner of your display. (I could be nicer and move the mouse with a little animation, but I won’t be watching the screen as the automation task runs, so with this script the mouse just jumps to the location you specify.)

I almost always work on Mac OS X systems, but I couldn’t find a way to do this with AppleScript, so I wrote this little shell script to solve the problem.

A custom JavaFX web browser (to show stock quotes)

I’m currently doing something completely different, and writing a little custom web browser using JavaFX and its WebView component. I’m using it so I can easily look at stock quotes and charts. I just started on it, and the current UI looks like this:

A custom JavaFX WebView web browser

All I have to do is click on one of the stock symbols on the left, and it loads the proper URL into the WebView on the right.

The current Java/JavaFX code is crap, but I’m sharing it here anyway:

package test1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Rectangle2D;

public class StockBrowser1 extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {
        
        String usersHomeDir = System.getProperty("user.home");
        String canonDataFile = usersHomeDir + "/" + "StockBrowser.data";
        String[] stockSymbols = readFileToStringArray(canonDataFile);
        
        Group root = new Group();
        Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
        double initialWidth = primaryScreenBounds.getWidth()*2/3;
        double initialHeight = primaryScreenBounds.getHeight()*2/3;
        Scene scene = new Scene(root, initialWidth, initialHeight);
        
        // LIST VIEW (URLS)
        ListView<String> listView = new ListView<String>();
        ObservableList<String> data = FXCollections.observableArrayList (stockSymbols);
        listView.setItems(data);
        listView.setPrefWidth(150);
        
        // BROWSER
        final WebView webView = new WebView();
        final WebEngine webEngine = webView.getEngine();

        listView.getSelectionModel().selectedItemProperty().addListener(
            new ChangeListener<String>() {
                public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) {
                    String url = getUrlFromStockSymbol(newValue);
                    webEngine.load(url);
            }
        });
        
        // THESE METHODS DO GET CALLED (THIS RESIZE APPROACH WORKS)
        // https://blog.idrsolutions.com/2012/11/adding-a-window-resize-listener-to...
        scene.widthProperty().addListener(new ChangeListener<Number>() {
            @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) {
                webView.setPrefWidth(newSceneWidth.doubleValue()*0.9);
            }
        });
        scene.heightProperty().addListener(new ChangeListener<Number>() {
            @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {
                webView.setPrefHeight(newSceneHeight.doubleValue()*0.98);
            }
        });
        
        // BORDER PANE
        BorderPane borderPane = new BorderPane();
        borderPane.setLeft(listView);
        borderPane.setCenter(webView);
        root.getChildren().add(borderPane);
        
        primaryStage.setTitle("Stocks Browser");
        primaryStage.setScene(scene);
        primaryStage.show();
        
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private static String getUrlFromStockSymbol(String symbol) {
        // google finance (their urls depend on nasdaq, etc.)
        //return "https://www.google.com/finance?q=NASDAQ%3AAAPL";
//        String url1 = "http://finance.yahoo.com/echarts?s=";
//        String url2 = "+Interactive#symbol=yhoo;range=1y;compare=;indicator=volume;charttype=area;crosshair=on;ohlcvalues=0;logscale=off;source=undefined;";
//        return url1 + symbol.toUpperCase() + url2;
        return "http://finance.yahoo.com/q?s=" + symbol.trim().toUpperCase();
    }

    private String[] readFileToStringArray(String canonFilename) throws IOException {
        FileReader fileReader = new FileReader(canonFilename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
    
}

I’ll write more about this some time in the future, but for today I just wanted to post this.

One of the good things about the code is that it handles the resizing of the WebView component. I just started with JavaFX and I don’t know why the WebView doesn’t resize itself by default, but that’s something I’ll have to learn over time.

Note 1: This SO article might show the best way(s) to resize a WebView.

Note 2: Having done all of this work, one of the big things I wanted to see is the interactive charts on Yahoo Finance. Unfortunately those don’t work with the JavaFX WebView, or at least they don’t work with them by default.

In the meantime, if you wanted to see how to use a JavaFX WebView, how to get it to resize, and how to use it in a BorderPane, I hope this (crappy) code is helpful.

Testing the Haskell do block with getContents and putStr

I was curious about how the “input redirection” program on page 170 of Learn You a Haskell for Great Good (LYAH) worked, so I typed it into a file named do1.hs, with one additional line:

import Data.Char

main = do
    contents <- getContents
    putStrLn "dude"
    putStr $ map toUpper contents

The line I added is the putStrLn "dude" line.

I compiled it like this:

$ ghc do1.hs

Then I ran it like this:

$ ./do1 < do1.hs

Can you guess what the output was?

This space intentionally left blank so you can think about it ...

.

.

.

Here’s the output:

dude
IMPORT DATA.CHAR

MAIN = DO
    CONTENTS <- GETCONTENTS
    PUTSTRLN "DUDE"
    PUTSTR $ MAP TOUPPER CONTENTS

That’s pretty cool.

I ran this code because I wasn’t 100% sold on the description of the do block code on page 172, but the description is correct. The putStr and getContents functions have a lazy interaction that is, well, cool.

Follow-up: The same example in Scala

Hmph, I guess that code isn’t that exciting ... if I use the using construct that I described in the Scala Cookbook, that Haskell code is close to being the same as this:

using(Source.fromFile("/etc/passwd")) { source => {
    lazy val lines = source.getLines
    println("dude")
    lines.map(_.toUpperCase).foreach(println)
}}

In this code getLines returns an iterator. I’m actually interested in the Haskell hGetContents function, which LYAH says returns a Handle. At the moment I don’t know how that maps to Scala, as in I don’t know if a Haskell Handle is more similar to a Scala File or an Iterator.

Note that I put the lazy in there because I think that’s closer to what Haskell does. Also note that in Scala that last line can be written a little more directly like this:

    lines.foreach(s => println(s.toUpperCase))

I think I was just confused with the Haskell code by the do block. For some reason I always want it to be a loop, which it is not.

(The using block isn’t necessary for this example, but it does automatically close the file, which is nice.)