text:
package org.clinical3PO.common.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.validation.Valid;

import org.clinical3PO.common.environment.EnvironmentType;
import org.clinical3PO.common.form.ObservationSearchForm;
import org.clinical3PO.common.security.model.User;
import org.clinical3PO.model.JobSearchDetails;
import org.clinical3PO.model.JobSearchParameter;
import org.clinical3PO.services.JobSearchService;
import org.clinical3PO.services.common.utils.WebAppUtils;
import org.clinical3PO.services.constants.JobSearchConstants;
import org.clinical3PO.services.constants.SearchOn;
import org.clinical3PO.services.constants.SearchScript;
import org.clinical3PO.services.dao.model.JobSearch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/RObservationSearch")
public class RObservationSearch {

	@Autowired
	JobSearchService jobSearchService;

	private @Autowired ServletContext servletContext;

	private static final Logger logger = LoggerFactory.getLogger(RObservationSearch.class);

	private static final String stringSeparator = "|";

	@Autowired
	private EnvironmentType envType;

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String getObservation(
			@Valid @ModelAttribute("observationSearchForm") ObservationSearchForm observationForm,
			BindingResult result, Model model) {

		if (result.hasErrors()) {
			model.addAttribute("observationIds",WebAppUtils.getObservationIds());
			return "ObservationSearchView";
		}

		// Invoke service which inserts a record in the table, calls the hadoop
		// job
		assert (jobSearchService != null);

		JobSearch jobSearch = new JobSearch();

		List<JobSearchParameter> searchParameters = new ArrayList<JobSearchParameter>(1);
		JobSearchParameter jobSearchParameter = new JobSearchParameter(
				JobSearchConstants.PATIENTID.getSearchKey(),
				observationForm.getPatientId(), 1);

		searchParameters.add(jobSearchParameter);

		jobSearchParameter = new JobSearchParameter(
				JobSearchConstants.OBSERVATIONID.getSearchKey(),
				observationForm.getObservationId(), 1);
		searchParameters.add(jobSearchParameter);

		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		assert (user != null);

		jobSearch.setSearchBy(user.getId());
		jobSearch.setSearchParameters(searchParameters);

		JobSearchDetails jobSearchDetails = new JobSearchDetails();
		jobSearchDetails.setSearchOn(SearchOn.OBSERVATIONIDR.getSearchOn());
		jobSearchDetails.setSearchType("ObservationIdR");
		jobSearchDetails.setSearchParameters(jobSearch.getSearchParameters().get(1).getValue());
		jobSearchDetails.setScriptType(SearchScript.OBSERVATIONIDR.getSearchScript());
		jobSearchDetails.setScriptParameters(jobSearchService.getScriptParameters(jobSearch));

		jobSearchService.searchJob(jobSearch, jobSearchDetails);

		return "redirect:/MySearch/";
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String observationSearch(ModelMap model) {

		model.addAttribute("observationIds",WebAppUtils.getObservationIds());
		model.addAttribute("observationSearchForm", new ObservationSearchForm());

		return "ObservationSearchView";
	}
	@RequestMapping(value = "/FileUpload", method = RequestMethod.POST)
	public String getPatient(@RequestParam("batchFile") MultipartFile batchFile, Model model) {
		// Invoke service which inserts a record in the table, calls the hadoop
		// job
		assert (jobSearchService != null);
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		assert (user != null);

		if (batchFile.isEmpty()) {
			logger.error("Uploaded file is empty");
			return "redirect:/MySearch/";
		}

		BufferedOutputStream stream = null;
		BufferedReader reader = null;

		try {
			byte[] bytes = batchFile.getBytes();

			File dir = new File(jobSearchService.getAppDataDirectory()+File.separator+"batchUploads");

			JobSearch jobSearch = new JobSearch();
			jobSearch.setSearchBy(user.getId());

			if (!dir.exists())
				dir.mkdirs();

			// Create the file on server
			String name = "BatchFile"+ new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
			File savedBatchFile = new File(dir.getAbsolutePath() + File.separator + name);

			if (envType == EnvironmentType.DEVELOPMENT && logger.isDebugEnabled()){
				logger.debug("File uploaded path:"+savedBatchFile.getAbsolutePath());
			}

			try{
				stream = new BufferedOutputStream(new FileOutputStream(savedBatchFile));
				stream.write(bytes);
			} catch (Exception e) {
				logger.info("File upload directory not found");
			} finally{
				if (stream!=null) stream.close();
			}

			String regexSeparator = "(?<!\\\\)" + Pattern.quote(stringSeparator);

			List<JobSearchParameter> searchParameters = new ArrayList<JobSearchParameter>(1);
			try{
				reader = new BufferedReader(new FileReader(savedBatchFile));
				String patientInfo;
				int index = 1;

				while ((patientInfo = reader.readLine()) != null) {
					searchParameters.add(new JobSearchParameter(
							JobSearchConstants.PATIENTIDS.getSearchKey(),
							patientInfo.split(regexSeparator)[0], index));
					searchParameters.add(new JobSearchParameter(
							JobSearchConstants.OBSERVATIONIDS.getSearchKey(),
							patientInfo.split(regexSeparator)[1], index));
					searchParameters.add(new JobSearchParameter(
							JobSearchConstants.COLORCODE.getSearchKey(),
							patientInfo.split(regexSeparator)[2], index));
					index++;

					jobSearch.setSearchParameters(searchParameters);
				}
			} catch (Exception e) {
				logger.error("Unable to read uploaded file");
			} finally{
				if (reader!=null) reader.close();
			}

			JobSearchDetails jobSearchDetails = new JobSearchDetails();
			jobSearchDetails.setSearchOn(SearchOn.PATIENTIDUSERPREFSBATCHR.getSearchOn());
			jobSearchDetails.setSearchType("PatientIdFromFileR");
			jobSearchDetails.setScriptType(SearchScript.PATIENTIDUSERPREFSR.getSearchScript());
			jobSearchDetails.setScriptParameters(jobSearchService.getPatientSearchWithUserPrefsParameters(jobSearch));

			jobSearchService.searchJob(jobSearch, jobSearchDetails);

			File newServerFile = new File(dir.getAbsolutePath() + File.separator + "UploadedFile-" + jobSearch.getId() + ".txt");
			savedBatchFile.renameTo(newServerFile);

			if (envType == EnvironmentType.DEVELOPMENT && logger.isDebugEnabled()){
				logger.debug("File renaming path:"+newServerFile.getAbsolutePath());
			}

			return "redirect:/MySearch/";

		} catch (Exception e) {
			logger.error("You failed to upload " + " => " + e.getMessage());
			return "redirect:/MySearch/";
		}
	}

	@RequestMapping(value = "/FileUpload", method = RequestMethod.GET)
	public String patientSearchFromFile(ModelMap model) {
		// Allow the user to search for a patient
		return "PatientSearchBatch";
	}
}


text:
<?php
namespace tests\phpunit4567;

class InfoFieldsTest extends \tests\InfoFieldsTest
{
}

redpajama_set_name: RedPajamaGithub


text:
require "rails_helper"

describe ConArtist do
  describe "#configure" do
    context "default values" do
      before do
        ConArtist.configure do |config|
        end
      end

      it "has a default user class" do
        expect(ConArtist.configuration.user_class).to eql("User")
      end
    end
    context "setting values" do

      before do
        ConArtist.configure do |config|
          config.user_class = "Admin"
        end
      end

      it "sets the user class" do
        expect(ConArtist.configuration.user_class).to eql("Admin")
      end
    end
  end
end


text:
@interface ZKFieldLayoutComponent()
@property (strong,nonatomic) NSArray<ZKDescribeLayoutComponent *>  *components__v;
@property (strong,nonatomic) NSString                              *fieldType__v;
@end

@implementation ZKFieldLayoutComponent

+(void)load {
    [self registerType:self xmlName:@"FieldLayoutComponent"];
}

+(ZKComplexTypeInfo *)wsdlSchema {
   static ZKComplexTypeInfo *wsdlSchema;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       wsdlSchema = [[ZKComplexTypeInfo alloc] initWithType:@"FieldLayoutComponent" parent:[ZKDescribeLayoutComponent class]
                    fields:@[
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"components" propertyName:@"components" optional:YES nillable:NO],
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"fieldType" propertyName:@"fieldType" optional:NO nillable:NO],

                    ]];
   });
   return wsdlSchema;
}

-(NSArray<ZKDescribeLayoutComponent *> *)components {
    if ((fields__set2[0] & 0x1) == 0) {
        self.components__v = [self complexTypeArrayFromElements:@"components" cls:[ZKDescribeLayoutComponent class]];
        fields__set2[0] |= 0x1;
    }
    return self.components__v;
}

-(void)setComponents:(NSArray<ZKDescribeLayoutComponent *> *)v {
    self.components__v = v;
    fields__set2[0] |= 0x1;
}

-(NSString *)fieldType {
    if ((fields__set2[0] & 0x2) == 0) {
        self.fieldType__v = [self string:@"fieldType"];
        fields__set2[0] |= 0x2;
    }
    return self.fieldType__v;
}

-(void)setFieldType:(NSString *)v {
    self.fieldType__v = v;
    fields__set2[0] |= 0x2;
}

-(void)serializeTo:(ZKXmlWriter *)env elemName:(NSString *)elemName {
	[env startElement:elemName type:@"FieldLayoutComponent"];
	[env addIntElement:@"displayLines" elemValue:self.displayLines];
	[env addIntElement:@"tabOrder"     elemValue:self.tabOrder];
	[env addElement:@"type"            elemValue:self.type         nillable:NO  optional:NO];
	[env addElement:@"value"           elemValue:self.value        nillable:YES optional:NO];
	[env addElementArray:@"components" elemValue:self.components];
	[env addElement:@"fieldType"       elemValue:self.fieldType    nillable:NO  optional:NO];
	[env endElement:elemName];
}
@end


text:
/**
 * @fileoverview This module provides functions for reading and writing streams of raw bytes.
 * It implements the Stream and TextStream classes as per
 * the CommonJS IO/A proposal.
 *
 * Streams are closely related with two other modules. Low-level byte manipulation is provided
 * by the binary module
 * and uses the ByteArray or ByteString class. The
 * fs module returns io streams for reading and
 * writing files.
 */

var {Binary, ByteArray, ByteString} = require("binary");
var {Encoder, Decoder} = require("ringo/encoding");

defineClass(org.ringojs.wrappers.Stream);

/**
 * This class implements an I/O stream used to read and write raw bytes.
 * @constructor
 */
exports.Stream = Stream;

var {InputStreamReader, BufferedReader, OutputStreamWriter, BufferedWriter} = java.io;

/**
 * Reads all data available from this stream and writes the result to the
 * given output stream, flushing afterwards. Note that this function does
 * not close this stream or the output stream after copying.
 * @param {Stream} output The target Stream to be written to.
 */
Stream.prototype.copy = function(output) {
    var read, length = 8192;
    var buffer = new ByteArray(length);
    while ((read = this.readInto(buffer, 0, length)) > -1) {
        output.write(buffer, 0, read);
    }
    output.flush();
    return this;
};

/**
 * Read all data from this stream and invoke function `fn` for each chunk of data read.
 * The callback function is called with a ByteArray as single argument. Note that
 * the stream is not closed after reading.
 * @param {Function} fn the callback function
 * @param {Object} [thisObj] optional this-object to use for callback
 */
Stream.prototype.forEach = function(fn, thisObj) {
    var read, length = 8192;
    var buffer = new ByteArray(length);
    while ((read = this.readInto(buffer, 0, length)) > -1) {
        buffer.length = read;
        fn.call(thisObj, buffer);
        buffer.length = length;
    }
};

/**
 * A binary stream that reads from and/or writes to an in-memory byte array.
 *
 * If the constructor is called with a Number argument, a ByteArray with the
 * given length is allocated and the length of the stream is set to zero.
 *
 * If the argument is a [binary object](../binary) it will be used as underlying
 * buffer and the stream length set to the length of the binary object.
 * If argument is a [ByteArray](../binary#ByteArray), the resulting stream is both
 * readable, writable, and seekable. If it is a [ByteString](../binary#ByteString),
 * the resulting stream is readable and seekable but not writable.
 *
 * If called without argument, a ByteArray of length 1024 is allocated as buffer.
 *
 * @param {Binary|Number} binaryOrNumber the buffer to use, or the initial
 * capacity of the buffer to allocate.
 * @constructor
 */
exports.MemoryStream = function MemoryStream(binaryOrNumber) {

    var buffer, length;
    if (!binaryOrNumber) {
        buffer = new ByteArray(0);
        length = 0;
    } else if (binaryOrNumber instanceof Binary) {
        buffer = binaryOrNumber;
        length = buffer.length;
    } else if (typeof binaryOrNumber == "number") {
        buffer = new ByteArray(binaryOrNumber);
        length = 0;
    } else {
        throw new Error("Argument must be Binary, Number, or undefined");
    }

    var stream = Object.create(Stream.prototype);
    var position = 0;
    var closed = false;
    var canWrite = buffer instanceof ByteArray;

    function checkClosed() {
        if (closed) {
            throw new Error("Stream has been closed");
        }
    }

    /**
     * Returns true if the stream supports reading, false otherwise.
     * Always returns true for MemoryStreams.
     * @name MemoryStream.prototype.readable
     * @see #Stream.prototype.readable
     * @return {Boolean} true if stream is readable
     * @function
     */
    stream.readable = function() {
       return true;
    };

    /**
     * Returns true if the stream supports writing, false otherwise.
     * For MemoryStreams this returns true if the wrapped binary is an
     * instance of ByteArray.
     * @name MemoryStream.prototype.writable
     * @see #Stream.prototype.writable
     * @return {Boolean} true if stream is writable
     * @function
     */
    stream.writable = function() {
        return buffer instanceof ByteArray;
    };

    /**
     * Returns true if the stream is randomly accessible and supports the length
     * and position properties, false otherwise.
     * Always returns true for MemoryStreams.
     * @name MemoryStream.prototype.seekable
     * @see #Stream.prototype.seekable
     * @return {Boolean} true if stream is seekable
     * @function
     */
    stream.seekable = function() {
        return true;
    };

    /**
     * Read up to `maxBytes` bytes from the stream, or until the end of the stream
     * has been reached. If `maxBytes` is not specified, the full stream is read
     * until its end is reached. Reading from a stream where the end has already been
     * reached returns an empty ByteString.
     * @name MemoryStream.prototype.read
     * @param {Number} maxBytes the maximum number of bytes to read
     * @returns {ByteString}
     * @see #Stream.prototype.read
     * @function
     */
    stream.read = function(maxBytes) {
        checkClosed();
        var result;
        if (isFinite(maxBytes)) {
            if (maxBytes < 0) {
                throw new Error("read(): argument must not be negative");
            }
            var end = Math.min(position + maxBytes, length);
            result = ByteString.wrap(buffer.slice(position, end));
            position = end;
            return result;
        } else {
            result = ByteString.wrap(buffer.slice(position, length));
            position = length;
        }
        return result;
    };

    /**
     * Read bytes from this stream into the given buffer. This method does
     * *not* increase the length of the buffer.
     * @name MemoryStream.prototype.readInto
     * @param {ByteArray} buffer the buffer
     * @param {Number} begin optional begin index, defaults to 0.
     * @param {Number} end optional end index, defaults to buffer.length - 1.
     * @returns {Number} The number of bytes read or -1 if the end of the stream
     *          has been reached
     * @see #Stream.prototype.readInto
     * @function
     */
    stream.readInto = function(target, begin, end) {
        checkClosed();
        if (!(target instanceof ByteArray)) {
            throw new Error("readInto(): first argument must be ByteArray");
        }
        if (position >= length) {
            return -1;
        }
        begin = begin === undefined ? 0 : Math.max(0, begin);
        end = end === undefined ? target.length : Math.min(target.length, end);
        if (begin < 0 || end < 0) {
            throw new Error("readInto(): begin and end must not be negative");
        } else if (begin > end) {
            throw new Error("readInto(): end must be greater than begin");
        }
        var count = Math.min(length - position, end - begin);
        buffer.copy(position, position + count, target, begin);
        position += count;
        return count;
    };

    /**
     * Write bytes from b to this stream. If begin and end are specified,
     * only the range starting at begin and ending before end is written.
     * @name MemoryStream.prototype.write
     * @param {Binary} source The source to be written from
     * @param {Number} begin optional
     * @param {Number} end optional
     * @see #Stream.prototype.write
     * @function
     */
    stream.write = function(source, begin, end) {
        checkClosed();
        if (typeof source === "string") {
            require("system").stderr.print("Warning: binary write called with string argument. "
                    + "Using default encoding");
            source = source.toByteString();
        }
        if (!(source instanceof Binary)) {
            throw new Error("write(): first argument must be binary");
        }
        begin = begin === undefined ? 0 : Math.max(0, begin);
        end = end === undefined ? source.length : Math.min(source.length, end);
        if (begin > end) {
            throw new Error("write(): end must be greater than begin");
        }
        var count = end - begin;
        source.copy(begin, end, buffer, position);
        position += count;
        length = Math.max(length, position);
    };

    /**
     * The wrapped buffer.
     * @name MemoryStream.prototype.content
     */
    Object.defineProperty(stream, "content", {
        get: function() {
            return buffer;
        }
    });

    /**
     * The number of bytes in the stream's underlying buffer.
     * @name MemoryStream.prototype.length
     */
    Object.defineProperty(stream, "length", {
        get: function() {
            checkClosed();
            return length
        },
        set: function(value) {
            if (canWrite) {
                checkClosed();
                length = buffer.length = value;
                position = Math.min(position, length);
            }
        }
    });

    /**
     * The current position of this stream in the wrapped buffer.
     * @name MemoryStream.prototype.position
     */
    Object.defineProperty(stream, "position", {
        get: function() {
            checkClosed();
            return position;
        },
        set: function(value) {
            checkClosed();
            position = Math.min(Math.max(0, value), length);
        }
    });

    /**
     * Try to skip over num bytes in the stream. Returns the number of acutal bytes skipped
     * or throws an error if the operation could not be completed.
     * @name Stream.prototype.skip
     * @param {Number} num bytes to skip
     * @returns {Number} actual bytes skipped
     * @name MemoryStream.prototype.skip
     * @function
     */
    stream.skip = function(num) {
        checkClosed();
        num = Math.min(parseInt(num, 10), length - position);
        if (isNaN(num)) {
            throw new Error("skip() requires a number argument");
        } else if (num < 0) {
            throw new Error("Argument to skip() must not be negative");
        }
        position += num;
        return num
    };

    /**
     * Flushes the bytes written to the stream to the underlying medium.
     * @name MemoryStream.prototype.flush
     * @function
     */
    stream.flush = function() {
        checkClosed();
    };

    /**
     * Closes the stream, freeing the resources it is holding.
     * @name MemoryStream.prototype.close
     * @function
     */
    stream.close = function() {
        checkClosed();
        closed = true;
    };

    /**
     * Returns true if the stream is closed, false otherwise.
     * @name MemoryStream.prototype.closed
     * @return {Boolean} true if the stream has been closed
     * @function
     */
    stream.closed = function() {
        return closed;
    };

    return stream;
};

/**
 * A TextStream implements an I/O stream used to read and write strings. It
 * wraps a raw Stream and exposes a similar interface.
 * @param {Stream} io The raw Stream to be wrapped.
 * @param {Object} options the options object. Supports the following properties:
 *

charset: string containing the name of the encoding to use.
 *            Defaults to "utf8".

 *
newline: string containing the newline character sequence to use in
 *            writeLine() and writeLines(). Defaults to "\n".

 *
delimiter: string containing the delimiter to use in print().
 *            Defaults to " ".

 * @param {Number} buflen optional buffer size. Defaults to 8192.
 * @constructor
 */
exports.TextStream = function TextStream(io, options, buflen) {
    if (this.constructor !== exports.TextStream) {
        return new exports.TextStream(io, options, buflen);
    }

    options = options || {};
    var charset = options.charset || "utf8";
    var newline = options.hasOwnProperty("newline") ? options.newline : "\n";
    var delimiter = options.hasOwnProperty("delimiter") ? options.delimiter : " ";
    var reader, writer;
    var encoder, decoder;
    var DEFAULTSIZE = 8192;

    if (io.readable()) {
        decoder = new Decoder(charset, false, buflen || DEFAULTSIZE);
        decoder.readFrom(io);
    }

    if (io.writable()) {
        encoder = new Encoder(charset, false, buflen || DEFAULTSIZE);
        encoder.writeTo(io);
    }

    /**
     * @see #Stream.prototype.readable
     */
    this.readable = function() {
       return io.readable();
    };

    /**
     * @see #Stream.prototype.writable
     */
    this.writable = function() {
        return io.writable();
    };

    /**
     * Always returns false, as a TextStream is not randomly accessible.
     */
    this.seekable = function() {
        return false;
    };

    /**
     * Reads a line from this stream. If the end of the stream is reached
     * before any data is gathered, returns an empty string. Otherwise, returns
     * the line including only the newline character. Carriage return will be dropped.
     * @returns {String} the next line
     */
    this.readLine = function () {
        var line = decoder.readLine(true);
        if (line === null)
            return "";
        return String(line);
    };

    /**
     * Returns this stream.
     * @return {TextStream} this stream
     */
    this.iterator = function () {
        return this;
    };

    /**
     * Returns the next line of input without the newline. Throws
     * `StopIteration` if the end of the stream is reached.
     * @returns {String} the next line
     * @example var fs = require('fs');
     * var txtStream = fs.open('./browserStats.csv', 'r');
     * try {
     *   while (true) {
     *      console.log(txtStream.next());
     *   }
     * } catch (e) {
     *   console.log("EOF");
     * }
     */
    this.next = function () {
        var line = decoder.readLine(false);
        if (line == null) {
            throw StopIteration;
        }
        return String(line);
    };

    /**
     * Calls `callback` with each line in the input stream.
     * @param {Function} callback the callback function
     * @param {Object} [thisObj] optional this-object to use for callback
     * @example var txtStream = fs.open('./browserStats.csv', 'r');
     * txtStream.forEach(function(line) {
     *   console.log(line); // Print one single line
     * });
     */
    this.forEach = function (callback, thisObj) {
        var line = decoder.readLine(false);
        while (line != null) {
            callback.call(thisObj, line);
            line = decoder.readLine(false);
        }
    };

    /**
     * Returns an Array of Strings, accumulated by calling `readLine` until it
     * returns an empty string. The returned array does not include the final
     * empty string, but it does include a trailing newline at the end of every
     * line.
     * @returns {Array} an array of lines
     * @example >> var fs = require('fs');
     * >> var txtStream = fs.open('./sampleData.csv', 'r');
     * >> var lines = txtStream.readLines();
     * >> console.log(lines.length + ' lines');
     * 6628 lines
     */
    this.readLines = function () {
        var lines = [];
        do {
            var line = this.readLine();
            if (line.length)
                lines.push(line);
        } while (line.length);
        return lines;
    };

    /**
     * Read the full stream until the end is reached and return the data read
     * as string.
     * @returns {String}
     */
    this.read = function () {
        return decoder.read();
    };

    /**
     * Not implemented for `TextStream`. Calling this method will raise an error.
     */
    this.readInto = function () {
        throw new Error("Not implemented");
    };

    /**
     * Reads from this stream with [readLine](#readLine), writing the results
     * to the target stream and flushing, until the end of this stream is reached.
     * @param {Stream} output
     * @return {TextStream} this stream
     */
    this.copy = function (output) {
        while (true) {
            var line = this.readLine();
            if (!line.length)
                break;
            output.write(line).flush();
        }
        return this;
    };

    /**
     * Writes all arguments to the stream.
     * @return {TextStream} this stream
     * @example >> var fs = require('fs');
     * >> var txtOutStream = fs.open('./demo.txt', 'w');
     * >> txtOutStream.write('foo', 'bar', 'baz');
     *
     * // demo.txt content:
     * foobarbaz
     */
    this.write = function () {
        if (!io.writable()) {
            throw new Error("The TextStream is not writable!");
        }

        for (var i = 0; i < arguments.length; i++) {
            encoder.encode(String(arguments[i]));
        }
        return this;
    };

    /**
     * Writes the given line to the stream, followed by a newline.
     * @param {String} line
     * @return {TextStream} this stream
     */
    this.writeLine = function (line) {
        this.write(line + newline);
        return this;
    };

    /**
     * Writes the given lines to the stream, terminating each line with a newline.
     * This is a non-standard extension, not part of CommonJS IO/A.
     *
     * @param {Array} lines
     * @return {TextStream} this stream
     */
    this.writeLines = function (lines) {
        lines.forEach(this.writeLine, this);
        return this;
    };

    /**
     * Writes all argument values as a single line, delimiting the values using
     * a single blank.
     * @example >> var fs = require('fs');
     * >> var txtOutStream = fs.open('./demo.txt', 'w');
     * >> txtOutStream.print('foo', 'bar', 'baz');
     *
     * // demo.txt content:
     * foo bar baz
     * @return {TextStream} this stream
     */
    this.print = function () {
        for (var i = 0; i < arguments.length; i++) {
            this.write(String(arguments[i]));
            if (i < arguments.length - 1) {
                this.write(delimiter);
            }
        }
        this.write(newline);
        this.flush();
        return this;
    };

    /**
     * @see #Stream.prototype.flush
     */
    this.flush = function () {
        io.flush();
        return this;
    };

    /**
     * @see #Stream.prototype.close
     */
    this.close = function () {
        io.close();
    };

    /**
     * If the wrapped stream is a [MemoryStream](#MemoryStream) this contains its
     * content decoded to a String with this streams encoding. Otherwise contains
     * an empty String.
     */
    Object.defineProperty(this, "content", {
        get: function() {
            var wrappedContent = io.content;
            if (!wrappedContent) {
                return "";
            }
            return wrappedContent.decodeToString(charset);
        }
    });

    /**
     * The wrapped binary stream.
     */
    Object.defineProperty(this, "raw", {
        get: function() {
            return io;
        }
    });

    return this;
};

/**
 * Write bytes from b to this stream. If begin and end are specified, only the
 * range starting at begin and ending before end is written.
 * @name Stream.prototype.write
 * @param {Binary} source The source to be written from
 * @param {Number} begin optional
 * @param {Number} end optional
 * @function
 */

/**
 * Read up to `maxBytes` bytes from the stream, or until the end of the stream
 * has been reached. If `maxBytes` is not specified, the full stream is read
 * until its end is reached. Reading from a stream where the end has already been
 * reached returns an empty ByteString.
 * @name Stream.prototype.read
 * @param {Number} maxBytes the maximum number of bytes to read
 * @returns {ByteString}
 * @function
 */

/**
 * Read bytes from this stream into the given buffer. This method does
 * *not* increase the length of the buffer.
 * @name Stream.prototype.readInto
 * @param {ByteArray} buffer the buffer
 * @param {Number} begin optional begin index, defaults to 0.
 * @param {Number} end optional end index, defaults to buffer.length - 1.
 * @returns {Number} The number of bytes read or -1 if the end of the stream
 *          has been reached
 * @function
 */

/**
 * Try to skip over num bytes in the stream. Returns the number of acutal bytes skipped
 * or throws an error if the operation could not be completed.
 * @name Stream.prototype.skip
 * @param {Number} num bytes to skip
 * @returns {Number} actual bytes skipped
 * @function
 */

/**
 * Flushes the bytes written to the stream to the underlying medium.
 * @name Stream.prototype.flush
 * @function
 */

/**
 * Closes the stream, freeing the resources it is holding.
 * @name Stream.prototype.close
 * @function
 */

/**
 * Returns true if the stream has been closed, false otherwise.
 * @name Stream.prototype.closed
 * @return {Boolean} true if the stream has been closed
 * @function
 */

/**
 * Returns true if the stream supports reading, false otherwise.
 * @name Stream.prototype.readable
 * @return {Boolean} true if stream is readable
 * @function
 */

/**
 * Returns true if the stream is randomly accessible and supports the length
 * and position properties, false otherwise.
 * @name Stream.prototype.seekable
 * @return {Boolean} true if stream is seekable
 * @function
 */

/**
 * Returns true if the stream supports writing, false otherwise.
 * @name Stream.prototype.writable
 * @return {Boolean} true if stream is writable
 * @function
 */

/**
 * Get the Java input or output stream instance wrapped by this Stream.
 * @name Stream.prototype.unwrap
 * @function
 */

/**
 * The wrapped `java.io.InputStream`.
 * @name Stream.prototype.inputStream
 * @property
 * @type java.io.InputStream
 */

/**
 * The wrapped `java.io.OutputStream`.
 * @name Stream.prototype.outputStream
 * @property
 * @type java.io.OutputStream
 */


text:
package org.lab41.graphlab.twill;

import org.apache.commons.cli.*;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.twill.api.*;
import org.apache.twill.api.logging.PrinterLogHandler;
import org.apache.twill.common.Services;
import org.apache.twill.yarn.YarnTwillRunnerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Main {

    private static final Logger LOG = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        CommandLineParser parser = new GnuParser();

        Options options = new Options();

        options.addOption("h", "help", false, "print this message");
        options.addOption("i", "instances", true, "number of instances");
        options.addOption("t", "threads", true, "number of threads");
        options.addOption("debug", false, "enable debugging");

        int instanceCount = 1;
        int virtualCores = 1;
        boolean debug = false;

        try {
            CommandLine line = parser.parse(options, args, true);

            if (line.hasOption("help")) {
                printHelp(options);
                System.exit(0);
            }

            if (line.hasOption("instances")) {
                String option = line.getOptionValue("instances");
                instanceCount = Integer.parseInt(option);
            }

            if (line.hasOption("threads")) {
                String option = line.getOptionValue("threads");
                virtualCores = Integer.parseInt(option);
            }

            if (line.hasOption("debug")) {
                debug = true;
            }

            args = line.getArgs();

        } catch (ParseException e) {
            System.out.println("error: " + e);
            System.exit(1);
        }

        if (args.length != 5) {
            printHelp(options);
            System.exit(1);
        }

        String zkStr = args[0];
        GraphLabRunnable.Arguments arguments = GraphLabRunnable.Arguments.fromArray(
                Arrays.copyOfRange(args, 1, args.length));

        final TwillRunnerService twillRunner = new YarnTwillRunnerService(new YarnConfiguration(), zkStr);
        twillRunner.startAndWait();

        ResourceSpecification resources = ResourceSpecification.Builder.with()
                .setVirtualCores(virtualCores)
                .setMemory(512, ResourceSpecification.SizeUnit.MEGA)
                .setInstances(instanceCount)
                .build();

        String runnableName = "GraphLabRunnable";

        TwillPreparer preparer = twillRunner.prepare(new GraphLabRunnable(), resources)
                .withArguments(runnableName, arguments.toArray())
                .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out, true)));

        if (debug) {
            preparer.enableDebugging(true);
        }

        final TwillController controller = preparer.start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                LOG.debug("shutting down");
                controller.stopAndWait();
                twillRunner.stopAndWait();
            }
        });

        try {
            /*
            // Try to catch the debug port.
            if (debug) {
                waitForDebugPort(controller, runnableName, 300);
            }
            */

            Services.getCompletionFuture(controller).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        LOG.debug("after shutting down");
    }

    private static void printHelp(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "java" +
                " -cp graphLab-twill-1.0-SNAPSHOT.jar" +
                " org.lab41.graphLab.twill.Main" +
                " [options]" +
                " zookeeper-address" +
                " graphLab-path" +
                " input-path" +
                " input-format" +
                " output-path",
                options);
    }

    private static boolean waitForDebugPort(TwillController controller, String runnable, int timeLimit) throws InterruptedException {
        long millis = 0;
        while (millis < 1000 * timeLimit) {
            ResourceReport report = controller.getResourceReport();
            if (report == null || report.getRunnableResources(runnable) == null) {
                continue;
            }
            for (TwillRunResources resources : report.getRunnableResources(runnable)) {
                if (resources.getDebugPort() != null) {
                    System.out.println("runnable debug port: " + resources.getHost() + ":" + resources.getDebugPort());
                    return true;
                }
            }
            TimeUnit.MILLISECONDS.sleep(100);
            millis += 100;
        }
        return false;
    }
}


text:
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Controls the loading, parsing and creation of the entities from the BSP.
//
//=============================================================================//

#include "cbase.h"
#include "mapentities_shared.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)

static const char *s_BraceChars = "{}()\'";
static bool s_BraceCharacters[256];
static bool s_BuildReverseMap = true;

bool MapEntity_ExtractValue( const char *pEntData, const char *keyName, char Value[MAPKEY_MAXLENGTH] )
{
	char token[MAPKEY_MAXLENGTH];
	const char *inputData = pEntData;

	while ( inputData )
	{
		inputData = MapEntity_ParseToken( inputData, token );	// get keyname
		if ( token[0] == '}' )									// end of entity?
			break;												// must not have seen the classname

		// is this the right key?
		if ( !strcmp(token, keyName) )
		{
			inputData = MapEntity_ParseToken( inputData, token );	// get value and return it
			Q_strncpy( Value, token, MAPKEY_MAXLENGTH );
			return true;
		}

		inputData = MapEntity_ParseToken( inputData, token );	// skip over value
	}

	return false;
}

int MapEntity_GetNumKeysInEntity( const char *pEntData )
{
	char token[MAPKEY_MAXLENGTH];
	const char *inputData = pEntData;
	int iNumKeys = 0;

	while ( inputData )
	{
		inputData = MapEntity_ParseToken( inputData, token );	// get keyname
		if ( token[0] == '}' )									// end of entity?
			break;												// must not have seen the classname

		iNumKeys++;

		inputData = MapEntity_ParseToken( inputData, token );	// skip over value
	}

	return iNumKeys;
}

// skips to the beginning of the next entity in the data block
// returns NULL if no more entities
const char *MapEntity_SkipToNextEntity( const char *pMapData, char *pWorkBuffer )
{
	if ( !pMapData )
		return NULL;

	// search through the map string for the next matching '{'
	int openBraceCount = 1;
	while ( pMapData != NULL )
	{
		pMapData = MapEntity_ParseToken( pMapData, pWorkBuffer );

		if ( FStrEq(pWorkBuffer, "{") )
		{
			openBraceCount++;
		}
		else if ( FStrEq(pWorkBuffer, "}") )
		{
			if ( --openBraceCount == 0 )
			{
				// we've found the closing brace, so return the next character
				return pMapData;
			}
		}
	}

	// eof hit
	return NULL;
}

//-----------------------------------------------------------------------------
// Purpose: parses a token out of a char data block
//			the token gets fully read no matter what the length, but only MAPKEY_MAXLENGTH
//			characters are written into newToken
// Input  : char *data - the data to parse
//			char *newToken - the buffer into which the new token is written
//			char *braceChars - a string of characters that constitute braces.  this pointer needs to be
//			distince for each set of braceChars, since the usage is cached.
// Output : const char * - returns a pointer to the position in the data following the newToken
//-----------------------------------------------------------------------------
const char *MapEntity_ParseToken( const char *data, char *newToken )
{
	int             c;
	int             len;

	len = 0;
	newToken[0] = 0;

	if (!data)
		return NULL;

	// build the new table if we have to
	if ( s_BuildReverseMap )
	{
		s_BuildReverseMap = false;

		Q_memset( s_BraceCharacters, 0, sizeof(s_BraceCharacters) );

		for ( const char *c = s_BraceChars; *c; c++ )
		{
			s_BraceCharacters[static_cast<size_t>(*c)] = true;
		}
	}

// skip whitespace
skipwhite:
	while ( (c = *data) <= ' ')
	{
		if (c == 0)
			return NULL;                    // end of file;
		data++;
	}

// skip // comments
	if (c=='/' && data[1] == '/')
	{
		while (*data && *data != '\n')
			data++;
		goto skipwhite;
	}

// handle quoted strings specially
	if (c == '\"')
	{
		data++;
		while ( len < MAPKEY_MAXLENGTH )
		{
			c = *data++;
			if (c=='\"' || !c)
			{
				newToken[len] = 0;
				return data;
			}
			newToken[len] = c;
			len++;
		}

		if ( len >= MAPKEY_MAXLENGTH )
		{
			len--;
			newToken[len] = 0;
		}
	}

// parse single characters
	if ( s_BraceCharacters[c]/*c=='{' || c=='}'|| c==')'|| c=='(' || c=='\''*/ )
	{
		newToken[len] = c;
		len++;
		newToken[len] = 0;
		return data+1;
	}

// parse a regular word
	do
	{
		newToken[len] = c;
		data++;
		len++;
		c = *data;
		if ( s_BraceCharacters[c] /*c=='{' || c=='}'|| c==')'|| c=='(' || c=='\''*/ )
			break;

		if ( len >= MAPKEY_MAXLENGTH )
		{
			len--;
			newToken[len] = 0;
		}

	} while (c>32);

	newToken[len] = 0;
	return data;
}

#endif // !STATIC_LINKED || CLIENT_DLL

/* ================= CEntityMapData definition ================ */

bool CEntityMapData::ExtractValue( const char *keyName, char *value )
{
	return MapEntity_ExtractValue( m_pEntData, keyName, value );
}

bool CEntityMapData::GetFirstKey( char *keyName, char *value )
{
	m_pCurrentKey = m_pEntData; // reset the status pointer
	return GetNextKey( keyName, value );
}

const char *CEntityMapData::CurrentBufferPosition( void )
{
	return m_pCurrentKey;
}

bool CEntityMapData::GetNextKey( char *keyName, char *value )
{
	char token[MAPKEY_MAXLENGTH];

	// parse key
	char *pPrevKey = m_pCurrentKey;
	m_pCurrentKey = (char*)MapEntity_ParseToken( m_pCurrentKey, token );
	if ( token[0] == '}' )
	{
		// step back
		m_pCurrentKey = pPrevKey;
		return false;
	}

	if ( !m_pCurrentKey )
	{
		Warning( "CEntityMapData::GetNextKey: EOF without closing brace\n" );
		Assert(0);
		return false;
	}

	Q_strncpy( keyName, token, MAPKEY_MAXLENGTH );

	// fix up keynames with trailing spaces
	int n = strlen(keyName);
	while (n && keyName[n-1] == ' ')
	{
		keyName[n-1] = 0;
		n--;
	}

	// parse value
	m_pCurrentKey = (char*)MapEntity_ParseToken( m_pCurrentKey, token );
	if ( !m_pCurrentKey )
	{
		Warning( "CEntityMapData::GetNextKey: EOF without closing brace\n" );
		Assert(0);
		return false;
	}
	if ( token[0] == '}' )
	{
		Warning( "CEntityMapData::GetNextKey: closing brace without data\n" );
		Assert(0);
		return false;
	}

	// value successfully found
	Q_strncpy( value, token, MAPKEY_MAXLENGTH );
	return true;
}

//-----------------------------------------------------------------------------
// Purpose: find the keyName in the endata and change its value to specified one
//-----------------------------------------------------------------------------
bool CEntityMapData::SetValue( const char *keyName, char *NewValue, int nKeyInstance )
{
	// If this is -1, the size of the string is unknown and cannot be safely modified!
	Assert( m_nEntDataSize != -1 );
	if ( m_nEntDataSize == -1 )
		return false;

	char token[MAPKEY_MAXLENGTH];
	char *inputData = m_pEntData;
	char *prevData;

	char newvaluebuf[ 1024 ];
	int nCurrKeyInstance = 0;

	while ( inputData )
	{
		inputData = (char*)MapEntity_ParseToken( inputData, token );	// get keyname
		if ( token[0] == '}' )									// end of entity?
			break;												// must not have seen the classname

		// is this the right key?
		if ( !strcmp(token, keyName) )
		{
			++nCurrKeyInstance;
			if ( nCurrKeyInstance > nKeyInstance )
			{
				// Find the start & end of the token we're going to replace
				int entLen = strlen(m_pEntData);
				char *postData = new char[entLen];
				prevData = inputData;
				inputData = (char*)MapEntity_ParseToken( inputData, token );	// get keyname
				Q_strncpy( postData, inputData, entLen );

				// Insert quotes if caller didn't
				if ( NewValue[0] != '\"' )
				{
					Q_snprintf( newvaluebuf, sizeof( newvaluebuf ), "\"%s\"", NewValue );
				}
				else
				{
					Q_strncpy( newvaluebuf, NewValue, sizeof( newvaluebuf ) );
				}

				int iNewValueLen = Q_strlen(newvaluebuf);
				int iPadding = iNewValueLen - Q_strlen( token ) - 2;	// -2 for the quotes (token doesn't have them)

				// prevData has a space at the start, seperating the value from the key.
				// Add 1 to prevData when pasting in the new Value, to account for the space.
				Q_strncpy( prevData+1, newvaluebuf, iNewValueLen+1 );	// +1 for the null terminator
				Q_strcat( prevData, postData, m_nEntDataSize - ((prevData-m_pEntData)+1) );

				m_pCurrentKey += iPadding;
				delete [] postData;
				return true;
			}
		}

		inputData = (char*)MapEntity_ParseToken( inputData, token );	// skip over value
	}

	return false;
}


text:
package org.apache.hadoop.hive.cassandra.serde;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.hadoop.hive.serde2.ByteStream;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.lazy.LazyCassandraUtils;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe.SerDeParameters;
import org.apache.hadoop.hive.serde2.lazy.LazyUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Writable;

public abstract class TableMapping {
    /* names of columns from SerdeParameters */

    protected final List<String> cassandraColumnNames;

    protected final String cassandraColumnFamily;

    private boolean useJSONSerialize;
    protected final ByteStream.Output serializeStream = new ByteStream.Output();

    private final byte[] separators; // the separators array
    private final boolean escaped; // whether we need to escape the data when writing out
    private final byte escapeChar; // which char to use as the escape char, e.g. '\\'
    private final boolean[] needsEscape; // which chars need to be escaped. This array should have size

    protected TableMapping(String colFamily, List<String> columnNames, SerDeParameters serdeParams) {
        this.cassandraColumnFamily = colFamily;
        this.cassandraColumnNames = columnNames;

        separators = serdeParams.getSeparators();
        escaped = serdeParams.isEscaped();
        escapeChar = serdeParams.getEscapeChar();
        needsEscape = serdeParams.getNeedsEscape();
    }

    public abstract Writable getWritable(
            List<? extends StructField> fields,
            List<Object> list,
            List<? extends StructField> declaredFields) throws IOException;

    /**
     * Serialize the index-th object into bytes array.
     *
     * @param index the index of the object to be seralized.
     * @param fields a list of fields
     * @param list a list of objects
     * @param declaredFields a list of declared fields
     * @return object serialized into bytes
     * @throws IOException
     */
    protected byte[] serializeToBytes(int index,
            List<? extends StructField> fields,
            List<Object> list,
            List<? extends StructField> declaredFields) throws IOException {
        return serializeToBytes(
                fields.get(index).getFieldObjectInspector(),
                declaredFields.get(index).getFieldObjectInspector(),
                list.get(index),
                useJsonSerialize(index, declaredFields));
    }

    /**
     * Return true if using json serialization. Otherwise, false;
     *
     * @param index the index of the field to be deserialized.
     * @param declaredFields a list of declared fields
     * @return true if using json serialization
     */
    protected boolean useJsonSerialize(int index, List<? extends StructField> declaredFields) {
        return (declaredFields == null
                || declaredFields.get(index).getFieldObjectInspector().getCategory()
                .equals(Category.PRIMITIVE) || useJSONSerialize);
    }

    /**
     * Serialize a object into bytes.
     *
     * @param foi object inspector
     * @param obj object to be serialized
     * @param useJsonSerialize true to use json serialization
     * @return object in serialized bytes
     * @throws IOException when error happens
     */
    protected byte[] serializeToBytes(ObjectInspector foi, ObjectInspector doi, Object obj, boolean useJsonSerialize) throws IOException {
        serializeStream.reset();
        boolean isNotNull;
        if (!foi.getCategory().equals(Category.PRIMITIVE)
                && useJsonSerialize) {
            isNotNull = serialize(SerDeUtils.getJSONString(obj, foi),
                    PrimitiveObjectInspectorFactory.javaStringObjectInspector, doi, 1);
        } else {
            isNotNull = serialize(obj, foi, doi, 1);
        }
        if (!isNotNull) {
            return null;
        }
        byte[] key = new byte[serializeStream.getLength()];
        System.arraycopy(serializeStream.getData(), 0, key, 0, serializeStream.getLength());

        return key;
    }

    protected boolean serialize(Object obj, ObjectInspector objInspector, ObjectInspector declaredObjInspector, int level)
            throws IOException {

        switch (objInspector.getCategory()) {
            case PRIMITIVE: {

                //Marshal to expected cassandra format
                AbstractType validator = LazyCassandraUtils.getCassandraType((PrimitiveObjectInspector) declaredObjInspector);

                if (validator instanceof BytesType) {
                    BytesWritable bw = ((BinaryObjectInspector) objInspector).getPrimitiveWritableObject(obj);
                    serializeStream.write(bw.getBytes(), 0, bw.getLength());
                } else {

                    LazyUtils.writePrimitiveUTF8(
                            serializeStream, obj,
                            (PrimitiveObjectInspector) objInspector,
                            escaped, escapeChar, needsEscape);

                    //convert from string to cassandra type
                    if (!declaredObjInspector.getTypeName().equals(PrimitiveObjectInspectorUtils.stringTypeEntry.typeName)) {
                        ByteBuffer bb = validator.fromString(serializeStream.toString());
                        serializeStream.reset();
                        serializeStream.write(ByteBufferUtil.getArray(bb));
                    }
                }

                return true;
            }
            case LIST: {
                char separator = (char) separators[level];
                ListObjectInspector loi = (ListObjectInspector) objInspector;
                List<?> list = loi.getList(obj);
                ObjectInspector eoi = loi.getListElementObjectInspector();
                if (list == null) {
                    return false;
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        if (i > 0) {
                            serializeStream.write(separator);
                        }
                        serialize(list.get(i), eoi, PrimitiveObjectInspectorFactory.javaStringObjectInspector, level + 1);
                    }
                }
                return true;
            }
            case MAP: {
                char separator = (char) separators[level];
                char keyValueSeparator = (char) separators[level + 1];
                MapObjectInspector moi = (MapObjectInspector) objInspector;
                ObjectInspector koi = moi.getMapKeyObjectInspector();
                ObjectInspector voi = moi.getMapValueObjectInspector();

                Map<?, ?> map = moi.getMap(obj);
                if (map == null) {
                    return false;
                } else {
                    boolean first = true;
                    for (Map.Entry<?, ?> entry : map.entrySet()) {
                        if (first) {
                            first = false;
                        } else {
                            serializeStream.write(separator);
                        }
                        serialize(entry.getKey(), koi, PrimitiveObjectInspectorFactory.javaStringObjectInspector, level + 2);
                        serializeStream.write(keyValueSeparator);
                        serialize(entry.getValue(), voi, PrimitiveObjectInspectorFactory.javaStringObjectInspector, level + 2);
                    }
                }
                return true;
            }
            case STRUCT: {
                char separator = (char) separators[level];
                StructObjectInspector soi = (StructObjectInspector) objInspector;
                List<? extends StructField> fields = soi.getAllStructFieldRefs();
                List<Object> list = soi.getStructFieldsDataAsList(obj);
                if (list == null) {
                    return false;
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        if (i > 0) {
                            serializeStream.write(separator);
                        }
                        serialize(list.get(i), fields.get(i).getFieldObjectInspector(), PrimitiveObjectInspectorFactory.javaStringObjectInspector, level + 1);
                    }
                }
                return true;
            }
        }
        throw new RuntimeException("Unknown category type: " + objInspector.getCategory());
    }
}


text:
package com.google.gdata.data.photos;

import com.google.gdata.data.AbstractExtension;
import com.google.gdata.data.AttributeGenerator;
import com.google.gdata.data.AttributeHelper;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.util.ParseException;

import java.util.Date;

/**
 * A datetime in unix timestamp format.
 *
 *
 */
@ExtensionDescription.Default(
    nsAlias = Namespaces.PHOTOS_ALIAS,
    nsUri = Namespaces.PHOTOS,
    localName = GphotoTimestamp.XML_NAME)
public class GphotoTimestamp extends AbstractExtension {

  /** XML element name */
  static final String XML_NAME = "timestamp";

  /** Timestamp */
  private Long value = null;

  /**
   * Default mutable constructor.
   */
  public GphotoTimestamp() {
    super();
  }

  /**
   * Immutable constructor.
   *
   * @param value timestamp.
   */
  public GphotoTimestamp(Long value) {
    super();
    setValue(value);
    setImmutable(true);
  }

  /**
   * Returns the timestamp.
   *
   * @return timestamp
   */
  public Long getValue() {
    return value;
  }

  /**
   * Sets the timestamp.
   *
   * @param value timestamp or null to reset
   */
  public void setValue(Long value) {
    throwExceptionIfImmutable();
    this.value = value;
  }

  /**
   * Returns whether it has the timestamp.
   *
   * @return whether it has the timestamp
   */
  public boolean hasValue() {
    return getValue() != null;
  }

  @Override
  protected void validate() {
  }

  /**
   * Returns the extension description, specifying whether it is required, and
   * whether it is repeatable.
   *
   * @param required   whether it is required
   * @param repeatable whether it is repeatable
   * @return extension description
   */
  public static ExtensionDescription getDefaultDescription(boolean required,
      boolean repeatable) {
    ExtensionDescription desc =
        ExtensionDescription.getDefaultDescription(GphotoTimestamp.class);
    desc.setRequired(required);
    desc.setRepeatable(repeatable);
    return desc;
  }

  @Override
  protected void putAttributes(AttributeGenerator generator) {
    generator.setContent(value.toString());
  }

  @Override
  protected void consumeAttributes(AttributeHelper helper) throws ParseException
      {
    value = helper.consumeLong(null, false);
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (!sameClassAs(obj)) {
      return false;
    }
    GphotoTimestamp other = (GphotoTimestamp) obj;
    return eq(value, other.value);
  }

  @Override
  public int hashCode() {
    int result = getClass().hashCode();
    if (value != null) {
      result = 37 * result + value.hashCode();
    }
    return result;
  }

  @Override
  public String toString() {
    return "{GphotoTimestamp value=" + value + "}";
  }

  public GphotoTimestamp(Date value) {
    this(value == null ? null : value.getTime());
  }
}


text:
* Below the _preferred wording_ is in italics.

### Notes

* PEI Devs has been meeting since _spring 2012_, not 2011.
* 'About 25 people' could be _On average, 25 people_
* re: panel. no mention of Wendy MacIntyre ?
* Ian Morse is a developer of _digital signage_ (as opposed to digital screens)


text:
package io.reactivesw.order.shippingmethod.application.model;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.reactivesw.common.model.Reference;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * This representation needs to be given with a Create ShippingMethod request.
 * Created by umasuo on 16/11/17.
 */
@ApiModel(description = "This representation needs to be given with a Create ShippingMethod " +
    "request.")
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ShippingMethodDraft {

  @ApiModelProperty(required = true)
  private String name;

  @ApiModelProperty(required = false)
  private String description;

  @ApiModelProperty(required = true)
  private Reference taxCategory;

  @ApiModelProperty(required = true)
  private List<ZoneRate> zoneRates;

  @ApiModelProperty(value = "If true the shipping method will be the default one in a merchant.",
      required = true)
  private Boolean isDefault;

}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.idm.engine.delegate.event.impl;

import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.idm.api.event.FlowableIdmEventType;

/**
 * Base class for all IDM event implementations.
 *
 * @author Tijs Rademakers
 */
public class FlowableIdmEventImpl implements FlowableEvent {

    protected FlowableIdmEventType type;

    /**
     * Creates a new event implementation, not part of an execution context.
     */
    public FlowableIdmEventImpl(FlowableIdmEventType type) {
        if (type == null) {
            throw new FlowableIllegalArgumentException("type is null");
        }
        this.type = type;
    }

    @Override
    public FlowableIdmEventType getType() {
        return type;
    }

    public void setType(FlowableIdmEventType type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return getClass() + " - " + type;
    }

}


text:
@implementation TongXunmodel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.ob-flush">
 <refnamediv>
  <refname>ob_flush</refname>
  <refpurpose>Flush (send) the output buffer</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>void</type><methodname>ob_flush</methodname>
   <void/>
  </methodsynopsis>
  <para>
   This function will send the contents of the output buffer (if any). If you
   want to further process the buffer's contents you have to call
   <function>ob_get_contents</function> before <function>ob_flush</function>
   as the buffer contents are discarded after <function>ob_flush</function>
   is called.
  </para>
  <para>
   This function does not destroy the output buffer like
   <function>ob_end_flush</function> does.
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &return.void;
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>ob_get_contents</function></member>
    <member><function>ob_clean</function></member>
    <member><function>ob_end_flush</function></member>
    <member><function>ob_end_clean</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
typedef struct _IconStubClass IconStubClass;
typedef struct _IconStub IconStub;

#define ICON_STUB_TYPE (icon_stub_get_type())
#define ICON_STUB(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), ICON_STUB_TYPE, IconStub))
#define ICON_STUB_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), ICON_STUB_TYPE, IconStubClass))
#define IS_ICON_STUB(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), ICON_STUB_TYPE))
#define IS_ICON_STUB_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), ICON_STUB_TYPE))
#define ICON_STUB_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), ICON_STUB_TYPE, IconStubClass))

GType icon_stub_get_type();

enum {
	ICON_STUB_PROPERTY_0,
	ICON_STUB_PROPERTY_BLINKING,
	ICON_STUB_PROPERTY_EMBEDDED,
	ICON_STUB_PROPERTY_FILE,
	ICON_STUB_PROPERTY_GICON,
	ICON_STUB_PROPERTY_HAS_TOOLTIP,
	ICON_STUB_PROPERTY_ICON_NAME,
	ICON_STUB_PROPERTY_ORIENTATION,
	ICON_STUB_PROPERTY_PIXBUF,
	ICON_STUB_PROPERTY_SCREEN,
	ICON_STUB_PROPERTY_SIZE,
	ICON_STUB_PROPERTY_STOCK,
	ICON_STUB_PROPERTY_STORAGE_TYPE,
	ICON_STUB_PROPERTY_TITLE,
	ICON_STUB_PROPERTY_TOOLTIP_MARKUP,
	ICON_STUB_PROPERTY_TOOLTIP_TEXT,
	ICON_STUB_PROPERTY_VISIBLE
} IconStubProperty;

void icon_stub_get_property(GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
void icon_stub_set_property(GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);

void icon_stub_configure_menu_prepend_activate(IconStub * icon_stub, GtkWidget * menu);
void icon_stub_configure_menu_select_activate(IconStub * icon_stub, GtkWidget * menu_item);
void icon_stub_configure_menu_select_activate_head(IconStub * icon_stub, GtkWidget * menu);

IconStub * icon_stub_new(const gchar * id, const gchar * title, const gchar * default_icon, gpointer data);

gpointer icon_stub_get_data(IconStub * icon_stub);

void icon_stub_set_query_tooltip(IconStub * icon_stub, gboolean query_tooltip);
void icon_stub_set_icon_tooltip(IconStub * icon_stub, const gchar * name, const gchar * tooltip_text);
void icon_stub_set_visible(IconStub * icon_stub, gboolean visible);

void * icon_stub_dlsym_override(const char * symbol);

#define status_icon_check_condition_void(condition, function, args, call) \
if (condition) { \
	super_lookup_static(function, void, args); \
	function##_super(call); \
	return; \
}

#define status_icon_check_condition(condition, function, result, args, call) \
if (condition) { \
	super_lookup_static(function, result, args); \
	return function##_super(call); \
}

#define status_icon_check_void(function, args, call) \
status_icon_check_condition_void(GTK_IS_STATUS_ICON(status_icon), function, \
	pass_args(args), pass_args(call))

#define status_icon_check(function, result, args, call) \
status_icon_check_condition(GTK_IS_STATUS_ICON(status_icon), function, result, \
	pass_args(args), pass_args(call))

#define status_icon_check_init_void(function, args, call) \
status_icon_check_condition_void(app_indicator_falling_back, function, \
	pass_args(args), pass_args(call))

#define status_icon_check_init(function, result, args, call) \
status_icon_check_condition(app_indicator_falling_back, function, result, \
	pass_args(args), pass_args(call))

#endif


text:
using System.Windows;
using System.Windows.Media;

namespace Toasts
{
    public interface IToastLayoutCustomRenderer
    {
        UIElement Render(ToastNotificationType type, string title, string description, object context, out Brush backgroundBrush);

        bool IsTappable { get; }

        bool HasCloseButton { get; }
    }
}


text:
class TeamProperty < ApplicationRecord
  include Warehousable

  VALID_KEYS = %w(
    area
    lead
    can_allocate
    role
  ).freeze
  ROLES = %w[manager responder approver].freeze

  belongs_to :team

  validates :value, uniqueness: { scope: [:team_id, :key], message: "%{value} is not unique in team and key" }
  validates :key, inclusion: { in: VALID_KEYS, message: "%{value} is not a valid key" }

  # This rather strange syntax checks that there can only be one lead property per team
  validates :key,
            if: -> (tp) { tp.key == 'lead' },
            uniqueness: { scope: :team_id, message: 'lead already exists for this team'}

  validates :value,
            if: -> (tp) { tp.key == 'role' },
            inclusion: ROLES

  scope :area, -> { where( key: 'area').order(created_at: :desc) }

  scope :lead, -> { where( key: 'lead') }
  scope :role, -> { where( key: 'role') }

end


text:
package org.jbpm.ruleflow.core.factory;

import org.jbpm.process.core.event.EventFilter;
import org.jbpm.process.core.event.EventTransformer;
import org.jbpm.process.core.event.EventTypeFilter;
import org.jbpm.ruleflow.core.RuleFlowNodeContainerFactory;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.NodeContainer;
import org.jbpm.workflow.core.node.BoundaryEventNode;

public class BoundaryEventNodeFactory extends NodeFactory {

    private NodeContainer nodeContainer;

    private String attachedToUniqueId;

    public BoundaryEventNodeFactory(RuleFlowNodeContainerFactory nodeContainerFactory, NodeContainer nodeContainer, long id) {
        super(nodeContainerFactory, nodeContainer, id);
        this.nodeContainer = nodeContainer;
    }

    public BoundaryEventNodeFactory attachedTo(long attachedToId) {
        attachedToUniqueId = (String)nodeContainer.getNode(attachedToId).getMetaData().get("UniqueId");
        getBoundaryEventNode().setAttachedToNodeId(attachedToUniqueId);
        getBoundaryEventNode().setMetaData("AttachedTo", attachedToUniqueId);
        return this;
    }

    protected Node createNode() {
        return new BoundaryEventNode();
    }

    protected BoundaryEventNode getBoundaryEventNode() {
        return(BoundaryEventNode) getNode();
    }

    public BoundaryEventNodeFactory name(String name) {
        getNode().setName(name);
        return this;
    }

    public BoundaryEventNodeFactory variableName(String variableName) {
        getBoundaryEventNode().setVariableName(variableName);
        return this;
    }

    public BoundaryEventNodeFactory eventFilter(EventFilter eventFilter) {
        getBoundaryEventNode().addEventFilter(eventFilter);
        return this;
    }

    public BoundaryEventNodeFactory eventType(String eventType) {
        EventTypeFilter filter = new EventTypeFilter();
        filter.setType(eventType);
        return eventFilter(filter);
    }

    public BoundaryEventNodeFactory eventType(String eventTypePrefix, String eventTypeSurffix) {
        if (attachedToUniqueId == null) {
            throw new IllegalStateException("attachedTo() must be called before");
        }
        EventTypeFilter filter = new EventTypeFilter();
        filter.setType(eventTypePrefix + "-" + attachedToUniqueId + "-" + eventTypeSurffix);
        return eventFilter(filter);
    }

    public BoundaryEventNodeFactory timeCycle(String timeCycle) {
        eventType("Timer", timeCycle);
        setMetaData("TimeCycle", timeCycle);
        return this;
    }

    public BoundaryEventNodeFactory timeCycle(String timeCycle, String language) {
        eventType("Timer", timeCycle);
        setMetaData("TimeCycle", timeCycle);
        setMetaData("Language", language);
        return this;
    }

    public BoundaryEventNodeFactory timeDuration(String timeDuration) {
        eventType("Timer", timeDuration);
        setMetaData("TimeDuration", timeDuration);
        return this;
    }

    public BoundaryEventNodeFactory cancelActivity(boolean cancelActivity) {
        setMetaData("CancelActivity", cancelActivity);
        return this;
    }

    public BoundaryEventNodeFactory eventTransformer(EventTransformer transformer) {
        getBoundaryEventNode().setEventTransformer(transformer);
        return this;
    }

    public BoundaryEventNodeFactory scope(String scope) {
        getBoundaryEventNode().setScope(scope);
        return this;
    }

    public BoundaryEventNodeFactory setMetaData(String name,Object value) {
        getBoundaryEventNode().setMetaData(name, value);
        return this;
    }
}


text:
package com.yalantis.phoenix.interfacepackage;

/**
 * Created by shijg on 2017/9/19.
 */

public interface RefreshableAndLoadable {
    void onRefreshing();
    void onLoading();
}


text:
<?php
namespace Anax\Questions;

/**
 * Model for Questions.
 *
 */
class Questions extends \Anax\MVC\CDatabaseModel
{
    private $questionRank = <<<EOD
	SELECT
	    (
		SELECT count(*) FROM QuestionVotes WHERE QuestionVotes.questionId = Q.id AND isUpvote = "TRUE"
	    )
	    -
	    (
		SELECT count(*) FROM QuestionVotes WHERE QuestionVotes.questionId = Q.id AND isUpvote = "FALSE"
	    )
EOD;
    private $answerRank = <<<EOD
	SELECT
	    (
		SELECT count(*) FROM AnswerVotes WHERE AnswerVotes.answerId = A.id AND isUpvote = "TRUE"
	    )
	    -
	    (
		SELECT count(*) FROM AnswerVotes WHERE AnswerVotes.answerId = A.id AND isUpvote = "FALSE"
	    )
EOD;
    private $commentRank = <<<EOD
	SELECT
	    (
		SELECT count(*) FROM CommentVotes WHERE CommentVotes.commentId = C.id AND isUpvote = "TRUE"
	    )
	    -
	    (
		SELECT count(*) FROM CommentVotes WHERE CommentVotes.commentId = C.id AND isUpvote = "FALSE"
	    )
EOD;

    public function addQuestion($header, $question, $tags){
	$this->create([
	    'header' => $header,
	    'question' => $question,
	    'userId'	=> $this->session->get('user')->getProperties()['id'],
	]);

	$questionId = $this->db->lastInsertId();

	$sql = 'INSERT INTO QuestionTags (\'questionId\', \'tag\') VALUES (?, ?)';
	foreach($tags as $t){
	    $t = strtoupper(trim($t));
	    $params = [$questionId, $t];
	    $this->db->execute($sql, $params);
	}

	return $questionId;
    }
    public function addAnswer($id, $answer){
	$sql = 'INSERT INTO Answers(\'questionId\', \'answer\', \'userId\') VALUES (?, ?, ?)';

	$userId = $this->session->get('user')->getProperties()['id'];
	$params = [$id, $answer, $userId];
	$this->db->execute($sql, $params);
    }
    public function addComment($id, $comment){
	$sql = 'INSERT INTO Comments(\'answerId\', \'comment\', \'userId\') VALUES (?, ?, ?)';

	$userId = $this->session->get('user')->getProperties()['id'];
	$params = [$id, $comment, $userId];
	$this->db->execute($sql, $params);
	$commentId = $this->db->lastInsertId();
	return $commentId;
    }

    public function getQuestionForComment($commentId){
	$sql = 'SELECT A.questionId FROM Comments AS C INNER JOIN Answers AS A ON C.answerId = A.id WHERE C.id = ?';
	$params = [$commentId];
	return $this->db->executeFetchAll($sql, $params)[0]->questionId;
    }

    public function getTagsForQuestion($questionId){
	$sql = 'SELECT tag FROM QuestionTags AS T INNER JOIN Questions AS Q ON T.questionId = Q.id WHERE Q.id = ?';
	$params = [$questionId];

	return $this->db->executeFetchAll($sql, $params);
    }
    public function getAnswersForQuestion($questionId){
	$sql = 'SELECT Q.id, U.name, A.answer, A.accepted, A.userId, A.id, ('.$this->answerRank.') AS rank FROM Answers AS A INNER JOIN Questions AS Q ON Q.id = A.questionId INNER JOIN Users AS U ON U.id = A.userId WHERE Q.id = ? ORDER BY A.created DESC';
	$params = [$questionId];
	return $this->db->executeFetchAll($sql, $params);
    }
    public function getCommentsForAnswer($answerId){
	$sql = 'SELECT C.id, U.name, C.comment, C.userId, ('.$this->commentRank.') AS rank FROM Comments AS C INNER JOIN Answers AS A ON A.id = C.answerId INNER JOIN Users AS U ON U.id = C.userId WHERE A.id = ? ORDER BY C.created DESC';
	$params = [$answerId];
	return $this->db->executeFetchAll($sql, $params);
    }
    public function getQuestionWithId($id){
	$answers = 'SELECT count(*) FROM Answers WHERE questionId = ?';

	$sql = 'SELECT Q.id, U.name, Q.userId, Q.header, Q.question, ('.$answers.') AS answers, ('.$this->questionRank.') AS rank FROM Questions AS Q INNER JOIN Users AS U ON Q.userId = U.id WHERE Q.id = ?';
	$params = [$id, $id];
	return $this->db->executeFetchAll($sql, $params);
    }
    public function findAllQuestions($order){
	$answers = 'SELECT count(*) FROM Answers WHERE questionId = Q.id';
	$sql = 'SELECT U.name, Q.userId, Q.header, Q.question, Q.id, ('.$answers.') AS answers, ('.$this->questionRank.') AS rank FROM Questions AS Q INNER JOIN Users AS U ON Q.userId = U.id ORDER BY '.$order.' DESC';
	$params = [];
	return $this->db->executeFetchAll($sql, $params);
    }
    public function getLatestQuestions(){
	$answers = 'SELECT count(*) FROM Answers WHERE questionId = Q.id';
	$sql = 'SELECT U.name, Q.userId, Q.header, Q.question, Q.id, ('.$answers.') AS answers, ('.$this->questionRank.') AS rank FROM Questions AS Q INNER JOIN Users AS U ON Q.userId = U.id ORDER BY Q.created DESC LIMIT 3';
	$params = [];
	return $this->db->executeFetchAll($sql, $params);
    }
    public function acceptAnswer($id){
	$sql = 'UPDATE Answers SET accepted = "TRUE" WHERE id = ?';
	$params = [$id];
	$this->db->execute($sql, $params);
    }

    public function questionAlreadyVoted($userId, $questionId){
	$sql = 'SELECT count(*) AS count FROM QuestionVotes  WHERE voterId = ? AND questionId = ?';
	$params = [$userId, $questionId];
	return $this->db->executeFetchAll($sql, $params)[0]->count;
    }
    public function answerAlreadyVoted($userId, $answerId){
	$sql = 'SELECT count(*) AS count FROM AnswerVotes WHERE voterId = ? AND answerId = ?';
	$params = [$userId, $answerId];
	return $this->db->executeFetchAll($sql, $params)[0]->count;
    }
    public function commentAlreadyVoted($userId, $commentId){
	$sql = 'SELECT count(*) AS count FROM CommentVotes WHERE voterId = ? AND commentId = ?';
	$params = [$userId, $commentId];
	return $this->db->executeFetchAll($sql, $params)[0]->count;
    }
    public function questionVote($userId, $questionId, $isUpvote){
	$sql = "INSERT INTO QuestionVotes ('voterId', 'questionId', 'isUpvote') VALUES (?,?,?)";
	$params = [$userId, $questionId, $isUpvote];
	$this->db->execute($sql, $params);
    }
    public function commentVote($userId, $commentId, $isUpvote){
	$sql = "INSERT INTO CommentVotes ('voterId', 'commentId', 'isUpvote') VALUES (?,?,?)";
	$params = [$userId, $commentId, $isUpvote];
	$this->db->execute($sql, $params);
    }
    public function answerVote($userId, $answerId, $isUpvote){
	$sql = "INSERT INTO AnswerVotes ('voterId', 'answerId', 'isUpvote') VALUES (?,?,?)";
	$params = [$userId, $answerId, $isUpvote];
	$this->db->execute($sql, $params);
    }
}


text:
package com.davidbracewell.apollo.linear.sparse;

import com.davidbracewell.apollo.linear.NDArray;
import com.davidbracewell.apollo.linear.NDArrayFactory;
import org.apache.mahout.math.function.IntDoubleProcedure;
import org.apache.mahout.math.list.IntArrayList;
import org.apache.mahout.math.map.OpenIntFloatHashMap;

/**
 * @author David B. Bracewell
 */
public class SparseFloatNDArray extends SparseNDArray {
   private static final long serialVersionUID = 1L;
   private final OpenIntFloatHashMap storage = new OpenIntFloatHashMap();

   public SparseFloatNDArray(int nRows, int nCols) {
      super(nRows, nCols);
   }

   @Override
   protected double adjustOrPutValue(int index, double amount) {
      return storage.adjustOrPutValue(index, (float) amount, (float) amount);
   }

   @Override
   public NDArray compress() {
      storage.trimToSize();
      return this;
   }

   @Override
   protected void forEachPair(IntDoubleProcedure procedure) {
      storage.forEachPair((index, value) -> {
         procedure.apply(index, value);
         return true;
      });
   }

   @Override
   public double get(int index) {
      return storage.get(index);
   }

   @Override
   public NDArrayFactory getFactory() {
      return NDArrayFactory.SPARSE_FLOAT;
   }

   @Override
   protected IntArrayList nonZeroIndexes() {
      return storage.keys();
   }

   @Override
   protected void removeIndex(int index) {
      storage.removeKey(index);
   }

   @Override
   protected void setValue(int index, double value) {
      storage.put(index, (float) value);
   }

   @Override
   public int size() {
      return storage.size();
   }

}//END OF SparseFloatNDArray


text:
/**
 * @fileOverview A test runner compliant to the
 * [CommonJS Unit Testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0)
 * specification.
 */

var strings = require("ringo/utils/strings");
var term = require("ringo/term");
var fs = require("fs");

export(
    "run",
    "jsDump",
    "getStackTrace",
    "getType"
);

var {
    AssertionError,
    ArgumentsError
} = require("./assert");

/**
 * Converts the value passed as argument into a nicely formatted and
 * indented string
 * @param {Object} value The value to convert into a string
 * @param {Number} lvl Optional indentation level (defaults to zero)
 * @returns The string representation of the object passed as argument
 * @type String
 */
function jsDump(value, lvl) {
    if (!lvl) {
        lvl = 0;
    }

    switch (getType(value)) {
        case "string":
            return jsDump.quote(value);
        case "boolean":
        case "number":
        case "nan":
        case "date":
        case "regexp":
            return value.toString();
        case "undefined":
        case "null":
            return String(value);
        case "function":
            if (getType(value.name) === "string" && value.name.length > 0) {
                return value.name;
            }
            return value.toSource();
        case "array":
            var buf = value.map(function(val) {
                return jsDump.indent(lvl + 1) + jsDump(val, lvl + 1);
            });
            return ["[", buf.join(",\n"), jsDump.indent(lvl) + "]"].join("\n");
        case "object":
            var buf = [];
            for (var propName in value) {
                buf.push(jsDump.indent(lvl + 1) + '"' + propName + '": ' + jsDump(value[propName], lvl + 1));
            }
            return ["{", buf.join(",\n"), jsDump.indent(lvl) + "}"].join("\n");
        case "java":
            return '<java:' + value.class.name + '>';
    }
}
jsDump.indent = function(lvl) {
    return strings.repeat("    ", lvl);
};
jsDump.quote = function(str) {
    return JSON.stringify(str.toString());
};

/**
 * Returns the type of the object passed as argument. This is
 * heavily inspired by http://philrathe.com/articles/equiv and
 * tlrobinson's narwhal test module (http://github.com/tlrobinson/narwhal/)
 * @returns The type of the object passed as argument
 * @type String
 */
function getType(obj) {
    if (typeof(obj) === "string") {
        return "string";
    } else if (typeof(obj) === "boolean") {
        return "boolean";
    } else if (typeof (obj) === "number") {
        return (isNaN(obj) === true) ? "nan" : "number";
    } else if (typeof(obj) === "undefined") {
        return "undefined";
    } else if (obj === null) {
        return "null";
    } else if (obj instanceof Array) {
        return "array";
    } else if (obj instanceof Date) {
        return "date";
    } else if (obj instanceof RegExp) {
        return "regexp";
    } else if (obj instanceof Function) {
        return "function";
    } else if (obj instanceof java.lang.Object) {
        return "java";
    }
    return "object";
}

/**
 * Creates a stack trace and parses it for display.
 * @param {java.lang.StackTraceElement} trace The trace to parse. If not given
 * a stacktrace will be generated
 * @returns The parsed stack trace
 * @type String
 */
function getStackTrace(trace) {
    // create exception and fill in stack trace
    if (!trace) {
        var ex = new Packages.org.mozilla.javascript.EvaluatorException("");
        ex.fillInStackTrace();
        trace = ex.getScriptStack();
    }
    var stack = [];
    var el, fileName, lineNumber;
    for (var i = 0; i < trace.length; i += 1) {
        el = trace[i];
        if (el.fileName != null && el.lineNumber > -1) {
            // exclude all lines containing the unittest module itself
            // FIXME (ro): this is quite ugly, but it works ...
            if (el.fileName.indexOf(module.id) === 0 || el.fileName.indexOf("assert") === 0) {
                continue;
            }
            stack.push("at " + el.fileName + ":" + el.lineNumber);
        }
    }
    return stack;
};

/**
 * The main runner method. This method can be called with one, two or three
 * arguments: run(scope), run(scope, nameOfTest),
 * run(scope, writer) or run(scope, nameOfTest, writer)
 * @param {String|Object} scope Either the path to a module containing unit
 * tests to execute, or an object containing the exported test methods or nested scopes.
 * @param {String} name Optional name of a test method to execute
 * @param {Object} writer Optional writer to use for displaying the test results. Defaults
 * to TermWriter.
 */
function run(scope, name, writer) {
    if (arguments.length === 2) {
        if (typeof(arguments[1]) === "object") {
            writer = name;
            name = undefined;
        } else {
            writer = new TermWriter();
        }
    } else if (arguments.length === 1) {
        writer = new TermWriter();
    }
    if (typeof(scope) === "string") {
        scope = require(fs.resolve(fs.workingDirectory(), scope));
    }
    var summary = {
        "testsRun": 0,
        "passed": 0,
        "errors": 0,
        "failures": 0,
        "time": 0
    };
    writer.writeHeader();
    if (name != undefined) {
        executeTest(scope, name, summary, writer, []);
    } else {
        executeTestScope(scope, summary, writer, []);
    }
    scope = null;
    writer.writeSummary(summary);
    return summary.failures + summary.errors;
}

/**
 * Loops over all properties of a test scope and executes all methods whose
 * name starts with "test".
 * @param {Object} scope The scope object containing the test functions
 * @param {Object} summary An object containing summary information
 * @param {Object} writer A writer instance for displaying test results
 * @param {Array} path An array containing property path segments
 */
function executeTestScope(scope, summary, writer, path) {
    // loop over all exported properties and see if there are test methods to run
    for (var name in scope) {
        var value = scope[name];
        if (name === "test" || !strings.startsWith(name, "test")) {
            continue;
        }
        executeTest(scope, name, summary, writer, path);
    }
    return;
};

/**
 * Executes a single test, which can be either a single test method
 * or a test submodule.
 * @param {Object} scope The scope object containing the test
 * @param {String} name The name of the test to execute
 * @param {Object} summary An object containing summary information
 * @param {Object} writer A writer instance for displaying test results
 * @param {Array} path An array containing property path segments
 */
function executeTest(scope, name, summary, writer, path) {
    var value = scope[name];
    if (value instanceof Function) {
        writer.writeTestStart(name);
        var start = null;
        var time = 0;
        try {
            // execute setUp, if defined
            if (typeof(scope.setUp) === "function") {
                scope.setUp();
            }
            // execute test function
            start = new Date();
            value();
            time = (new Date()).getTime() - start.getTime();
            writer.writeTestPassed(time);
            summary.passed += 1;
        } catch (e) {
            if (!(e instanceof AssertionError) && !(e instanceof ArgumentsError)) {
                e = new EvaluationError(e);
            }
            writer.writeTestFailed(e);
            if (e instanceof AssertionError) {
                summary.failures += 1;
            } else {
                summary.errors += 1;
            }
        } finally {
            // execute tearDown, if defined
            if (typeof(scope.tearDown) === "function") {
                scope.tearDown();
            }
            summary.testsRun += 1;
            summary.time += time;
        }
    } else if (value.constructor === Object) {
        writer.enterScope(name);
        executeTestScope(value, summary, writer, path.concat([name]));
        writer.exitScope(name);
    }
    return;
}

/*******************************************
 *****  T E R M I N A L   W R I T E R  *****
 *******************************************/

/**
 * Constructs a new TermWriter instance
 * @class Instances of this class represent a writer for displaying test results
 * in the shell
 * @returns A newly created TermWriter instance
 * @constructor
 */
var TermWriter = function() {
    this.indent = "";
    return this;
};

/** @ignore */
TermWriter.prototype.toString = function() {
    return "[TermWriter]";
};

/**
 * Write a header at the beginning of a unit test(suite)
 */
TermWriter.prototype.writeHeader = function() {
    term.writeln("================================================================================");
    return;
};

/**
 * Notification that we're entering a new test scope.
 * @param name the name of the test scope
 */
TermWriter.prototype.enterScope = function(name) {
    term.writeln(this.indent, "+ Running", name, "...");
    this.indent += "  ";
};

/**
 * Notification that we're leaving a test scope.
 * @param name the name of the test scope
 */
TermWriter.prototype.exitScope = function(name) {
    this.indent = this.indent.substring(2);
};

/**
 * Display the beginning of a test function execution
 * @param {String} name The name of the test function about to be executed
 */
TermWriter.prototype.writeTestStart = function(name) {
    term.write(this.indent, "+ Running", name, "...");
    return;
};

/**
 * Display a passed test method execution
 * @param {Number} time The time the execution of the test method took
 */
TermWriter.prototype.writeTestPassed = function(time) {
    term.writeln(term.BOLD, " PASSED", term.RESET, "(" + time + " ms)");
    return;
};

/**
 * Display a failed test
 * @param {Object} exception The exception thrown during test method execution
 */
TermWriter.prototype.writeTestFailed = function(exception) {
    term.writeln(term.BOLD, term.WHITE, term.ONRED, " FAILED ");
    exception.message.split(/\n/).forEach(function(line) {
        term.writeln("  ", term.BOLD, term.RED, line);
    });
    if (exception.stackTrace != null) {
        exception.stackTrace.forEach(function(line) {
            term.writeln("  ", term.BOLD, line);
        });
    }
    term.writeln("");
    return;
};

/**
 * Display the summary of a unit test(suite) execution
 * @param {Object} summary The unit test summary
 */
TermWriter.prototype.writeSummary = function(summary) {
    if (summary.testsRun > 0) {
        term.writeln("--------------------------------------------------------------------------------");
        term.writeln("Executed", summary.testsRun, "tests in", summary.time, "ms ");
        term.writeln(term.BOLD, "Passed", summary.passed + ";", "Failed", summary.failures + ";", "Errors", summary.errors + ";");
    } else {
        term.writeln("No tests found");
    }
    return;
};
/**
 * Creates a new EvaluationError instance
 * @class Instances of this class represent an exception thrown when evaluating
 * a test file or a single test function
 * @param {Object} messageOrException Either a message string or the exception
 * thrown when evaluating
 * @returns A newly created EvaluationError instance
 * @constructor
 * @exteds TestException
 */
function EvaluationError(messageOrException) {
    var message = undefined;
    var exception = null;
    var stackTrace = null;
    var fileName = null;
    var lineNumber = -1;

    Object.defineProperty(this, "message", {
        get: function() {
            return message;
        }
    });

    Object.defineProperty(this, "stackTrace", {
        get: function() {
            return stackTrace;
        }
    });

    Object.defineProperty(this, "fileName", {
        get: function() {
            return fileName;
        }
    });

    Object.defineProperty(this, "lineNumber", {
        get: function() {
            return lineNumber;
        }
    });

    /**
     * Main constructor body
     */
    if (messageOrException instanceof Error) {
        exception = messageOrException;
    } else {
        message = messageOrException;
    }

    if (exception != null) {
        if (exception.rhinoException != null) {
            var e = exception.rhinoException;
            message += e.details();
            stackTrace = getStackTrace(e.getStackTrace());
        } else if (exception instanceof Error) {
            message = exception.message;
        }
        if (!stackTrace) {
            // got no stack trace, so add at least filename and line number
            fileName = exception.fileName || null;
            lineNumber = exception.lineNumber || null;
        }
    }
    return this;
};
EvaluationError.prototype = new Error();

/**
 * Executed when called from the command line
 */
if (require.main == module.id) {
    var system = require("system");
    if (system.args.length == 1) {
        term.writeln("Usage: bin/ringo test test/file1 test/file2");
    } else {
        var writer = new TermWriter();
        var failures = 0;
        for (var i=1; i<system.args.length; i+=1) {
            failures += this.run(system.args[i], writer);
        }
        system.exit(failures);
    }
}