Source code snippets (examples)

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

How to configure the GHCI prompt with a configuration file (Haskell)

To configure your GHCI prompt, create a Haskell/GHCI configuration file named .ghci, which should be in your home directory. Assuming that you are first creating it, put content like this in it:

:set prompt "ghci> "
:set +t

The first command shown sets the GHCI prompt, and the second command tells GHCI to show the type of each expression you type.

As an example of the file location, my home directory is /Users/Al, so I created my file as /Users/Al/.ghci.

If you wanted to see how to set your Haskell GHCI prompt permanently, or otherwise wanted to see how to create a GHCI configuration file, I hope this is helpful.

 

How to determine the type of an object in a Haskell program

There may be other ways to do this, but if you need to determine the type (type signature) of an object in a Haskell program, the following approach worked for me.

First, add this import statement to your program:

import Data.Typeable

What that does is give you access to a function named typeOf, which you can then use like this:

putStrLn ("type of action1 is: " ++ (show (typeOf action1)))
putStrLn ("type of action2 is: " ++ (show (typeOf action2)))

For the purpose of this solution it doesn’t matter what action1 and action2 are; I just use typeOf to determine their type, then use show to convert the output of typeOf to a String so I can print it. (Note to my future self: code that prints output like this must be in a do block.)

Now, when I run my Haskell program I see these two lines of debug output.

Style note: I’m relatively new to Haskell, and I prefer the use of parentheses to using $.

If you need to figure out what the type of an object is in a Haskell program, I hope this is helpful.

Note that if you are in GHCI, you can just put :type before your expression to determine the expression’s type, or use :set +t to see the type of every expression in GHCI.

Safe String to Int conversion in Haskell (a string from the command line)

I was working on a Haskell factorial function (which turned out to be easy) and decided I wanted to write a program to prompt a user at the command line for an Int, and then do the factorial of that Int.

I quickly learned that this required a String to Int conversion, which I wanted to do safely (I didn’t want my program to blow up). Technically what I do is actually a String to Maybe Int conversion, as you can see in this code:

-- this example shows how to read an Int from the command line, safely.
-- semi-helpful info here: http://www.reddit.com/r/haskell/comments/1vras3/haskell_io_how_to_read_n...

main = do

    -- prompt the user and get their input
    putStrLn "Enter an Int: "
    line <- getLine

    -- convert `line` (whose type is `String`) to a value of type `Maybe Int`
    let maybeInt = readMaybe line :: Maybe Int

    case maybeInt of
         Just n  -> putStrLn (show (factorial n)) >> main   -- `>> main` repeats the loop (asking for user input)
         Nothing -> putStrLn "Please try again."  >> main


-- converts an input `String` (i think) into a `Maybe a`.
-- in this example i use it to get a "Maybe Int" from the user's input.
readMaybe :: Read a => String -> Maybe a
readMaybe s = case reads s of
                  [(val, "")] -> Just val
                  _           -> Nothing

-- factorial function
factorial :: Int -> Int
factorial n = if n < 2 then 1 else n * factorial (n-1)

I found the readMaybe method at the Reddit URL shown in the source code. That URL doesn’t show how to do the complete String to Int conversion, but this code does. It safely converts a String to an Int by creating the integer value as a Maybe Int, which is like an Option in Scala, and is a safe way to either (a) get an Int value, or get a Nothing if the String to Int cast/conversion fails.

The Haskell reads function is an important part of this solution. It doesn’t blow up if the input string is “foo” or some other non-integer value. Search the Reddit URL I’ve shown for more details on how it works.

As a summary, if you wanted to see how to safely convert a String that you receive as user input to an Int in Haskell, I hope this code is helpful.

Scala code to print the byte values of text files

This is some test code I wrote. It shows how to read a text file in Scala.

This first program shows how to read the entire file into memory and print out the “byte values” of each byte/character in the file:

import scala.io.Source
import scala.util.control.Breaks._

object FileAsBytes extends App {

    // get the (entire) file contents
    val filename = "Chapter5.md"
    val bufferedSource = Source.fromFile(filename)
    val text = bufferedSource.mkString
    bufferedSource.close

    breakable {
        for ((char, count) <- text.zipWithIndex) {
            println(s"$char => ${char.toByte}")
            if (count > 250) break
        }
    }

}

This second example shows the same thing, how to show the byte value of each byte in a file using Scala, but it uses an iterator, so it should be able to read/parse a file of any size:

import scala.io.Source
import scala.util.control.Breaks._

object Iterator extends App {

    val filename = "Chapter5.md"
    val bufferedSource = Source.fromFile(filename)

    breakable {
        var count = 0
        bufferedSource.foreach { char =>
            count += 1
            println(s"$char => ${char.toByte}")
            if (count > 250) break
        }
    }

    bufferedSource.close

}

I wrote the first program because I wanted a way to see the byte values in a good format, and other Unix/Linux commands like xxd and hexdump weren’t printing the output the way I wanted to see it.

(They probably would have worked out eventually, but I wanted to see the byte values in the format printed by this Scala code, and it was easier to write the Scala code than it was to try to figure out how to format the output of those commands.)

I wrote these little programs because I thought there may have been some unusual characters in files that I converted from PDF to text, but in the end there were not.

Mac OS X 'sed' commands I use to clean up MacDown HTML output

FWIW, this is the source code for a sed script I use on my Mac OS X system to convert HTML output generated by MacDown into a format I need. MacDown generates some extra “cruft” that I don’t need, so I use these sed commands to clean up that HTML output:

# clean h1 tags. also add newlines before each h1.
s?<h1 id="toc_.*">\(.*\)</h1>?\
\
\
<h1>\1</h1>?

# clean h2 tags
s?<h2 id="toc_.*">\(.*\)</h2>?<h2>\1</h2>?

# clean h3 tags
s?<h3 id="toc_.*">\(.*\)</h3>?<h3>\1</h3>?

# clean pre tags
s?<pre><code>?<pre>?

s?</code></pre>?</pre>?

# these next two lines are unique to modifying "scala>" content
# inside pre tags (something i do while converting the scala cookbook)
s?^scala&gt; \(.*\)$?scala\&gt; <strong>\1</strong>?

s?^<pre>scala&gt; \(.*\)$?<pre>scala\&gt; <strong>\1</strong>?

I won’t explain those sed commands, I just wanted to put it out here in case I needed it again. (Putting it here makes it easier to find it later.)

How to turn off (disable) java.util.logging

If you need to turn off (disable) java.util.logging logging, adding this line of code to your main method seems to work:

LogManager.getLogManager().reset();

The LogManager class is located at java.util.logging.LogManager. I just put this code in the main method of a new project, where my project uses a library named Easy Rules that writes output via the java.util.logging library. After I implemented this LogManager approach I found that there was another way to turn off logging, but until then I can confirm that this approach worked.

I’m sure that you can also disable logging with a configuration file, but for my purposes I didn’t want to have to deal with that, I wanted to be able to disable it within my application, and this approach worked.

How to delete a file from a Java Jar file (use zip)

Java Jar file FAQ: Is there an easy way to delete a file from a Jar file?

Yes. Because a Jar file is just a Zip file, you can use the zip command to remove a file from a Jar file, like this:

zip -d MyApp.jar fileToDelete.foo

Of course the file to delete can be any sort of file. I just went through this process where I had to delete a configuration file, and my command looked like this:

zip -d sarah.jar application2.conf

It’s a long story about why I had to do that, but in summary, if you need to delete a file in a Java Jar file, I can confirm that this works.

A Scala "open URL as InputStream" method (HttpURLConnection)

As a quick note, I just found this getUrlInputStream method in an old Scala project. It needs to be updated and cleaned-up, but if you are looking for some code to get you started with opening a URL as an InputStream in Scala, this may be helpful:

/**
 * See http://alvinalexander.com/blog/post/java/how-open-url-read-contents-http...
 *
 * Note that this can throw a java.net.UnknownHostException
 *
 */
def getUrlInputStream(url: String,
                     connectTimeout: Int = 5000,
                     readTimeout: Int = 5000,
                     requestMethod: String = "GET") = {
   val u = new URL(url)
   val conn = u.openConnection.asInstanceOf[HttpURLConnection]
   HttpURLConnection.setFollowRedirects(false)
   conn.setConnectTimeout(connectTimeout)
   conn.setReadTimeout(readTimeout)
   conn.setRequestMethod(requestMethod)
   conn.connect
   conn.getInputStream
}

Again, the code isn’t great, but it can serve as a starter if you need some code to read from a URL as an input stream in Scala.

Android: An example onCreateView method in a Fragment class

This Java code shows how to implement a couple of things in an onCreateView method inside a Fragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
    View rootView = inflater.inflate(R.layout.fragment_single_image, parent, false);
    ImageView imageView = (ImageView)rootView.findViewById(R.id.currentImage);
    imageView.setImageBitmap(currentImage);
    return rootView;
}

What I’m doing here is:

  1. Enabling the Android Back/Up button in the ActionBar
  2. Getting a reference to the “root view” in my layout file
  3. Getting a reference to an ImageView that I know is in that layout file
  4. Setting a bitmap image on that ImageView

If you wanted to see how to do any of these things in a fragment’s onCreateView method, I hope this source code is helpful.

Android: How to add a click listener to a Button (action listener)

As another quick Android example, this Java source code shows how to add a “click listener” (on click/tap event) to an Android Button:

public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.my_layout_id);

         final Button button = (Button) findViewById(R.id.my_cool_button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // your handler code here
             }
         });
     }

}

Important things to know are a) you need to add a listener to the Button, b) the listener you need is called an OnClickListener (not an ActionListener or ButtonClickListener, etc.), c) you add the listener with the setOnClickListener method, and d) that you need to implement the onClick method.

If you needed to see how to add a listener to an Android Button, I hope this example code is helpful.