text:
<?php

list($prefix, $modules) = $s['d'];

?>
<?php foreach ($modules as $module): ?>
<?php section('module', array($prefix, $module)) ?>
<?php endforeach ?>

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace PhpOffice\PhpWord\Tests\Section;

use PhpOffice\PhpWord\Section\Header;

class HeaderTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructDefault()
    {
        $iVal = rand(1, 1000);
        $oHeader = new Header($iVal);

        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Header', $oHeader);
        $this->assertEquals($oHeader->getHeaderCount(), $iVal);
        $this->assertEquals($oHeader->getType(), Header::AUTO);
    }

    public function testAddText()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addText('text');

        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Text', $element);
        $this->assertCount(1, $oHeader->getElements());
        $this->assertEquals($element->getText(), 'text');
    }

    public function testAddTextNotUTF8()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addText(utf8_decode('ééé'));

        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Text', $element);
        $this->assertCount(1, $oHeader->getElements());
        $this->assertEquals($element->getText(), 'ééé');
    }

    public function testAddTextBreak()
    {
        $oHeader = new Header(1);
        $oHeader->addTextBreak();
        $this->assertCount(1, $oHeader->getElements());
    }

    public function testAddTextBreakWithParams()
    {
        $oHeader = new Header(1);
        $iVal = rand(1, 1000);
        $oHeader->addTextBreak($iVal);
        $this->assertCount($iVal, $oHeader->getElements());
    }

    public function testCreateTextRun()
    {
        $oHeader = new Header(1);
        $element = $oHeader->createTextRun();
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\TextRun', $element);
        $this->assertCount(1, $oHeader->getElements());
    }

    public function testAddTable()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addTable();
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Table', $element);
        $this->assertCount(1, $oHeader->getElements());
    }

    public function testAddImage()
    {
        $src = __DIR__ . "/../_files/images/earth.jpg";
        $oHeader = new Header(1);
        $element = $oHeader->addImage($src);

        $this->assertCount(1, $oHeader->getElements());
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Image', $element);
    }

    public function testAddImageByUrl()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addImage(
            'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'
        );

        $this->assertCount(1, $oHeader->getElements());
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Image', $element);
    }

    public function testAddPreserveText()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addPreserveText('text');

        $this->assertCount(1, $oHeader->getElements());
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Footer\\PreserveText', $element);
    }

    public function testAddPreserveTextNotUTF8()
    {
        $oHeader = new Header(1);
        $element = $oHeader->addPreserveText(utf8_decode('ééé'));

        $this->assertCount(1, $oHeader->getElements());
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Footer\\PreserveText', $element);
        $this->assertEquals($element->getText(), array('ééé'));
    }

    public function testAddWatermark()
    {
        $src = __DIR__ . "/../_files/images/earth.jpg";
        $oHeader = new Header(1);
        $element = $oHeader->addWatermark($src);

        $this->assertCount(1, $oHeader->getElements());
        $this->assertInstanceOf('PhpOffice\\PhpWord\\Section\\Image', $element);
    }

    public function testGetElements()
    {
        $oHeader = new Header(1);

        $this->assertInternalType('array', $oHeader->getElements());
    }

    public function testRelationId()
    {
        $oHeader = new Header(1);

        $iVal = rand(1, 1000);
        $oHeader->setRelationId($iVal);
        $this->assertEquals($oHeader->getRelationId(), $iVal);
    }

    public function testResetType()
    {
        $oHeader = new Header(1);
        $oHeader->firstPage();
        $oHeader->resetType();

        $this->assertEquals($oHeader->getType(), Header::AUTO);
    }

    public function testFirstPage()
    {
        $oHeader = new Header(1);
        $oHeader->firstPage();

        $this->assertEquals($oHeader->getType(), Header::FIRST);
    }

    public function testEvenPage()
    {
        $oHeader = new Header(1);
        $oHeader->evenPage();

        $this->assertEquals($oHeader->getType(), Header::EVEN);
    }
}


text:
package gov.nih.nci.cagrid.testing.system.haste.io;

import java.io.Writer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;

/**
 * This writer prepends every line with the REPORTLINE_PREFIX
 * for later filtering.
 * $Revision: 1.1 $
 */
public class ReportWriter extends Writer {

	/** Text to use for all report-oriented output */
	public static final String REPORTLINE_PREFIX = "[REPORT]:";

	/** Line Break String */
	static String lineSep = System.getProperty("line.separator");

	/** OuputStream to write to */
	OutputStream os;

	/** Flag for first write */
	boolean firstTime;

	/** Buffer for writes with possible line separators at end */
	StringBuffer buffer;

	/**
	 * Create a new ReportWriter to write to an OutputStream.
	 * @param stream the OutputStream to write to.
	 * @throws IllegalArgumentException if stream is null.
	 */
	public ReportWriter(OutputStream stream) {
		if (stream == null) {
			throw new IllegalArgumentException("stream was null");
		}
		os = stream;
		firstTime = true;
		buffer = new StringBuffer();
	}

	/**
	 * Write a portion of an array of characters.  REPORTLINE_PREFIX
	 * will be inserted at beginning of stream and after every BR.
	 * @param cbuf Array of characters.
	 * @param off Offset at which to start writing characters.
	 * @param len Number of characters to write.
	 * @throws IOException if an I/O error occurs.
	 * @throws IllegalArgumentException if cbuf is null.
	 * @throws IndexOutOfBoundsException if the off and len arguments index
	 *         characters outside the bounds of the cbuf array.
	 */
	public void write(char[] cbuf, int off, int len)
		throws IOException, IllegalArgumentException, IndexOutOfBoundsException
	{
		String str = new String(cbuf, off, len);
		write(str);
	}

	/**
	 * Write a String.  REPORTLINE_PREFIX will be inserted at
	 * beginning of stream and after every BR.
	 * @param str String to write.
	 * @throws IOException if an I/O error occurs.
	 * @throws IllegalArgumentException if str is null.
	 */
	public void write(String str) throws IOException {
		if (str == null) {
			throw new IllegalArgumentException("str was null");
		}

		buffer.append(str);

		for (int i=1; i < getLineSep().length(); i++) {
			if ( str.endsWith(getLineSep().substring(0, i)) ) {
				// we don't know for sure if the stream will
				// contain a line break string yet
				return;
			}
		}

		StringBuffer tempBuf = prependLines(buffer.toString());
		buffer = new StringBuffer();

		os.write(tempBuf.toString().getBytes());
	}

	/**
	 * Flushes the underlying output stream.
	 * @throws IOException if an I/O error occurs or called when
	 * buffer is not empty due to undeterminable line break sequence.
	 */
	public void flush() throws IOException {
		if (buffer.length() > 0) {
			throw new IOException("buffer contains undetermined linebreak sequence");
		}
		os.flush();
	}

	/**
	 * Closes the underlying output stream.
	 * @throws IOException if an I/O error occurs.
	 */
	public void close() throws IOException {
		os.close();
	}

	public static String getLineSep() {
		return lineSep;
	}

	/**
	 * Inserts REPORTLINE_PREFIX before all occurences
	 * of BR, and prepends entire string if firstTime
	 * is true.
	 * @param str String to operate on.
	 * @return StringBuffer after search / replace.
	 */
	StringBuffer prependLines(String str) {
		if (firstTime) {
			firstTime = false;
			str = REPORTLINE_PREFIX + str;
		}

		StringBuffer buf = new StringBuffer(str);

		// get first occurence of line break
		int index = buf.toString().indexOf(getLineSep());
		while (index != -1) {
			buf.insert(index + getLineSep().length(), REPORTLINE_PREFIX);
			index = buf.toString().indexOf(getLineSep(), index + 1 + REPORTLINE_PREFIX.length());
		}

		return buf;
	}

}


text:
namespace Ramesoft.Cms.Api.Areas.HelpPage
{
    /// <summary>
    ///     Indicates whether the sample is used for request or response
    /// </summary>
    public enum SampleDirection
    {
        /// <summary>
        ///     The request.
        /// </summary>
        Request = 0,

        /// <summary>
        ///     The response.
        /// </summary>
        Response
    }
}


text:
module Searchlogic
  class Config
    # = Helpers Configuration
    # Provide configuration for searchlogic's rails helpers
    #
    # === Example
    #   Searchlogic::Config.configure do |config|
    #     config.helpers.order_by_link_asc_indicator = "ASC"
    #   end
    class Helpers
      class << self
        # Which hidden fields to automatically include when creating a form with a Searchlogic object. See Searchlogic::Helpers::Form for more info.
        #
        # * <tt>Default:</tt> [:order_by, :order_as, :priority_order_by, :priority_order_as, :per_page]
        # * <tt>Accepts:</tt> Array, nil, false
        def hidden_fields
          @hidden_fields ||= (Searchlogic::Search::Base::SPECIAL_FIND_OPTIONS - [:page, :priority_order])
        end
        attr_writer :hidden_fields

        # Searchlogic does some javascript magic when you use the form helpers with a Searchlogic object. To make configuration easier Searchlogic checks for the existence of Prototype and jQuery and uses the first
        # one it finds. To cut back on the javascript output you can specify your library here.
        #
        # * <tt>Default:</tt> nil
        # * <tt>Accepts:</tt> :prototype or :jquery
        def javascript_library
          @javascript_library
        end
        attr_writer :javascript_library

        # The class name for used in the order_as_link helper
        #
        # * <tt>Default:</tt> "order_as"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def order_as_link_class_name
          return @order_as_link_class_name if defined?(@order_as_link_class_name)
          @order_as_link_class_name = "order_as"
        end
        attr_writer :order_as_link_class_name

        # The class name for used in the order_as_select helper
        #
        # * <tt>Default:</tt> "order_as"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def order_as_select_class_name
          return @order_as_select_class_name if defined?(@order_as_select_class_name)
          @order_as_select_class_name = "order_as"
        end
        attr_writer :order_as_select_class_name

        # The indicator that is used when the sort of a column is ascending
        #
        # * <tt>Default:</tt>  ▲
        # * <tt>Accepts:</tt> String or a Proc.
        #
        # === Examples
        #
        #   config.asc_indicator = "(ASC)"
        #   config.asc_indicator = Proc.new { |template| template.image_tag("asc.jpg") }
        def order_by_link_asc_indicator
          @order_by_link_asc_indicator ||= " ▲"
        end
        attr_writer :order_by_link_asc_indicator

        # The class name for used in the order_by_link helper
        #
        # * <tt>Default:</tt> "order_by"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def order_by_link_class_name
          return @order_by_link_class_name if defined?(@order_by_link_class_name)
          @order_by_link_class_name = "order_by"
        end
        attr_writer :order_by_link_class_name

        # See order_by_link_asc_indicator=
        def order_by_link_desc_indicator
          @order_by_link_desc_indicator ||= " ▼"
        end
        attr_writer :order_by_link_desc_indicator

        # The class name used in order_by_links for the link that it is currently ordering by
        #
        # * <tt>Default:</tt> "# The class name for used in the page_link helper
        #
        # * <tt>Default:</tt> "page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def order_by_links_ordering_by_class_name
          return @order_by_links_ordering_by_class_name if defined?(@order_by_links_ordering_by_class_name)
          @order_by_links_ordering_by_class_name = "ordering_by"
        end
        attr_writer :order_by_links_ordering_by_class_name

        # The class name for used in the order_by_select helper
        #
        # * <tt>Default:</tt> "order_by"
        # * <tt>Accepts:</tt> String
        def order_by_select_class_name
          @order_by_select_class_name ||= "order_by"
        end
        attr_writer :order_by_select_class_name

        # Makes page_links look just like the output of will_paginate.
        #
        # * <tt>Default:</tt> false
        # * <tt>Accepts:</tt> Boolean
        def page_links_act_like_will_paginate
          @page_links_act_like_will_paginate ||= false
        end
        attr_writer :page_links_act_like_will_paginate

        # Convenience methods for determining if page_links_act_like_will_paginate is set to true
        def page_links_act_like_will_paginate?
          page_links_act_like_will_paginate == true
        end

        # The class name for used in the page_link helper
        #
        # * <tt>Default:</tt> "page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_link_class_name
          return @page_link_class_name if defined?(@page_link_class_name)
          @page_link_class_name = "page"
        end
        attr_writer :page_link_class_name

        # The choices used in the per_page_links helper. Works just like per_page_select_choices.
        def per_page_links_choices
          @per_page_links_choices ||= per_page_select_choices
        end
        attr_writer :per_page_links_choices

        # The class that the current page link gets.
        #
        # * <tt>Default:</tt> "current_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_current_page_class_name
          return @page_links_current_page_class_name if defined?(@page_links_current_page_class_name)
          @page_links_current_page_class_name = page_links_act_like_will_paginate? ? "current" : "current_page"
        end
        attr_writer :page_links_current_page_class_name

        # The class that disabled page links get. Including the current page, prev page, next page, first page, and last page.
        #
        # * <tt>Default:</tt> "disabled_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_disabled_class_name
          return @page_links_disabled_class_name if defined?(@page_links_disabled_class_name)
          @page_links_disabled_class_name = page_links_act_like_will_paginate? ? "disabled" : "disabled_page"
        end
        attr_writer :page_links_disabled_class_name

        # Wraps page links in a div
        #
        # * <tt>Default:</tt> false
        # * <tt>Accepts:</tt> Boolean
        def page_links_div_wrapper
          return @page_links_div_wrapper if defined?(@page_links_div_wrapper)
          @page_links_div_wrapper = page_links_act_like_will_paginate?
        end
        attr_writer :page_links_div_wrapper

        # If page_links_div_wrapper is true you can specify a class name here.
        #
        # * <tt>Default:</tt> "pagination"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_div_wrapper_class_name
          return @page_links_div_wrapper_class_name if defined?(@page_links_div_wrapper_class_name)
          @page_links_div_wrapper_class_name = "pagination"
        end
        attr_writer :page_links_div_wrapper_class_name

        # The default for the :first option for the page_links helper.
        #
        # * <tt>Default:</tt> nil
        # * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable
        def page_links_first
          @page_links_first
        end
        attr_writer :page_links_first

        # The default for the :inner_spread option for the page_links helper.
        #
        # * <tt>Default:</tt> 3
        # * <tt>Accepts:</tt> Any integer >= 1, set to nil to show all pages
        def page_links_inner_spread
          @page_links_inner_spread ||= 3
        end
        attr_writer :page_links_inner_spread

        # The class for the first page link
        #
        # * <tt>Default:</tt> "first_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_first_page_class_name
          return @page_links_first_page_class_name if defined?(@page_links_first_page_class_name)
          @page_links_first_page_class_name = "first_page"
        end
        attr_writer :page_links_first_page_class_name

        # The default for the :last option for the page_links helper.
        #
        # * <tt>Default:</tt> nil
        # * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable
        def page_links_last
          @page_links_last
        end
        attr_writer :page_links_last

        # The class for the last page link
        #
        # * <tt>Default:</tt> "last_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_last_page_class_name
          return @page_links_last_page_class_name if defined?(@page_links_last_page_class_name)
          @page_links_last_page_class_name = "last_page"
        end
        attr_writer :page_links_last_page_class_name

        # The default for the :next option for the page_links helper.
        #
        # * <tt>Default:</tt> "Next >"
        # * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable
        def page_links_next
          @page_links_next ||= "Next >"
        end
        attr_writer :page_links_next

        # The class for the next page link
        #
        # * <tt>Default:</tt> "next_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_next_page_class_name
          return @page_links_next_page_class_name if defined?(@page_links_next_page_class_name)
          @page_links_next_page_class_name = "next_page"
        end
        attr_writer :page_links_next_page_class_name

        # The default for the :outer_spread option for the page_links helper.
        #
        # * <tt>Default:</tt> 2
        # * <tt>Accepts:</tt> Any integer >= 1, set to nil to display, 0 to only show the "..." separator
        def page_links_outer_spread
          @page_links_outer_spread ||= 1
        end
        attr_writer :page_links_outer_spread

        # The class for the previous page link
        #
        # * <tt>Default:</tt> "prev_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_links_prev_page_class_name
          return @page_links_prev_page_class_name if defined?(@page_links_prev_page_class_name)
          @page_links_prev_page_class_name = "prev_page"
        end
        attr_writer :page_links_prev_page_class_name

        # The default for the :prev option for the page_links helper.
        #
        # * <tt>Default:</tt> "< Prev"
        # * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable
        def page_links_prev
          @page_links_prev ||= "< Prev"
        end
        attr_writer :page_links_prev

        # The class name for used in the page_seect helper
        #
        # * <tt>Default:</tt> "page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def page_select_class_name
          return @page_select_class_name if defined?(@page_select_class_name)
          @page_select_class_name = "page"
        end
        attr_writer :page_select_class_name

        # The class name for used in the per_page_link helper
        #
        # * <tt>Default:</tt> "per_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def per_page_link_class_name
          return @per_page_link_class_name if defined?(@per_page_link_class_name)
          @per_page_link_class_name = "per_page"
        end
        attr_writer :per_page_link_class_name

        # The choices used in the per_page_select helper
        #
        # * <tt>Default:</tt> [["10 per page", 10], ["25 per page", 25], ["50 per page", 50], ["100 per page", 100], ["150 per page", 150], ["200 per page", 200], ["Show all", nil]]
        # * <tt>Accepts:</tt> Array
        def per_page_select_choices
          return @per_page_select_choices if @per_page_select_choices
          @per_page_select_choices = []
          [10, 25, 50, 100, 150, 200].each { |choice| @per_page_select_choices << ["#{choice} per page", choice] }
          @per_page_select_choices << ["Show all", nil]
        end
        attr_writer :per_page_select_choices

        # The class name for used in the per_page_select helper
        #
        # * <tt>Default:</tt> "per_page"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def per_page_select_class_name
          return @per_page_select_class_name if defined?(@per_page_select_class_name)
          @per_page_select_class_name = "per_page"
        end
        attr_writer :per_page_select_class_name

        # The default value for the :activate_text option for priority_order_by_link
        #
        # * <tt>Default:</tt> "Show %s first"
        # * <tt>Accepts:</tt> String with substitutions, using rubys % method for strings
        def priority_order_by_link_activate_text
          @priority_order_by_link_activate_text ||= "Show %s first"
        end
        attr_writer :priority_order_by_link_activate_text

        # The class name for used in the priority_order_by_link helper
        #
        # * <tt>Default:</tt> "priority_order_by"
        # * <tt>Accepts:</tt> String, set to nil to disable
        def priority_order_by_link_class_name
          return @priority_order_by_link_class_name if defined?(@priority_order_by_link_class_name)
          @priority_order_by_link_class_name = "priority_order_by"
        end
        attr_writer :priority_order_by_link_class_name

        # The default value for the :deactivate_text option for priority_order_by_link
        #
        # * <tt>Default:</tt> "Dont' show %s first"
        # * <tt>Accepts:</tt> String with substitutions, using rubys % method for strings
        def priority_order_by_link_deactivate_text
          @priority_order_by_link_deactivate_text ||= "Don't show %s first"
        end
        attr_writer :priority_order_by_link_deactivate_text
      end
    end
  end
end


text:
u"""
Created on 2015-8-19

@author: cheng.li
"""

import copy

class DataProvider(object):
    def __init__(self):
        self._data = {}

    def set(self, symbol, field, value):
        symbol = symbol.lower()
        field = field.lower()
        if symbol not in self._data:
            self._data[symbol] = {}
        if field in self._data[symbol]:
            raise ValueError("symbol {0}'s field ({1}) can't be assigned again".format(symbol, field))
        self._data[symbol][field] = value

    @property
    def data(self):
        return copy.deepcopy(self._data)

    def clear(self):
        self._data = {}


text:
#include "Gear2D.h"

#define thisTTClass			Gear2D
#define thisTTClassName		"gear.2D"
#define thisTTClassTags		"audio, trajectory, 2D"

TT_AUDIO_CONSTRUCTOR
{
	addAttribute(A,	kTypeFloat64);
	addAttribute(B,	kTypeFloat64);
	addAttribute(C,	kTypeFloat64);

	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Gear2D::~Gear2D()
{
	;
}

//TTErr Gear2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Gear2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 2) {
		TTValue v = 2;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTFloat64 phi,r, temp1;

	temp1 = mA + 1.0/mB;

	for (int i=0; i<vs; i++) {

		phi = inSampleX[i] * kTTPi; // 0 .. 2Pi
		r = temp1 * tanh(mB * sin(mC * phi));
		outSampleX[i] = r * sin(phi);
		outSampleY[i] = r * cos(phi);

	}
return kTTErrNone;
}


text:
Pimwi
=====

Facebook-like


text:
/* $Id$ */

package org.apache.fop.tools.anttasks;

// Ant
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

import org.xml.sax.SAXException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.SimpleLog;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.util.GlobPatternMapper;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopConfParser;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FopFactoryBuilder;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.cli.InputHandler;

/**
 * Wrapper for FOP which allows it to be accessed from within an Ant task.
 * Accepts the inputs:
 *

 *
fofile -> formatting objects file to be transformed

 *
format -> MIME type of the format to generate ex. "application/pdf"

 *
outfile -> output filename

 *
baseDir -> directory to work from

 *
relativebase -> (true | false) control whether to use each FO's
 *      directory as base directory. false uses the baseDir parameter.

 *
userconfig -> file with user configuration (same as the "-c" command
 *      line option)

 *
messagelevel -> (error | warn | info | verbose | debug) level to output
 *      non-error messages

 *
logFiles -> Controls whether the names of the files that are processed
 *      are logged or not

 *

 */
public class Fop extends Task {

    private File foFile;
    private File xmlFile;
    private File xsltFile;
    private String xsltParams;
    private List<FileSet> filesets = new java.util.ArrayList<FileSet>();
    private File outFile;
    private File outDir;
    private String format; //MIME type
    private File baseDir;
    private File userConfig;
    private int messageType = Project.MSG_VERBOSE;
    private boolean logFiles = true;
    private boolean force;
    private boolean relativebase;
    private boolean throwExceptions = true;

    /**
     * Sets the filename for the userconfig.xml.
     * @param userConfig Configuration to use
     */
    public void setUserconfig(File userConfig) {
        this.userConfig = userConfig;
    }

    /**
     * Returns the file for the userconfig.xml.
     * @return the userconfig.xml file
     */
    public File getUserconfig() {
        return this.userConfig;
    }

    /**
     * Sets the input XSL-FO file.
     * @param foFile input XSL-FO file
     */
    public void setFofile(File foFile) {
        this.foFile = foFile;
    }

    /**
     * Gets the input XSL-FO file.
     * @return input XSL-FO file
     */
    public File getFofile() {
        return foFile;
    }

    /**
     * Gets the input XML file.
     * @return the input XML file.
     */
    public File getXmlFile() {
        return xmlFile;
    }

    /**
     * Sets the input XML file.
     * @param xmlFile the input XML file.
     */
    public void setXmlFile(File xmlFile) {
        this.xmlFile = xmlFile;
    }

    /**
     * Gets the input XSLT file.
     * @return the input XSLT file.
     */
    public File getXsltFile() {
        return xsltFile;
    }

    /**
     * Sets the input XSLT file.
     * @param xsltFile the input XSLT file.
     */
    public void setXsltFile(File xsltFile) {
        this.xsltFile = xsltFile;
    }

    /**
     * Gets the XSLT parameters
     * @return the XSLT parameters
     */
    public String getXsltParams() {
        return xsltParams;
    }

    /**
     * Sets the XSLT parameters
     * @param xsltParams the XSLT parameters
     */
    public void setXsltParams(String xsltParams) {
        this.xsltParams = xsltParams;
    }

    /**
     * Adds a set of XSL-FO files (nested fileset attribute).
     * @param set a fileset
     */
    public void addFileset(FileSet set) {
        filesets.add(set);
    }

    /**
     * Returns the current list of filesets.
     * @return the filesets
     */
    public List getFilesets() {
        return this.filesets;
    }

    /**
     * Set whether to include files (external-graphics, instream-foreign-object)
     * from a path relative to the .fo file (true) or the working directory (false, default)
     * only useful for filesets
     *
     * @param relbase true if paths are relative to file.
     */
    public void setRelativebase(boolean relbase) {
        this.relativebase = relbase;
    }

    /**
     * Gets the relative base attribute
     * @return the relative base attribute
     */
    public boolean getRelativebase() {
        return relativebase;
    }

    /**
     * Set whether to check dependencies, or to always generate;
     * optional, default is false.
     *
     * @param force true if always generate.
     */
    public void setForce(boolean force) {
        this.force = force;
    }

    /**
     * Gets the force attribute
     * @return the force attribute
     */
    public boolean getForce() {
        return force;
    }

    /**
     * Sets the output file.
     * @param outFile File to output to
     */
    public void setOutfile(File outFile) {
        this.outFile = outFile;
    }

    /**
     * Gets the output file.
     * @return the output file
     */
    public File getOutfile() {
        return this.outFile;
    }

    /**
     * Sets the output directory.
     * @param outDir Directory to output to
     */
    public void setOutdir(File outDir) {
        this.outDir = outDir;
    }

    /**
     * Gets the output directory.
     * @return the output directory
     */
    public File getOutdir() {
        return this.outDir;
    }

    /**
     * Sets output format (MIME type).
     * @param format the output format
     */
    public void setFormat(String format) {
        this.format = format;
    }

    /**
     * Gets the output format (MIME type).
     * @return the output format
     */
    public String getFormat() {
        return this.format;
    }

    /**
     * Set whether exceptions are thrown.
     * default is false.
     * @param throwExceptions true if exceptions should be thrown
     */
    public void setThrowexceptions(boolean throwExceptions) {
        this.throwExceptions = throwExceptions;
    }

    /**
     * Gets the throw exceptions attribute
     * @return the throw exceptions attribute
     */
    public boolean getThrowexceptions() {
        return this.throwExceptions;
    }

    /**
     * Sets the message level to be used while processing.
     * @param messageLevel (error | warn| info | verbose | debug)
     */
    public void setMessagelevel(String messageLevel) {
        if (messageLevel.equalsIgnoreCase("info")) {
            messageType = Project.MSG_INFO;
        } else if (messageLevel.equalsIgnoreCase("verbose")) {
            messageType = Project.MSG_VERBOSE;
        } else if (messageLevel.equalsIgnoreCase("debug")) {
            messageType = Project.MSG_DEBUG;
        } else if (messageLevel.equalsIgnoreCase("err")
                 || messageLevel.equalsIgnoreCase("error")) {
            messageType = Project.MSG_ERR;
        } else if (messageLevel.equalsIgnoreCase("warn")) {
            messageType = Project.MSG_WARN;
        } else {
            log("messagelevel set to unknown value \"" + messageLevel
                + "\"", Project.MSG_ERR);
            throw new BuildException("unknown messagelevel");
        }
    }

    /**
     * Returns the message type corresponding to Project.MSG_*
     * representing the current message level.
     * @return message type
     * @see org.apache.tools.ant.Project
     */
    public int getMessageType() {
        return messageType;
    }

    /**
     * Sets the base directory for single FO file (non-fileset) usage
     * @param baseDir File to use as a working directory
     */
    public void setBasedir(File baseDir) {
        this.baseDir = baseDir;
    }

    /**
     * Gets the base directory.
     * @return the base directory
     */
    public File getBasedir() {
        return (baseDir != null) ? baseDir : getProject().resolveFile(".");
    }

    /**
     * Controls whether the filenames of the files that are processed are logged
     * or not.
     * @param logFiles True if the feature should be enabled
     */
    public void setLogFiles(boolean logFiles) {
        this.logFiles = logFiles;
    }

    /**
     * Returns True if the filename of each file processed should be logged.
     * @return True if the filenames should be logged.
     */
    public boolean getLogFiles() {
        return this.logFiles;
    }

    /**
     * {@inheritDoc}
     */
    public void execute() throws BuildException {
        int logLevel = SimpleLog.LOG_LEVEL_INFO;
        switch (getMessageType()) {
            case Project.MSG_DEBUG  : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break;
            case Project.MSG_INFO   : logLevel = SimpleLog.LOG_LEVEL_INFO; break;
            case Project.MSG_WARN   : logLevel = SimpleLog.LOG_LEVEL_WARN; break;
            case Project.MSG_ERR    : logLevel = SimpleLog.LOG_LEVEL_ERROR; break;
            case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break;
            default: logLevel = SimpleLog.LOG_LEVEL_INFO;
        }
        SimpleLog logger = new SimpleLog("FOP/Anttask");
        logger.setLevel(logLevel);
        try {
            FOPTaskStarter starter = new FOPTaskStarter(this);
            starter.setLogger(logger);
            starter.run();
        } catch (FOPException ex) {
            throw new BuildException(ex);
        } catch (IOException ioe) {
            throw new BuildException(ioe);
        } catch (SAXException saxex) {
            throw new BuildException(saxex);
        }

    }

}

class FOPTaskStarter {

    // configure fopFactory as desired
    private final FopFactory fopFactory;

    private Fop task;
    private URI baseUri;

    /**
     * logging instance
     */
    protected Log logger;

    /**
     * Sets the Commons-Logging instance for this class
     * @param logger The Commons-Logging instance
     */
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    /**
     * Returns the Commons-Logging instance for this class
     * @return  The Commons-Logging instance
     */
    protected Log getLogger() {
        return logger;
    }

    FOPTaskStarter(Fop task) throws SAXException, IOException {
        this.task = task;
        //Set base directory
        if (task.getBasedir() != null) {
            this.baseUri = task.getBasedir().toURI();
        } else {
            if (task.getFofile() != null) {
                this.baseUri = task.getFofile().getParentFile().toURI();
            }
        }
        if (task.getUserconfig() != null) {
            FopFactoryBuilder confBuilder = new FopConfParser(
                    task.getUserconfig()).getFopFactoryBuilder();
            confBuilder.setBaseURI(baseUri);
            fopFactory = confBuilder.build();
        } else {
            fopFactory = FopFactory.newInstance(baseUri);
        }
    }

    private static final String[][] SHORT_NAMES = {
        {"pdf",  MimeConstants.MIME_PDF},
        {"ps",   MimeConstants.MIME_POSTSCRIPT},
        {"mif",  MimeConstants.MIME_MIF},
        {"rtf",  MimeConstants.MIME_RTF},
        {"pcl",  MimeConstants.MIME_PCL},
        {"txt",  MimeConstants.MIME_PLAIN_TEXT},
        {"at",   MimeConstants.MIME_FOP_AREA_TREE},
        {"xml",  MimeConstants.MIME_FOP_AREA_TREE},
        {"tiff", MimeConstants.MIME_TIFF},
        {"tif",  MimeConstants.MIME_TIFF},
        {"png",  MimeConstants.MIME_PNG},
        {"afp",  MimeConstants.MIME_AFP}
    };

    private String normalizeOutputFormat(String format) {
        if (format == null) {
            return MimeConstants.MIME_PDF;
        }
        for (String[] shortName : SHORT_NAMES) {
            if (shortName[0].equals(format)) {
                return shortName[1];
            }
        }
        return format; //no change
    }

    private static final String[][] EXTENSIONS = {
        {MimeConstants.MIME_FOP_AREA_TREE,   ".at.xml"},
        {MimeConstants.MIME_FOP_AWT_PREVIEW, null},
        {MimeConstants.MIME_FOP_PRINT,       null},
        {MimeConstants.MIME_PDF,             ".pdf"},
        {MimeConstants.MIME_POSTSCRIPT,      ".ps"},
        {MimeConstants.MIME_PCL,             ".pcl"},
        {MimeConstants.MIME_PCL_ALT,         ".pcl"},
        {MimeConstants.MIME_PLAIN_TEXT,      ".txt"},
        {MimeConstants.MIME_RTF,             ".rtf"},
        {MimeConstants.MIME_RTF_ALT1,        ".rtf"},
        {MimeConstants.MIME_RTF_ALT2,        ".rtf"},
        {MimeConstants.MIME_MIF,             ".mif"},
        {MimeConstants.MIME_SVG,             ".svg"},
        {MimeConstants.MIME_PNG,             ".png"},
        {MimeConstants.MIME_JPEG,            ".jpg"},
        {MimeConstants.MIME_TIFF,            ".tif"},
        {MimeConstants.MIME_AFP,             ".afp"},
        {MimeConstants.MIME_AFP_ALT,         ".afp"},
        {MimeConstants.MIME_XSL_FO,          ".fo"}
    };

    private String determineExtension(String outputFormat) {
        for (String[] extension : EXTENSIONS) {
            if (extension[0].equals(outputFormat)) {
                String ext = extension[1];
                if (ext == null) {
                    throw new RuntimeException("Output format '"
                            + outputFormat + "' does not produce a file.");
                } else {
                    return ext;
                }
            }
        }
        return ".unk"; //unknown
    }

    private File replaceExtension(File file, String expectedExt,
                                  String newExt) {
        String name = file.getName();
        if (name.toLowerCase().endsWith(expectedExt)) {
            name = name.substring(0, name.length() - expectedExt.length());
        }
        name = name.concat(newExt);
        return new File(file.getParentFile(), name);
    }

    public void run() throws FOPException {
        task.log("Using base URI: " + baseUri, Project.MSG_DEBUG);

        String outputFormat = normalizeOutputFormat(task.getFormat());
        String newExtension = determineExtension(outputFormat);

        // actioncount = # of fofiles actually processed through FOP
        int actioncount = 0;
        // skippedcount = # of fofiles which haven't changed (force = "false")
        int skippedcount = 0;

        // deal with single source file
        if (task.getFofile() != null) {
            if (task.getFofile().exists()) {
                File outf = task.getOutfile();
                if (outf == null) {
                    throw new BuildException("outfile is required when fofile is used");
                }
                if (task.getOutdir() != null) {
                    outf = new File(task.getOutdir(), outf.getName());
                }
                // Render if "force" flag is set OR
                // OR output file doesn't exist OR
                // output file is older than input file
                if (task.getForce() || !outf.exists()
                    || (task.getFofile().lastModified() > outf.lastModified())) {
                    render(task.getFofile(), outf, outputFormat);
                    actioncount++;
                } else if (outf.exists()
                        && (task.getFofile().lastModified() <= outf.lastModified())) {
                    skippedcount++;
                }
            }
        } else if (task.getXmlFile() != null && task.getXsltFile() != null) {
            if (task.getXmlFile().exists() && task.getXsltFile().exists()) {
                File outf = task.getOutfile();
                if (outf == null) {
                    throw new BuildException("outfile is required when fofile is used");
                }
                if (task.getOutdir() != null) {
                    outf = new File(task.getOutdir(), outf.getName());
                }
                // Render if "force" flag is set OR
                // OR output file doesn't exist OR
                // output file is older than input file
                if (task.getForce() || !outf.exists()
                        || (task.getXmlFile().lastModified() > outf.lastModified()
                        || task.getXsltFile().lastModified() > outf.lastModified())) {
                    render(task.getXmlFile(), task.getXsltFile(), outf, outputFormat);
                    actioncount++;
                } else if (outf.exists()
                        && (task.getXmlFile().lastModified() <= outf.lastModified()
                            || task.getXsltFile().lastModified() <= outf.lastModified())) {
                    skippedcount++;
                }
            }
        }

        GlobPatternMapper mapper = new GlobPatternMapper();

        String inputExtension = ".fo";
        File xsltFile = task.getXsltFile();
        if (xsltFile != null) {
            inputExtension = ".xml";
        }
        mapper.setFrom("*" + inputExtension);
        mapper.setTo("*" + newExtension);

        // deal with the filesets
        for (int i = 0; i < task.getFilesets().size(); i++) {
            FileSet fs = (FileSet) task.getFilesets().get(i);
            DirectoryScanner ds = fs.getDirectoryScanner(task.getProject());
            String[] files = ds.getIncludedFiles();

            for (String file : files) {
                File f = new File(fs.getDir(task.getProject()), file);

                File outf = null;
                if (task.getOutdir() != null && file.endsWith(inputExtension)) {
                    String[] sa = mapper.mapFileName(file);
                    outf = new File(task.getOutdir(), sa[0]);
                } else {
                    outf = replaceExtension(f, inputExtension, newExtension);
                    if (task.getOutdir() != null) {
                        outf = new File(task.getOutdir(), outf.getName());
                    }
                }
                File dir = outf.getParentFile();
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    if (task.getRelativebase()) {
                        this.baseUri = f.getParentFile().toURI();
                    }
                    if (this.baseUri == null) {
                        this.baseUri = fs.getDir(task.getProject()).toURI();
                    }

                } catch (Exception e) {
                    task.log("Error setting base URL", Project.MSG_DEBUG);
                }

                // Render if "force" flag is set OR
                // OR output file doesn't exist OR
                // output file is older than input file
                if (task.getForce() || !outf.exists()
                        || (f.lastModified() > outf.lastModified())) {
                    if (xsltFile != null) {
                        render(f, xsltFile, outf, outputFormat);
                    } else {
                        render(f, outf, outputFormat);
                    }
                    actioncount++;
                } else if (outf.exists() && (f.lastModified() <= outf.lastModified())) {
                    skippedcount++;
                }
            }
        }

        if (actioncount + skippedcount == 0) {
            task.log("No files processed. No files were selected by the filesets "
                + "and no fofile was set." , Project.MSG_WARN);
        } else if (skippedcount > 0) {
            task.log(skippedcount + " xslfo file(s) skipped (no change found"
                + " since last generation; set force=\"true\" to override)."
                , Project.MSG_INFO);
        }
    }

    private void renderInputHandler(InputHandler inputHandler, File outFile, String outputFormat)
            throws Exception {
        OutputStream out = null;
        try {
            out = new java.io.FileOutputStream(outFile);
            out = new BufferedOutputStream(out);
        } catch (Exception ex) {
            throw new BuildException("Failed to open " + outFile, ex);
        }
        boolean success = false;
        try {
            FOUserAgent userAgent = fopFactory.newFOUserAgent();
            inputHandler.renderTo(userAgent, outputFormat, out);
            success = true;
        } catch (Exception ex) {
            if (task.getThrowexceptions()) {
                throw new BuildException(ex);
            }
            throw ex;
        } finally {
            try {
                out.close();
            } catch (IOException ioe) {
                logger.error("Error closing output file", ioe);
            }
            if (!success) {
                outFile.delete();
            }
        }
    }

    private void render(File foFile, File outFile,
                        String outputFormat) throws FOPException {
        InputHandler inputHandler = new InputHandler(foFile);
        try {
            renderInputHandler(inputHandler, outFile, outputFormat);
        } catch (Exception ex) {
            logger.error("Error rendering fo file: " + foFile, ex);
        }
        if (task.getLogFiles()) {
            task.log(foFile + " -> " + outFile, Project.MSG_INFO);
        }
    }

    private void render(File xmlFile, File xsltFile, File outFile, String outputFormat) {
        //TODO: implement support for XSLT params
        InputHandler inputHandler = new InputHandler(xmlFile, xsltFile, null);
        try {
            renderInputHandler(inputHandler, outFile, outputFormat);
        } catch (Exception ex) {
            logger.error("Error rendering xml/xslt files: "
                         + xmlFile + ", " + xsltFile, ex);
        }
        if (task.getLogFiles()) {
            task.log("xml: " + xmlFile + ", xslt: "
                     + xsltFile + " -> " + outFile, Project.MSG_INFO);
        }
    }
}


text:
package com.github.f1xman.movifier2.domain.movie;

public class GenericSearchDataFormatter implements SearchDataFormatter {

    @Override
    public String format(String originalTitle, String year) {
        return String.format("%s %s", originalTitle, year);
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Guardian extends SQ_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->library('Guardian_library');
	}

	public function get() {
		$filters = ($this->input->post('filters')) ? $this->input->post('filters') : array();
		$fields = ($this->input->post('fields')) ? $this->input->post('fields') : array();
		$order_by = ($this->input->post('order_by')) ? $this->input->post('order_by') : array();
		$limit = ($this->input->post('limit')) ? $this->input->post('limit') : null;
		$offset = ($this->input->post('offset')) ? $this->input->post('offset') : null;
		$modules = ($this->input->post('modules')) ? $this->input->post('modules') : array();

		$guardians = $this->guardian_library->get($filters, $fields, $order_by, $limit, $offset, $modules);
		$this->setResponseElement('success', true);
		$this->setResponseElement('guardians', $guardians);
		$this->sendResponse();
	}

	public function add() {
		$guardian_data = $this->input->post('guardian_data');
		if ($guardian_id = $this->guardian_library->add($guardian_data)) {
			$this->setResponseElement('guardian_id', $guardian_id);
		} else {
			$this->setResponseElement('guardian_id', null);
		}
		$this->sendResponse();
	}

	public function update() {
		$guardian_id = $this->input->post('guardian_id');
		$guardian_data = $this->input->post('guardian_data');
		$success = $this->guardian_library->update($guardian_id, $guardian_data);
		$this->setResponseElement('success', $success);
		$this->sendResponse();
	}

	public function verifyEmail() {
		$student_id = $this->input->post('student_id');
		$email = $this->input->post('email');
		$success_obj = $this->guardian_library->verifyEmail($student_id, $email);
		$this->setResponseElement('email_available', $success_obj['email_available']);
		$this->setResponseElement('guardian', $success_obj['guardian']);
		$this->setResponseElement('guardian_exist', $success_obj['guardian_exist']);
		$this->sendResponse();
	}
}


text:
layout: page
title: Wagner Electronics Trade Fair
date: 2016-05-24
author: Nicole Bridges
tags: weekly links, java
status: published
summary: Ut lacinia mattis lorem eu feugiat. Donec id.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 06/07/2016
  endDate: 06/12/2016
  ctyhocn: MKCMRHX
  groupCode: WETF
published: true
---
Quisque ac feugiat ipsum. Morbi porttitor sit amet odio maximus rhoncus. Morbi a felis sed velit malesuada tempor ut nec leo. Mauris cursus posuere scelerisque. Maecenas et magna lectus. Fusce ac varius dolor. Nam eget justo convallis, auctor sem sit amet, tempor tellus. Suspendisse elit augue, ultricies in mattis et, tempor in elit. Donec consequat ex nec dictum pharetra. Nullam at justo ipsum. Integer egestas ligula ac turpis fermentum euismod. Integer imperdiet vel dolor pretium pharetra. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

* Donec sit amet libero at nunc tincidunt tristique nec sit amet dui
* Sed eleifend orci sed nibh consequat, a rutrum est tristique
* Nulla varius felis vitae lacus facilisis ullamcorper.

Vestibulum at ullamcorper sapien. Ut ac dignissim justo, eu posuere lacus. Praesent nec fringilla neque, ac feugiat nunc. Aenean venenatis dapibus ligula quis vestibulum. Cras enim magna, commodo sed congue eget, gravida non risus. Nunc porta justo et ultricies ullamcorper. Aliquam erat volutpat. Sed tempus diam eu ante congue vestibulum. Nunc vitae scelerisque metus, quis pharetra sem. Nulla molestie in dui sed sagittis. Duis vel ante pharetra, sodales lectus ac, faucibus quam. Pellentesque eu quam eu dolor laoreet porta. Donec sed eleifend lectus. Duis sodales velit nec erat facilisis cursus. Vivamus ac posuere lacus.


text:
package org.apache.nifi.lookup;

import java.io.IOException;
import java.util.Collections;
import java.util.Optional;

import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

public class TestCSVRecordLookupService {

    private final static Optional<Record> EMPTY_RECORD = Optional.empty();

    @Test
    public void testSimpleCsvFileLookupService() throws InitializationException, IOException, LookupFailureException {
        final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
        final CSVRecordLookupService service = new CSVRecordLookupService();

        runner.addControllerService("csv-file-lookup-service", service);
        runner.setProperty(service, CSVRecordLookupService.CSV_FILE, "src/test/resources/test.csv");
        runner.setProperty(service, CSVRecordLookupService.CSV_FORMAT, "RFC4180");
        runner.setProperty(service, CSVRecordLookupService.LOOKUP_KEY_COLUMN, "key");
        runner.enableControllerService(service);
        runner.assertValid(service);

        final CSVRecordLookupService lookupService =
                (CSVRecordLookupService) runner.getProcessContext()
                        .getControllerServiceLookup()
                        .getControllerService("csv-file-lookup-service");

        assertThat(lookupService, instanceOf(LookupService.class));

        final Optional<Record> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1"));
        assertEquals("this is property 1", property1.get().getAsString("value"));
        assertEquals("2017-04-01", property1.get().getAsString("created_at"));

        final Optional<Record> property2 = lookupService.lookup(Collections.singletonMap("key", "property.2"));
        assertEquals("this is property 2", property2.get().getAsString("value"));
        assertEquals("2017-04-02", property2.get().getAsString("created_at"));

        final Optional<Record> property3 = lookupService.lookup(Collections.singletonMap("key", "property.3"));
        assertEquals(EMPTY_RECORD, property3);
    }

}


text:
package __TOP_LEVEL_PACKAGE__.__SEGMENT_PACKAGE__;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.http.client.Response;

/**
 * An event posted when an authentication failure is detected.
 */
public class AccountAuthenticationFailureEvent extends GwtEvent<AccountAuthenticationFailureEvent.Handler> {

    /**
     * Implemented by handlers of this type of event.
     */
    public interface Handler extends EventHandler {
        /**
         * Called when a {@link AccountAuthenticationFailureEvent} is fired.
         *
         * @param requestEvent a {@link AccountAuthenticationFailureEvent} instance
         */
        void onAuthFailure(AccountAuthenticationFailureEvent requestEvent);
    }

    private static final Type<Handler> TYPE = new Type<Handler>();

    /**
     * Register a {@link AccountAuthenticationFailureEvent.Handler} on an {@link EventBus}.
     *
     * @param eventBus the {@link EventBus}
     * @param handler  a {@link AccountAuthenticationFailureEvent.Handler}
     * @return a {@link HandlerRegistration} instance
     */
    public static HandlerRegistration register(EventBus eventBus, AccountAuthenticationFailureEvent.Handler handler) {
        return eventBus.addHandler(TYPE, handler);
    }

    /**
     * Will only be non-null if this is an event of type {@link State#RECEIVED},
     * and the RPC was successful.
     */
    private final String loginUrl;

    /**
     * Constructs a new @{link RequestEvent}.
     *
     * @param state    a {@link State} instance
     * @param response a {@link Response} instance
     */
    public AccountAuthenticationFailureEvent(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    public GwtEvent.Type<Handler> getAssociatedType() {
        return TYPE;
    }

    /**
     * Returns the URL the user can visit to reauthenticate.
     *
     * @return a {@link Response} instance
     */
    public String getLoginUrl() {
        return loginUrl;
    }

    @Override
    protected void dispatch(Handler handler) {
        handler.onAuthFailure(this);
    }
}


text:
module jasper.core {
    export interface IValueProvider {
        register(name: string, value: any);
    }

    export class ValueProvider implements IValueProvider, ng.IServiceProvider {

        static $inject = ['$provide'];

        constructor(private provide: any) {

        }

        register(name: string, value: any){
            this.provide.value(name, value);
        }

        $get() {
            return this;
        }
    }
}


text:
package org.keycloak.authorization.store;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.Resource;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.model.Scope;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;

/**
 * A {@link PolicyStore} is responsible to manage the persistence of {@link Policy} instances.
 *
 * @author Pedro Igor
 */
public interface PolicyStore {

    /**
     * Creates a new {@link Policy} instance. The new instance is not necessarily persisted though, which may require
     * a call to the {#save} method to actually make it persistent.
     *
     * @param resourceServer the resource server to which this policy belongs. Cannot be {@code null}.
     * @param representation the policy representation
     * @return a new instance of {@link Policy}
     */
    Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation);

    /**
     * Deletes a policy from the underlying persistence mechanism.
     *
     * @param realm the realm that the removed policy belongs to. Cannot be {@code null}
     * @param id the id of the policy to delete
     */
    void delete(RealmModel realm, String id);

    /**
     * Returns a {@link Policy} with the given id
     *
     *
     * @param realm the realm. Cannot be {@code null}.
     * @param resourceServer the resource server. Ignored if {@code null}.
     * @param id the identifier of the policy
     * @return a policy with the given identifier.
     */
    Policy findById(RealmModel realm, ResourceServer resourceServer, String id);

    /**
     * Returns a {@link Policy} with the given name
     *
     * @param resourceServer the resource server. Cannot be {@code null}
     * @param name the name of the policy
     * @return a policy with the given name or {@code null} if no such policy exists.
     */
    Policy findByName(ResourceServer resourceServer, String name);

    /**
     * Returns a list of {@link Policy} associated with the {@link ResourceServer}
     *
     * @param resourceServer the resource server. Cannot be {@code null}.
     * @return a list of policies that belong to the given resource server
     */
    List<Policy> findByResourceServer(ResourceServer resourceServer);

    /**
     * Returns a list of {@link Policy} associated with a {@link ResourceServer} with the given resourceServerId.
     *
     *
     * @param realm the realm. Cannot be {@code null}.
     * @param resourceServer the identifier of a resource server. Ignored if {@code null}.
     * @param attributes a map holding the attributes that will be used as a filter; possible filter options are given by {@link Policy.FilterOption}
     * @param firstResult first result to return. Ignored if negative or {@code null}.
     * @param maxResults maximum number of results to return. Ignored if negative or {@code null}.
     * @return a list of policies that belong to the given resource server
     *
     * @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map
     */
    List<Policy> find(RealmModel realm, ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults);

    /**
     * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Resource}
     *
     * @param resourceServer the resource server. Cannot be {@code null}.
     * @param resource the resource. Cannot be {@code null}.
     * @return a list of policies associated with the given resource
     */
    default List<Policy> findByResource(ResourceServer resourceServer, Resource resource) {
        List<Policy> result = new LinkedList<>();

        findByResource(resourceServer, resource, result::add);

        return result;
    }

    /**
     * Searches for all policies associated with the {@link org.keycloak.authorization.model.Resource} and passes the result to the {@code consumer}
     *
     * @param resourceServer the resourceServer. Cannot be {@code null}.
     * @param resource the resource. Cannot be {@code null}.
     * @param consumer consumer of policies resulted from the search
     */
    void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer);

    /**
     * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.ResourceServer} with the given type.
     *
     * @param resourceServer the resource server id. Cannot be {@code null}.
     * @param resourceType the type of a resource
     * @return a list of policies associated with the given resource type
     */
    default List<Policy> findByResourceType(ResourceServer resourceServer, String resourceType) {
        List<Policy> result = new LinkedList<>();

        findByResourceType(resourceServer, resourceType, result::add);

        return result;
    }

    /**
     * Searches for policies associated with a {@link org.keycloak.authorization.model.ResourceServer} and passes the result to the consumer
     *
     * @param resourceServer the resourceServer. Cannot be {@code null}.
     * @param type the type of a resource
     * @param policyConsumer consumer of policies resulted from the search
     */
    void findByResourceType(ResourceServer resourceServer, String type, Consumer<Policy> policyConsumer);

    /**
     * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} within the given scope.
     *
     * @param resourceServer the resource server. Cannot be {@code null}.
     * @param scopes the scopes
     * @return a list of policies associated with the given scopes
     */
    List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes);

    /**
     * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} with the given resource and scopes.
     *
     * @param resourceServer the resource server. Cannot be {@code null}.
     * @param resource the resource. Ignored if {@code null}.
     * @param scopes the scopes
     * @return a list of policies associated with the given scopes
     */
    default List<Policy> findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes) {
        List<Policy> result = new LinkedList<>();

        findByScopes(resourceServer, resource, scopes, result::add);

        return result;
    }

    /**
     * Effectively the same method as {@link #findByScopes(ResourceServer, Resource, List)}, however in the end
     * the {@code consumer} is fed with the result.
     *
     */
    void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer);

    /**
     * Returns a list of {@link Policy} with the given type.
     *
     * @param resourceServer the resource server id. Cannot be {@code null}.
     * @param type the type of the policy
     * @return a list of policies with the given type
     */
    List<Policy> findByType(ResourceServer resourceServer, String type);

    /**
     * Returns a list of {@link Policy} that depends on another policy with the given id.
     *
     * @param resourceServer the resource server
     * @param id the id of the policy to query its dependents
     * @return a list of policies that depends on the a policy with the given identifier
     */
    List<Policy> findDependentPolicies(ResourceServer resourceServer, String id);
}


text:
using System;

namespace MatterHackers.Agg.Tests
{
	public class RunTest
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("This is the test running exe that you can use when \nthere is a problem with a test.\n");

			// Run any test that needs debuging
			Vector3Tests test1 = new Vector3Tests();
			test1.DotProduct();

			LionRenderTest lionTest = new LionRenderTest();
			lionTest.CompareToLionTGA();

			Console.Write("There were no unhandled exceptions.\n\nPress any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}


text:
package org.santux.learn.ws.ejb.dto;

import javax.xml.bind.annotation.XmlType;

/**
 *
 * @author santos
 */
@XmlType(namespace = "www.santux.org/escribe/")
public class EscribeSalidaDTO {

    private String escribeL;
    private String escribePf;
    private String escribePa;

    public String getEscribeL() {
        return escribeL;
    }

    public void setEscribeL(String escribeL) {
        this.escribeL = escribeL;
    }

    public String getEscribePf() {
        return escribePf;
    }

    public void setEscribePf(String escribePf) {
        this.escribePf = escribePf;
    }

    public String getEscribePa() {
        return escribePa;
    }

    public void setEscribePa(String escribePa) {
        this.escribePa = escribePa;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:orientation="vertical">

    <RadioGroup android:id="@+id/sf__accounts_group"
        style="@style/SalesforceSDK.AccountSwitcher.List" />

    <Button android:id="@+id/sf__switcher_apply_button"
        android:text="@string/sf__switch_account"
        style="@style/SalesforceSDK.AccountSwitcher.Button.Apply"
        android:onClick="switchToExistingAccount" />

    <Button android:id="@+id/sf__add_account_button"
        android:text="@string/sf__add_new_account"
        style="@style/SalesforceSDK.AccountSwitcher.Button.AddAccount"
        android:onClick="switchToNewAccount" />
</LinearLayout>
<!-- From: file:/Users/kchitalia/repo/SalesforceMobileSDK-Android/libs/SalesforceSDK/res/layout/sf__account_switcher.xml --><!-- From: file:/Users/kchitalia/repo/SalesforceMobileSDK-Android/libs/SmartStore/build/intermediates/exploded-aar/com.salesforce.androidsdk/SalesforceSDK/unspecified/res/layout/sf__account_switcher.xml -->


text:
enum NAVITEMTYPES
{
    navsun,
    navplanet,
    navplayer,
    navcurrentplayer,
    navstation,
    navfighter,
    navcapship,
    navmissile,
    navasteroid,
    navnebula,
    navjump,
    navambiguous
};

#define navsunsize 0.03
#define navplanetsize 0.02
#define navplayersize 0.01
#define navcurrentplayersize 0.01
#define navstationsize 0.015
#define navfightersize 0.01
#define navcapshipsize 0.0125
#define navmissilesize 0.005
#define navasteroidsize 0.015
#define navnebulasize 0.03
#define navjumpsize 0.0125
#define navambiguoussize 0.01

#endif


text:
//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "component/endpoint_component.h"
#include "component/search/search_component.h"
#include "component/status/status_component.h"
#include "delegate/search/search_weight_delegate.h"
#include "entity/entity.h"
#include "font/font_awesome.h"
#include "utility/value.h"

Q_DECLARE_METATYPE(eja::entity::ptr);

namespace eja
{
	void search_weight_delegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex &index) const
	{
		QRect rect(option.rect.left() + offset::text, option.rect.top(), option.rect.width() - offset::text, option.rect.height());
		editor->setGeometry(rect);
	}

	QSize search_weight_delegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
	{
		// Data
		auto variant = index.data(Qt::EditRole);
		QString str = variant.toString();

		// Size
		QFontMetrics metrics(option.font);
		QRect rect = metrics.boundingRect(str);
		rect.setWidth(rect.width() + offset::text + offset::padding);

		return rect.size();
	}

	void search_weight_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
	{
		QStyledItemDelegate::paint(painter, option, index);

		if (option.state & QStyle::State_Enabled)
		{
			// Entity
			auto variant = index.data(Qt::DisplayRole);
			const auto entity = variant.value<entity::ptr>();
			if (!entity)
				return;

			painter->save();
			painter->setRenderHint(QPainter::Antialiasing, true);

			// Weight
			const auto search = entity->get<search_component>();
			const auto weight = QString("%1").arg(search->get_weight());

			variant = index.data(Qt::EditRole);
			const auto swarm_max = variant.toFloat();
			const auto ratio = ((search->get_swarm() * search->get_weight()) / swarm_max);

			auto color = option.palette.color(QPalette::WindowText);
			painter->setBrush(color);

			QColor outline = QColor(color.red(), color.green(), color.blue(), color.alpha() >> 1);
			painter->setPen(outline);

			const auto swarm_diameter = offset::circle * ratio;
			const auto left_padding = (option.rect.width() >> 1) - (swarm_diameter / 2.0);
			const auto top_padding = (offset::circle - swarm_diameter) / 2;
			QRect rect(option.rect.left() + left_padding, option.rect.top() + offset::top + top_padding, swarm_diameter, swarm_diameter);
			painter->drawEllipse(rect);

			// Font Awesome Version (not as awesome)
			/*QFont font(demonsaw::font_awesome);
			font.setPixelSize(offset::circle * ratio);
			painter->setFont(font);

			painter->drawText(option.rect, Qt::TextSingleLine | Qt::AlignCenter, QString(fa::circle));*/

			painter->restore();
		}
	}
}


text:
import withMediaControl from 'EditorWidgets/withMedia/withMediaControl';

const FileControl = withMediaControl();

export default FileControl;


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Sql;

namespace Azure.ResourceManager.Sql.Models
{
    /// <summary> A list of short term retention policies. </summary>
    internal partial class BackupShortTermRetentionPolicyListResult
    {
        /// <summary> Initializes a new instance of BackupShortTermRetentionPolicyListResult. </summary>
        internal BackupShortTermRetentionPolicyListResult()
        {
            Value = new ChangeTrackingList<BackupShortTermRetentionPolicyData>();
        }

        /// <summary> Initializes a new instance of BackupShortTermRetentionPolicyListResult. </summary>
        /// <param name="value"> Array of results. </param>
        /// <param name="nextLink"> Link to retrieve next page of results. </param>
        internal BackupShortTermRetentionPolicyListResult(IReadOnlyList<BackupShortTermRetentionPolicyData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Array of results. </summary>
        public IReadOnlyList<BackupShortTermRetentionPolicyData> Value { get; }
        /// <summary> Link to retrieve next page of results. </summary>
        public string NextLink { get; }
    }
}


text:
package sql.tpce.tpcedef.input;

import java.math.BigDecimal;

import sql.tpce.tpcedef.TPCETxnInput;

public class MarketFeedTxnInput implements TPCETxnInput {
  private static final long serialVersionUID = 100020001L;

  private BigDecimal[] price_quotes;
  private String status_submitted;
  private String[] symbols;
  private int[] trade_qty;
  private String type_limit_buy;
  private String type_limit_sell;
  private String type_stop_loss;

  public BigDecimal[] getPriceQuotes(){
    return price_quotes;
  }

  public String getStatusSubmitted(){
    return status_submitted;
  }

  public String[] getSymbol(){
    return symbols;
  }

  public int[] getTradeQty() {
    return trade_qty;
  }

  public String getLimitBuy(){
    return type_limit_buy;
  }

  public String getLimitSell(){
    return type_limit_sell;
  }

  public String getStopLoss(){
    return type_stop_loss;
  }

  public void setPriceQuotes(BigDecimal[] price_quotes){
    this.price_quotes = price_quotes;
  }

  public void setStatusSubmitted(String status_submitted){
    this.status_submitted = status_submitted;
  }

  public void setSymbol(String[] symbols){
    this.symbols = symbols;
  }

  public void setTradeQty(int[] trade_qty) {
    this.trade_qty = trade_qty;
  }

  public void setLimitBuy(String type_limit_buy){
    this.type_limit_buy = type_limit_buy;
  }

  public void setLimitSell(String type_limit_sell){
    this.type_limit_sell = type_limit_sell;
  }

  public void setStopLoss(String type_stop_loss){
    this.type_stop_loss = type_stop_loss;
  }

}


text:
package org.daylight.pathweaver.service.domain.repository.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.daylight.pathweaver.datamodel.CoreLoadBalancerStatus;
import org.daylight.pathweaver.service.domain.common.Constants;
import org.daylight.pathweaver.service.domain.common.ErrorMessages;
import org.daylight.pathweaver.service.domain.entity.*;
import org.daylight.pathweaver.service.domain.exception.EntityNotFoundException;
import org.daylight.pathweaver.service.domain.exception.ImmutableEntityException;
import org.daylight.pathweaver.service.domain.exception.UnprocessableEntityException;
import org.daylight.pathweaver.service.domain.repository.LoadBalancerRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.*;

@Repository
@Transactional(value="core_transactionManager")
public class LoadBalancerRepositoryImpl implements LoadBalancerRepository {

    private final Log logger = LogFactory.getLog(LoadBalancerRepositoryImpl.class);
    @PersistenceContext(unitName = "loadbalancing")
    private EntityManager entityManager;

    @Override
    public LoadBalancer getById(Integer id) throws EntityNotFoundException {
        LoadBalancer loadBalancer = entityManager.find(LoadBalancer.class, id);
        if (loadBalancer == null) {
            throw new EntityNotFoundException(ErrorMessages.LB_NOT_FOUND);
        }
        return loadBalancer;
    }

    @Override
    public LoadBalancer getByIdAndAccountId(Integer id, Integer accountId) throws EntityNotFoundException {
        LoadBalancer loadBalancer = getById(id);
        if (!loadBalancer.getAccountId().equals(accountId)) {
            throw new EntityNotFoundException(ErrorMessages.LB_NOT_FOUND);
        }

        return loadBalancer;
    }

    @Override
    public List<LoadBalancer> getByAccountId(Integer accountId) {
        return entityManager.createQuery("SELECT lb FROM LoadBalancer lb WHERE lb.accountId = :accountId")
                .setParameter("accountId", accountId)
                .getResultList();
    }

    @Override
    public LoadBalancer create(LoadBalancer loadBalancer) {

        setLbIdOnChildObjects(loadBalancer);

        final Set<LoadBalancerJoinVip> lbJoinVipsToLink = loadBalancer.getLoadBalancerJoinVipSet();
        loadBalancer.setLoadBalancerJoinVipSet(null);

        Calendar current = Calendar.getInstance();
        loadBalancer.setCreated(current);
        loadBalancer.setUpdated(current);
        loadBalancer = entityManager.merge(loadBalancer);

        Set<LoadBalancerJoinVip> newLbJoinVipSet = new HashSet<LoadBalancerJoinVip>();

        // Now attach loadbalancer to vips
        for (LoadBalancerJoinVip lbJoinVipToLink : lbJoinVipsToLink) {

            lbJoinVipToLink.setLoadBalancer(loadBalancer);
            lbJoinVipToLink = entityManager.merge(lbJoinVipToLink);
            newLbJoinVipSet.add(lbJoinVipToLink);
        }

        loadBalancer.setLoadBalancerJoinVipSet(newLbJoinVipSet);

        return loadBalancer;
    }

    protected void setLbIdOnChildObjects(final LoadBalancer loadBalancer) {
        if (loadBalancer.getNodes() != null) {
            for (Node node : loadBalancer.getNodes()) {
                node.setLoadBalancer(loadBalancer);
            }
        }

        if (loadBalancer.getConnectionThrottle() != null) {
            loadBalancer.getConnectionThrottle().setLoadBalancer(loadBalancer);
        }
        if (loadBalancer.getHealthMonitor() != null) {
            loadBalancer.getHealthMonitor().setLoadBalancer(loadBalancer);
        }
        if (loadBalancer.getSessionPersistence() != null) {
            loadBalancer.getSessionPersistence().setLoadBalancer(loadBalancer);
        }
    }

    @Override
    public LoadBalancer update(LoadBalancer loadBalancer) {
        //final Set<LoadBalancerJoinVip> lbJoinVipsToLink = loadBalancer.getLoadBalancerJoinVipSet();
        //loadBalancer.setLoadBalancerJoinVipSet(null);

        loadBalancer.setUpdated(Calendar.getInstance());
        loadBalancer = entityManager.merge(loadBalancer);

        // Now attach loadbalancer to vips
        /*     for (LoadBalancerJoinVip lbJoinVipToLink : lbJoinVipsToLink) {
            VirtualIp virtualIp = entityManager.find(VirtualIp.class, lbJoinVipToLink.getVirtualIp().getId());
            LoadBalancerJoinVip loadBalancerJoinVip = new LoadBalancerJoinVip(loadBalancer.getPort(), loadBalancer, virtualIp);
            entityManager.merge(loadBalancerJoinVip);
            entityManager.merge(lbJoinVipToLink.getVirtualIp());
        }

        entityManager.flush();*/
        return loadBalancer;
    }

    @Override
    public Integer getNumNonDeletedLoadBalancersForAccount(Integer accountId) {
        Query query = entityManager.createNativeQuery(
                "select count(account_id) from load_balancer where status != 'DELETED' and account_id = :accountId").setParameter("accountId", accountId);

        return ((BigInteger) query.getSingleResult()).intValue();
    }

    public void changeStatus(Integer accountId, Integer loadbalancerId, String newStatus) throws EntityNotFoundException, UnprocessableEntityException, ImmutableEntityException {
        changeStatus(accountId, loadbalancerId, newStatus, false);
    }

    public void changeStatus(Integer accountId, Integer loadbalancerId, String newStatus, boolean allowConcurrentModifications) throws EntityNotFoundException, UnprocessableEntityException, ImmutableEntityException {
        // TODO: Hook up AOP logging here

        String queryString = "from LoadBalancer lb where lb.accountId=:aid and lb.id=:lid";
        Query q = entityManager.createQuery(queryString).setLockMode(LockModeType.PESSIMISTIC_WRITE).
                setParameter("aid", accountId).
                setParameter("lid", loadbalancerId);

        List<LoadBalancer> lbList = q.getResultList();
        if (lbList.size() < 1) {
            throw new EntityNotFoundException(ErrorMessages.LB_NOT_FOUND);
        }

        LoadBalancer lb = lbList.get(0);
        if (lb.getStatus().equals(CoreLoadBalancerStatus.DELETED)) {
            throw new UnprocessableEntityException(ErrorMessages.LB_DELETED);
        }
        final boolean isActive = lb.getStatus().equals(CoreLoadBalancerStatus.ACTIVE);
        final boolean isPendingOrActive = lb.getStatus().equals(CoreLoadBalancerStatus.PENDING_UPDATE) || isActive;
        final boolean isError = lb.getStatus().equals(CoreLoadBalancerStatus.ERROR);

        if (isError  || (allowConcurrentModifications ? isPendingOrActive : isActive)) {
            lb.setStatus(newStatus);
            lb.setUpdated(Calendar.getInstance());
            entityManager.merge(lb);
            return;
        }

        throw new ImmutableEntityException("Load Balancer can not be updated as it is currently being updated.");
    }

    public void updatePortInJoinTable(LoadBalancer lb) {
        String queryString = "from LoadBalancerJoinVip where loadBalancer.id = :lbId";
        Query query = entityManager.createQuery(queryString).setParameter("lbId", lb.getId());
        LoadBalancerJoinVip loadBalancerJoinVip = (LoadBalancerJoinVip) query.getSingleResult();
        loadBalancerJoinVip.setPort(lb.getPort());
        entityManager.merge(loadBalancerJoinVip);
    }

    public boolean canUpdateToNewPort(Integer newPort, Set<LoadBalancerJoinVip> setToCheckAgainst) {
        Set<VirtualIp> vipsToCheckAgainst = new HashSet<VirtualIp>();

        for (LoadBalancerJoinVip loadBalancerJoinVip : setToCheckAgainst) {
            vipsToCheckAgainst.add(loadBalancerJoinVip.getVirtualIp());
        }

        String queryString = "select j from LoadBalancerJoinVip j where j.virtualIp in (:vips)";
        Query query = entityManager.createQuery(queryString).setParameter("vips", vipsToCheckAgainst);

        List<LoadBalancerJoinVip> entriesWithPortsToCheckAgainst = query.getResultList();

        for (LoadBalancerJoinVip entryWithPortToCheckAgainst : entriesWithPortsToCheckAgainst) {
            if (entryWithPortToCheckAgainst.getPort().equals(newPort)) {
                return false;
            }
        }

        return true;
    }

     public boolean testAndSetStatus(Integer accountId, Integer loadbalancerId, String statusToChangeTo, boolean allowConcurrentModifications) throws EntityNotFoundException, UnprocessableEntityException {
        String qStr = "from LoadBalancer lb where lb.accountId=:aid and lb.id=:lid";
        List<LoadBalancer> lbList;
        Query q = entityManager.createQuery(qStr).setLockMode(LockModeType.PESSIMISTIC_WRITE).
                setParameter("aid", accountId).
                setParameter("lid", loadbalancerId);
        lbList = q.getResultList();
        if (lbList.size() < 1) {
            throw new EntityNotFoundException("");
        }

        LoadBalancer lb = lbList.get(0);
        if (lb.getStatus().equals(CoreLoadBalancerStatus.DELETED)) {
            throw new UnprocessableEntityException(Constants.LoadBalancerDeleted);
        }
        final boolean isActive = lb.getStatus().equals(CoreLoadBalancerStatus.ACTIVE);
        final boolean isPendingOrActive = lb.getStatus().equals(CoreLoadBalancerStatus.PENDING_UPDATE) || isActive;

        if(allowConcurrentModifications ? isPendingOrActive : isActive) {
            lb.setStatus(statusToChangeTo);
            lb.setUpdated(Calendar.getInstance());
            entityManager.merge(lb);
            return true;
        }

        return false;
    }

    public LoadBalancer changeStatus(LoadBalancer loadBalancer, String status) throws EntityNotFoundException {
        String qStr = "from LoadBalancer lb where lb.accountId=:aid and lb.id=:lid";
        List<LoadBalancer> lbList;
        Query q = entityManager.createQuery(qStr).setLockMode(LockModeType.PESSIMISTIC_WRITE).
                setParameter("aid", loadBalancer.getAccountId()).
                setParameter("lid", loadBalancer.getId());
        lbList = q.getResultList();
        if (lbList.size() < 1) {
            throw new EntityNotFoundException(ErrorMessages.LB_NOT_FOUND);
        }

        loadBalancer = lbList.get(0);
        loadBalancer.setStatus(status);
        entityManager.persist(loadBalancer);
        return loadBalancer;
    }

    /* Returns only attributes needed for performance reasons */
    public List<LoadBalancer> getLoadBalancersWithStatus(String status) {
        List<Object> loadBalancerTuples;
        List<LoadBalancer> loadBalancers = new ArrayList<LoadBalancer>();

        loadBalancerTuples = entityManager.createNativeQuery("SELECT lb.id, lb.account_id, lb.name FROM load_balancer lb where lb.status = :status")
                .setParameter("status", status)
                .getResultList();

        for (Object loadBalancerTuple : loadBalancerTuples) {
            Object[] row = (Object[]) loadBalancerTuple;
            LoadBalancer lb = new LoadBalancer();
            lb.setId((Integer) row[0]);
            lb.setAccountId((Integer) row[1]);
            lb.setName((String) row[2]);
            loadBalancers.add(lb);
        }

        return loadBalancers;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.javacore</groupId>
    <artifactId>myJavaCore</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>myJavaCore</name>
    <description>myJavaCore</description>
    <packaging>war</packaging>

    <properties>
        <google-collections.version>1.0</google-collections.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>${google-collections.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.8</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
 #include <QtGui>

 #include "window.h"

 int main(int argc, char *argv[])
 {
     Q_INIT_RESOURCE(systray);

     QApplication app(argc, argv);

     if (!QSystemTrayIcon::isSystemTrayAvailable()) {
         QMessageBox::critical(0, QObject::tr("Systray"),
                               QObject::tr("I couldn't detect any system tray "
                                           "on this system."));
         return 1;
     }
     QApplication::setQuitOnLastWindowClosed(false);

     Window window;
     window.show();
     return app.exec();
 }


text:
cask "arduino-ide-nightly" do
  version :latest
  sha256 :no_check

  url "https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_macOS_64bit.dmg"
  name "Arduino IDE"
  desc "Electronics prototyping platform"
  homepage "https://www.arduino.cc/en/software#experimental-software"

  conflicts_with cask: "arduino-ide-beta"

  app "Arduino IDE.app"

  zap trash: [
    "~/Library/Application Support/arduino-ide",
    "~/.arduinoIDE",
  ]
end


text:
<?php

/**
 * PluginLateralMenuPermissions form.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage filter
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id$
 */
abstract class PluginLateralMenuPermissionsFormFilter extends BaseLateralMenuPermissionsFormFilter
{
}


text:
var nextFire = 0;
var fireRate = 150;
var facing = 'left';
var jumpTimer = 0;
var score = 0;
var scoreText;
var timer;
var bugCount = 0;

var playState = {
create: function() {

    this.keyboard = game.input.keyboard;
    timer = game.time.create(false);
    timer.loop(1000, createBug, this);
    timer.start();
    bugCount = 0;
    score = 0;

    game.load.spritesheet('eric', 'assets/eric.png', 32, 48);
    game.load.spritesheet('bug', 'assets/buggy1.png', 32, 32);
    game.load.image('bullet', 'assets/purple_ball.png');
    game.load.bitmapFont('arcadeFont', 'fonts/arcade.png', 'fonts/arcade.fnt');

    this.player = game.add.sprite(32, 32, 'eric');
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.time.desiredFps = 30;
    game.physics.arcade.gravity.y = 250;
    game.physics.enable(this.player, Phaser.Physics.ARCADE);

    //Set how much we want to bounce
    this.player.body.bounce.y = 0.5;
    //turn on collisions with edges of map
    this.player.body.collideWorldBounds = true;
    //set eric's size
    this.player.body.setSize(20, 32, 5, 16);

	//define eric's sprite animation for moving
    this.player.animations.add('left', [0, 1, 2, 3], 10, true);
    this.player.animations.add('turn', [4], 20, true);
    this.player.animations.add('right', [5, 6, 7, 8], 10, true);

	//define a physics group for the bugs we'll be killing
    bugs = game.add.physicsGroup(Phaser.Physics.ARCADE);
    bugs.setAll('body.collideWorldBounds', false);
    bugs.setAll('body.bounce.x', 1);
    bugs.setAll('body.bounce.y', 0);
    bugs.setAll('outOfBoundsKill', true);

	//define a group for the player's bullets
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
	bullets.createMultiple(50, 'bullet');
	bullets.setAll('checkWorldBounds', true);
    bullets.setAll('outOfBoundsKill', true);

	//show the score!
	scoreText = game.add.bitmapText(game.world.centerX, 50, 'arcadeFont', 'Score: 0', 20);

	//keybindings
    cursors = game.input.keyboard.createCursorKeys();
    jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    //dvorak masterrace
    altLeft = game.input.keyboard.addKey(Phaser.Keyboard.A);
    altRight = game.input.keyboard.addKey(Phaser.Keyboard.E);
    altJump = game.input.keyboard.addKey(Phaser.Keyboard.COMMA);
    altaltRight = game.input.keyboard.addKey(Phaser.Keyboard.D);
    altaltJump = game.input.keyboard.addKey(Phaser.Keyboard.W);

    restartButton = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
},

update: function() {

	//player loses the game if they collide with a bug
	game.physics.arcade.collide(this.player, bugs, loseGame, null, this);

	//bug dies if you shoot it
	game.physics.arcade.collide(bullets, bugs, killSprites, null, this);

	//don't keep moving the player unless they are still holding the button down
	this.player.body.velocity.x = 0;

    if (game.input.activePointer.isDown) {
            fire(this.player);
    }

    if (restartButton.isDown) {
            game.state.start('boot');
    }

   if (cursors.left.isDown || altLeft.isDown)
    {
        this.player.body.velocity.x = -150;

        if (facing != 'left')
        {
            this.player.animations.play('left');
            facing = 'left';
        }
    }
	else if (cursors.right.isDown || altRight.isDown || altaltRight.isDown)
    {
        this.player.body.velocity.x = 150;

        if (facing != 'right')
        {
            this.player.animations.play('right');
            facing = 'right';
        }
    }
    else
    {
        if (facing != 'idle')
        {
            this.player.animations.stop();

            if (facing == 'left')
            {
                this.player.frame = 0;
            }
            else
            {
                this.player.frame = 5;
            }
        	this.player.frame = 4;
            facing = 'idle';
        }
    }

	if ((jumpButton.isDown || altJump.isDown || cursors.up.isDown || altaltJump.isDown) && this.player.body.onFloor() && game.time.now > jumpTimer)
    {
        this.player.body.velocity.y = -250;
        jumpTimer = game.time.now + 750;
    }

},

}

function loseGame() {

	game.state.start('lose');

}

function createBug(){

    for (i = 0; i < bugCount; i++) {
        var s = bugs.create(game.rnd.integerInRange(100,700), game.rnd.integerInRange(32, 200), 'bug');
        s.animations.add('spin', [0, 1, 2, 3]);
        s.play('spin', 20, true);
        s.body.velocity.set(game.rnd.integerInRange(-200, 200), game.rnd.integerInRange(-200, 200));
    }
    bugCount++;
}

function killSprites(bullet, bug) {

bullet.kill();
bug.kill();
score++;
scoreText.setText("Score: " + score);
}

function fire(player) {

    if (game.time.now > nextFire && bullets.countDead() > 0)
    {
        nextFire = game.time.now + fireRate;
        var bullet = bullets.getFirstDead();
        bullet.reset(player.x + 16 , player.y );
        bullet.body.allowGravity = false;
        game.physics.arcade.moveToPointer(bullet, 300);
    }

}