Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total

Putlines in Haskell

This is an illustrative example of

a) Point free style
b) How Haskell IO works.

If you don't understand Haskell IO, it might be helpful to try and unpick the definition here to see how it works. :-)

import System

main :: IO ()
main = getArgs >>= sequence_ . (map putStrLn) 

aio.py

// Andrew Input/Output

"""Andrew's Input/Output module"""

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="21 Dec 2005 - 22 Dec 2005"
__copyright__="Copyright 2005 Andrew Pennebaker"
__license__="GPL"
__version__="0.1"
__URL__="http://snippets.dzone.com/posts/show/3537"

def getByteArray(s):
	return [ord(e) for e in s]

def readAll(f):
	byteArray=[]
	line=f.readline()
	while line!="":
		for e in line:
			byteArray.append(ord(e))
		line=f.readline()

	return byteArray

def chomp(text):
	if text=="" or text=="\n":
		return ""
	elif text[-1]=="\n":
		return text[:-1]

	return text

Java: Reading String from a File

// Ref: http://www.exampledepot.com/egs/java.util.regex/Comment.html

    try {
        File f = new File("pattern.txt");
        FileReader rd = new FileReader(f);
        char[] buf = new char[(int)f.length()];
        rd.read(buf);
        patternStr = new String(buf);
    
        matcher = pattern.matcher(inputStr);
        matchFound = matcher.matches();
    } catch (IOException e) {
    }

Left to right affectation operator in Io

This simple line makes a simple left to right affectation operator in Io

-> := method( call sender setSlot(call argAt(0) name, self)) 
# Use :
2 -> a
3 -> b
a * b -> c
c println # => 6
# (thaks to jer) Note : This is quite broken
foo := Object clone
2 -> foo c 
foo c # raises an exception: "Number does not respond to c"
foo # => 2
# However, one can do :
foo do(2 -> c)

Irma the Chatterbot

This is a very simple chatterbot written in Io
To learn Irma how to answer something, do :
Irma register("something", "how to answer")
To get an answer :
Irma answer("Blaha blaha")
To save Irma to a file :
Irma saveToFile("filename")
To get Irma's vocabulary from a file
Irma withFile("filename")

Sequence words := method( Regex setIsUTF8(true) setString(self) setPattern("\\w+") allMatches map(asString) )
Object or := method(self)
Irma := Object clone do(
	vocabulary := Map clone
	vocabulary atPut("bonjour",list("Salut !"))
	vocabulary atPut("salut",list("Comment vas-tu ?","Bonjour"))

	register := method(rep1, rep2, 
		rep1 := rep1 asLowercase words join(" ")
		if(vocabulary at(rep1),
			vocabulary at(rep1) append(rep2),
			vocabulary atPut(rep1, list(rep2))
		)
	)
	
	answer := method(rep,
		exactAnswer(rep) or nearAnswer(rep)
	)
	exactAnswer := method(rep, 
		rep := rep asLowercase words
		vocabulary detect(k, k words == rep ) ?at(1) ?anyOne
	)

	randAnswer := method( vocabulary values flatten anyOne )

	nearAnswer := method( rep,vocabulary at(vocabulary keys max(words intersect(rep asLowercase words) join size)) anyOne)

	save := method(	vocabulary serialized	)
	
	with := method( dict, vocabulary = doString(dict) )

	saveToFile := method( file, f := File clone with(file or "irma_sav.io") openForUpdating ; f write(self save println) ; f close)

	withFile := method( file, self with(File clone with(file or "irma_sav.io") open readLines join("\n")))

	willFree := method( "Saving Irma" println ; saveToFile( "irma.emergency.io" ) )
)

Writing directly to a JTextArea

Writer implementation which provides a means for writing directly to a JTextArea.

import java.io.Writer;
import java.io.IOException;

import javax.swing.JTextArea;

/** A implementation of the java.io.Writer class which facilitates writing to a JTextArea via a stream.
    
    <p><b>Note:</b> There appears to be bug in the Macintosh implementation of 
    the JDK 1.1 where a PrintWriter writing to this class will not include the 
    correct line feeds for display in a JTextArea.  There is a simple test of
    the "java.version" system property which, if it starts with the String "1.1"
    will cause newlines to be written each time the buffer is flushed.</p>
    
    @author Anthony Eden
*/

public class JTextAreaWriter extends Writer{
    
    private boolean closed = false;
    private JTextArea textArea;
    private StringBuffer buffer;

    /** Constructor.
    
        @param textArea The JTextArea to write to.
    */

    public JTextAreaWriter(JTextArea textArea){
        setTextArea(textArea);
    }
    
    /** Set the JTextArea to write to.
    
        @param textArea The JTextArea
    */
    
    public void setTextArea(JTextArea textArea){
        if(textArea == null){
            throw new IllegalArgumentException("The text area must not be null.");
        }
        this.textArea = textArea;
    }
    
    /** Close the stream. */

    public void close(){
        closed = true;
    }
    
    /** Flush the data that is currently in the buffer.
    
        @throws IOException
    */
    
    public void flush() throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        // the newline character should not be necessary.  The PrintWriter
        // should autmatically put the newline, but it doesn't seem to work
        textArea.append(getBuffer().toString());
        if(System.getProperty("java.version").startsWith("1.1")){
            textArea.append("\n");
        }
        textArea.setCaretPosition(textArea.getDocument().getLength());
        buffer = null;
    }
    
    /** Write the given character array to the output stream.
    
        @param charArray The character array
        @throws IOException
    */
    
    public void write(char[] charArray) throws IOException{
        write(charArray, 0, charArray.length);
    }
    
    /** Write the given character array to the output stream beginning from
        the given offset and proceeding to until the given length is reached.
    
        @param charArray The character array
        @param offset The start offset
        @param length The length to write
        @throws IOException
    */
    
    public void write(char[] charArray, int offset, int length) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(charArray, offset, length);
    }
    
    /** Write the given character to the output stream.
    
        @param c The character
        @throws IOException
    */
    
    public void write(int c) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append((char)c);
    }
    
    /** Write the given String to the output stream.
    
        @param string The String
        @throws IOException
    */
    
    public void write(String string) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(string);
    }
    
    /** Write the given String to the output stream beginning from the given offset 
        and proceeding to until the given length is reached.
    
        @param string The String
        @param offset The start offset
        @param length The length to write
        @throws IOException
    */
    
    public void write(String string, int offset, int length) throws IOException{
        if(closed){
            throw new IOException("The stream is not open.");
        }
        getBuffer().append(string.substring(offset, length));
    }
    
    // protected methods
    
    /** Get the StringBuffer which holds the data prior to writing via
        a call to the <code>flush()
method. This method should
never return null.

@return A StringBuffer
*/

protected StringBuffer getBuffer(){
if(buffer == null){
buffer = new StringBuffer();
}
return buffer;
}

}

DebugInputStream

This class is useful for printing the data coming through an InputStream without copying that data into memory first.

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DebugInputStream extends FilterInputStream {

    private OutputStream debugOut;

    public DebugInputStream(InputStream in, OutputStream debugOut) {
        super(in);
        this.debugOut = debugOut;
    }

    public int read() throws IOException {
        int c = super.read();
        debugOut.write((char) c);
        return c;
    }

    public int read(byte[] b) throws IOException {
        int readCount = super.read(b);
        for (int i = 0; i < readCount; i++) {
            debugOut.write((char) b[i]);
        }
        return readCount;
    }

    public int read(byte[] b, int offset, int length) throws IOException {
        int readCount = super.read(b, offset, length);
        int readTo = offset + readCount;
        for (int i = offset; i < readTo; i++) {
            debugOut.write((char) b[i]);
        }
        return readCount;
    }

}
« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total