text:
<?php

class BatchCompiler extends Base
{
	private $batchId;
	private $source;

	public static $syntax = array(
		// special commands
		'meta' => array(
			'isBlock' => false,
			'needsBlock' => false,
			'minArguments' => 1,
			'arguments' => array('key', 'value'),
			'description' => '',
			'keys' => array(
				'title' 		=> '',
				'description'	=> '',
				'workers'		=> -1,
				'timeout'		=> 600,
				),
			),
		'var' => array(
			'isBlock' => false,
			'needsBlock' => false,
			'minArguments' => 2,
			'arguments' => array('variable', 'value'),
			'description' => 'Sets an internal variable to `<value>`. To use this variable for example in a `set` command, use the following syntax: `set title $titlevar`',
			),
		'set' => array(
			'isBlock' => false,
			'needsBlock' => false,
			'minArguments' => 1,
			'arguments' => array('property', 'value'),
			'description' => 'The `set` command sets a property defined by the `<property>`-argument to the value specified by `<value>`. This property can be used by all further commands and its value will be set until a matching `unset`-command is processed.',
			),
		'unset' => array(
			'isBlock' => false,
			'needsBlock' => false,
			'minArguments' => 1,
			'arguments' => array('property'),
			'description' => 'Unsets the property with the passed `<property>`. If `all` is passed all properties will be unset.',
			),
		'end' => array(
			'isBlock' => false,
			'needsBlock' => false,
			'minArguments' => 1,
			'arguments' => array('block'),
			'description' => 'TODO',
			),

		// blocks
		'step' => array(
			'isBlock' => true,
			'needsBlock' => false,
			'minArguments' => 0,
			'arguments' => array('name'),
			'properties' => array(
				'delay' 		 => array(
					'default' => 0,
					'values' => 'number of seconds',
					'description' => 'Todo'),
				'skipvalidation' => array(
					'default' => false,
					'values' => 'true, false',
					'description' => 'Disables the validation of the answer values. The main purpose of this flag is to allow quick testing of the script during development.'),
				),
			'description' => 'TODO',
			),

		// commands inside blocks
		'title' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('title'),
			'properties' => array(),
			'description' => 'Todo',
			),
		'text' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('text'),
			'properties' => array(),
			'description' => 'Displays some text. For longer texts it is recommended to use the `include()`-macro: (e.g. `text include(welcome.html)`)',
			),
		'video' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('video1', 'video2'),
			'properties' => array(
				'mediaurl' 		 => array(
					'default' => MEDIA_URL,
					'values' => 'URL',
					'description' => 'Todo'),
				'videowidth' 	 => array(
					'default' => 352,
					'values' => 'number of pixels',
					'description' => 'Todo'),
				'videoheight' 	 => array(
					'default' => 288,
					'values' => 'number of pixels',
					'description' => 'Todo'),
				),
			'description' => '',
			),
		'image' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('image'),
			'properties' => array(
				'mediaurl' 		 => array(
					'default' => MEDIA_URL,
					'values' => 'URL',
					'description' => 'Todo'),
				),
			'description' => '',
			),
		'question' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('question'),
			'properties'   => array(
				'answermode'	 => array(
					'default' => 'discrete',
					'values' => 'continous, discrete, strings, text',
					'description' => 'Todo'),
				'answers'		 => array(
					'default' => '1: First answer; 2: Second answer; 3: Third answer',
					'values' => 'key value list',
					'description' => 'Todo'),
				'width'			 => array(
					'default' => -1,
					'values' => 'number',
					'description' => 'Todo'),
				),
			'description' => '',
			),
		'qualification' => array(
			'isBlock' => false,
			'needsBlock' => true,
			'minArguments' => 1,
			'arguments' => array('qualification-batch'),
			'properties'   => array(),
			'description' => '',
			),
		);

	public function __construct($batchId)
	{
		$this->batchId = $batchId;
	}

	public function getSource()
	{
		// load source file
		if ($this->source == '')
			$this->source = file_get_contents($this->getSourceFileName());

		return $this->source;
	}

	public function setSource($source)
	{
		if ($source <> '')
		{
			$this->source = $source;
			$file = $this->getSourceFileName();
			file_put_contents($file, $source);
			chmod($file, $this->getConfig('filePermissions'));
		}
	}

	public function exists()
	{
		return file_exists($this->getSourceFileName());
	}

	public function create()
	{
		$defaultQCS = <<<'EOT'
meta title "New Batch"
meta description "New batch description"

step
	title "New Batch"
	text "Hello World"
end step

EOT;
		$path = BATCH_PATH . $this->batchId;
		$file = $path . DS . 'definition.qcs';

		mkdir($path);
		chmod($path, $this->getConfig('dirPermissions'));

		file_put_contents($file, $defaultQCS);
		chmod($file, $this->getConfig('filePermissions'));
	}

	public function getBatch()
	{
		if (!$this->exists())
		{
			throw new Exception('Batch with id "' . $this->batchId . '" not found');
		}

		$myBatch = null;

		if (!file_exists($this->getCacheFileName()) ||
			filemtime($this->getSourceFileName()) > filemtime($this->getCacheFileName()) ) // || true)
		{
			$myBatch = $this->compile();
			$myBatch2 = clone $myBatch;
			$file = $this->getCacheFileName();
			file_put_contents($file, serialize($myBatch2));
			chmod($file, $this->getConfig('filePermissions'));
		} else
		{
			$myBatch = file_get_contents($this->getCacheFileName());
			$myBatch = unserialize($myBatch);
		}

		return $myBatch;
	}

	private function compile()
	{
		$steps = array();
		$sourceData = $this->parse();

		$meta = array();
		$properties = array('global' => array(), 'step' => array());
		$variables = array('global' => array(), 'step' => array());

		$currentScope = 'global';

		foreach($sourceData as $sourceStep)
		{
			switch($sourceStep['command'])
			{
				case 'meta':
					$meta[$sourceStep['arguments'][0]] =
						$this->parseValue($sourceStep['arguments'][1], $variables[$currentScope]);
					break;

				case 'set':
					$value = (isset($sourceStep['arguments'][1]) ? $sourceStep['arguments'][1] : true);
					$properties[$currentScope][$sourceStep['arguments'][0]] =
						$this->parseValue($value, $variables[$currentScope]);
					break;

				case 'var':
					$variables[$currentScope][$sourceStep['arguments'][0]] =
						$this->parseValue($sourceStep['arguments'][1], $variables[$currentScope]);
					break;

				case 'unset':
					if ($sourceStep['arguments'][0] == 'all') {
						$properties[$currentScope] = array();
					} else
					{
						unset($properties[$currentScope][$sourceStep['arguments'][0]]);
					}
					break;

				case 'step':
					$step = array(
						'arguments' => array(),
						'properties' => array(),
					 	'elements' => array()
					 	);

					// set properties
					foreach(self::$syntax['step']['properties'] as $propertyKey => $property)
					{
						if (isset($properties['global'][$propertyKey])) {
							$step['properties'][$propertyKey] = $properties['global'][$propertyKey];
						} else {
							$step['properties'][$propertyKey] = $property['default'];
						}
					}

					// set arguments
					$i = 0;
					foreach($sourceStep['arguments'] as $arg)
					{
						$argumentKey = self::$syntax['step']['arguments'][$i];
						$step['arguments'][$argumentKey] = $this->parseValue($arg, $variables['global']);
						$i++;
					}

					$properties['step'] = $properties['global'];
					$variables['step'] = $variables['global'];
					$currentScope = 'step';
					break;

				case 'end':
					$steps[] = $step;
					$currentScope = 'global';
					break;

				default:

					$element = array(
						'command' => $sourceStep['command'],
						'arguments' => array(),
						'properties' => array(),
						);

					// set properties
					foreach(self::$syntax[$sourceStep['command']]['properties'] as $propertyKey => $property)
					{
						if (isset($properties['step'][$propertyKey])) {
							$element['properties'][$propertyKey] = $properties['step'][$propertyKey];
						} else {
							$element['properties'][$propertyKey] = $property['default'];
						}
					}

					// set arguments
					$element['arguments'] = array();
					$i = 0;
					foreach($sourceStep['arguments'] as $arg)
					{
						$argumentKey = self::$syntax[$sourceStep['command']]['arguments'][$i];
						$element['arguments'][$argumentKey] = $this->parseValue($arg, $variables['step']);
						$i++;
					}

					$step['elements'][] = $element;

					break;
			}
		}

		// clean up meta properties
		foreach(self::$syntax['meta']['keys'] as $property => $default)
		{
			if (!isset($meta[$property])) {
				$meta[$property] = $default;
			}
		}

		$myBatch = new Batch($this->batchId, $meta, $steps);

		return $myBatch;
	}

	private function parse()
	{
		$data = array();
		$source = $this->getSource();
		$source = $this->normalize($source);
		$source = $this->resolveMacros($source);
		$source = $this->resolveForLoops($source);

		$source = $this->normalize($source);

		// parse source file
		$lines = explode("\n", $source);
		foreach($lines as $line)
		{
			$words = explode(' ', $line);
			$words = str_getcsv($line, ' ', '"');

			if (!isset(self::$syntax[$words[0]]))
			{
				throw new Exception ($this->batchId . ': unknown command "' . $words[0] . '"');
			}
			$cmd = self::$syntax[$words[0]];

			if (count($words) < $cmd['minArguments'] + 1)
			{
				throw new Exception($this->batchId . ': ' .
					'"' . $words[0] . '" requires at least ' .
					$cmd['minArguments'] . ' arguments');
			}

			if (count($words) > count($cmd['arguments']) + 1)
			{
				throw new Exception($this->batchId . ': ' .
					'"' . $words[0] . '" accepts a maximum of ' .
					count($cmd['arguments']) . ' arguments');
			}

			$data[] = array(
				'command' => $words[0],
				'arguments' => array_slice($words, 1),
				);
		}

		return $data;
	}

	private function resolveMacros($source)
	{
		// find macro definitions
		$macros = $this->extractBlock($source, 'macro');

		// replace macro references
		foreach($macros as $macro) {
			$content = implode("\n", $macro['content']);
			$source = str_replace('$' . $macro['arguments'][0], $content, $source);
		}

		return $source;
	}

	private function resolveForLoops($source)
	{
		// find list definitions
		$lists = $this->extractBlock($source, 'list');

		// find for loops
		$forloops = $this->extractBlock($source, 'for');
		//header("Content-Type: text/plain; charset=utf8");

		// expand for loops
		$lines = explode("\n", $source);

		foreach($forloops as $loop) {
			// find matching list
			$myList = null;
			foreach($lists as $list) {
				if ($list['arguments'][0] == $loop['arguments'][2]) {
					$myList = $list['content'];
					break;
				}
			}
			if ($myList === null) {
				throw new Exception("List with name '{$loop['arguments'][2]}' not found.");
			}

			// expanding
			$loopContent = array();
			foreach($myList as $listItem) {
				$content = implode("\n", $loop['content']);
				$content = str_replace('$' . $loop['arguments'][0], $listItem, $content);
				$loopContent[] = $content;
			}

			// replacing
			$loopContent = implode("\n", $loopContent);
			$lines[$loop['start']] = $loopContent;
		}

		$source = implode("\n", $lines);

		return $source;
	}

	private function extractBlock(&$source, $keyword)
	{
		$blocks = array();

		$insideBlock = false;
		$lines = explode("\n", $source);
		foreach($lines as $li => $line)
		{
			$words = explode(' ', $line);
			$words = str_getcsv($line, ' ', '"');

			if ($words[0] == $keyword) {
				array_shift($words);
				$block = array(
					'start' => $li,
					'arguments'  => $words,
					'content' => array(),
					);
				$insideBlock = true;

			} elseif ($words[0] == 'end' && $words[1] == $keyword) {
				$block['length'] = $li - $block['start'] + 1;
				$blocks[] = $block;
				$insideBlock = false;
			} else {
				if ($insideBlock) {
					$block['content'][] = $line;
				}
			}
		}

		// remove block definition
		foreach($blocks as $block) {
			$replacement = array_fill(0, $block['length'], '');
			array_splice($lines, $block['start'], $block['length'], $replacement);
		}

		$source = implode("\n", $lines);

		return $blocks;
	}

	private function normalize($source)
	{
		// remove comments
		$source = preg_replace("/\s*#.*$/m", '', $source);

		// replace tabs with spaces
		$source = str_replace("\t", ' ', $source);

		// clean up line endings
		$source = str_replace("\r\n", "\n", $source);

		// remove empty lines
		$source = preg_replace('/^\s*$/m', '', $source);
		$source = str_replace("\n\n", "\n", $source);
		$source = preg_replace('/^\n/', "", $source);
		$source = preg_replace('/\n$/', "", $source);

		// remove multiple spaces
		$source = preg_replace("/\ {2,}/", ' ', $source);

		// remove spaces at line beginnings
		$source = preg_replace("/^\ /m", "", $source);

		// remove spaces at line endings
		$source = preg_replace('/\ *\n/', "\n", $source);

		return $source;
	}

	private function parseValue($value, $variables)
	{
		// leave ints, bools, etc. untouched
		if (gettype($value) <> 'string') return $value;

		// resolve variables
		foreach($variables as $k => $v)
		{
			$value = str_replace('$' . $k, $v, $value);
		}

		// find and resolve includes
		if (preg_match('/^include\(\s*(.+)\s*\)$/', $value, $matches))
		{
			$inc = $matches[1];
			$inc = str_replace('/', DS, $inc);
			$inc = str_replace('\\', DS, $inc);

			$file = BATCH_PATH . $this->batchId . DS . $inc;
			if (file_exists($file))
			{
				$value = file_get_contents($file);
			}
		}

		return $value;
	}

	private function getSourceFileName()
	{
		return BATCH_PATH . $this->batchId . DS .'definition.qcs';
	}

	private function getCacheFileName()
	{
		return TMP_PATH . 'batch-cache' . DS . $this->batchId . '.txt';
	}
}


text:
require 'spec_helper'

RSpec.describe HealthInspector::Checklists::Environment do
  let(:pairing) { described_class.new(health_inspector_context) }

  it_behaves_like 'a chef model'
  it_behaves_like 'a chef model that can be represented in json'

  it 'ignores _default environment if it only exists on server' do
    pairing.name   = '_default'
    pairing.server = {}
    pairing.local  = nil
    pairing.validate

    expect(pairing.errors).to be_empty
  end
end

redpajama_set_name: RedPajamaGithub


text:
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IView } from 'vs/workbench/common/views';
import { CommentsFilters } from 'vs/workbench/contrib/comments/browser/commentsViewActions';

export const CommentsViewFilterFocusContextKey = new RawContextKey<boolean>('commentsFilterFocus', false);

export interface ICommentsView extends IView {

	readonly filters: CommentsFilters;
	focusFilter(): void;
	clearFilterText(): void;
	getFilterStats(): { total: number; filtered: number };

	collapseAll(): void;
}


text:
import 'mocha'
import { expect } from 'chai'

import * as C from '../../../constants'

import { getBasePermissions } from '../../../test/helper/test-helper'
import * as testHelper from '../../../test/helper/test-helper'

const noop = function () {}
const options = testHelper.getDeepstreamPermissionOptions()
const services = options.services
const testPermission = testHelper.testPermission(options)

const lastError = function () {
  return services.logger.logSpy.lastCall.args[2]
}

describe('permission handler loads data for cross referencing', () => {
  before((next) => {
    services.cache.set('item/doesExist', 0, { isInStock: true }, next)
  })

  it('retrieves an existing record from a synchronous cache', (next) => {
    const permissions = getBasePermissions()
    services.cache.nextGetWillBeSynchronous = true

    permissions.record['purchase/$itemId'] = {
      read: '_("item/" + $itemId).isInStock === true'
    }

    const message = {
      topic: C.TOPIC.RECORD,
      action: C.RECORD_ACTION.READ,
      name: 'purchase/doesExist'
    }

    const onDone = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(true)
      expect(services.cache.lastRequestedKey).to.equal('item/doesExist')
      next()
    }

    testPermission(permissions, message, null, null, onDone)
  })

  it('retrieves two records from the cache for cross referencing purposes', (next) => {
    const permissions = getBasePermissions()

    services.cache.set('item/itemA', 0, { isInStock: true }, noop)
    services.cache.set('item/itemB', 0, { isInStock: false }, noop)

    services.cache.nextGetWillBeSynchronous = false
    permissions.record['purchase/$itemId'] = {
      read: '_("item/" + $itemId).isInStock === true && _("item/itemB").isInStock === false'
    }

    const message = {
      topic: C.TOPIC.RECORD,
      action: C.RECORD_ACTION.READ,
      name: 'purchase/itemA'
    }

    const onDone = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(true)
      next()
    }

    testPermission(permissions, message, null, null, onDone)
  })

  it('retrieves and expects a non existing record', (next) => {
    const permissions = getBasePermissions()

    services.cache.nextGetWillBeSynchronous = false
    permissions.record['purchase/$itemId'] = {
      read: '_("doesNotExist") !== null && _("doesNotExist").isInStock === true'
    }

    const message = {
      topic: C.TOPIC.RECORD,
      action: C.RECORD_ACTION.READ,
      name: 'purchase/itemA'
    }

    const onDone = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(false)
      next()
    }

    testPermission(permissions, message, null, null, onDone)
  })

  it('gets a non existant record thats not expected', (next) => {
    const permissions = getBasePermissions()

    services.cache.nextGetWillBeSynchronous = false
    permissions.record['purchase/$itemId'] = {
      read: '_("doesNotExist").isInStock === true'
    }

    const message = {
      topic: C.TOPIC.RECORD,
      action: C.RECORD_ACTION.READ,
      name: 'purchase/itemA'
    }

    const onDone = function (socketWrapper, msg, passItOn, error, result) {
      expect(lastError()).to.contain('TypeError')
      .and.contain('null')
      .and.contain('isInStock')
      expect(result).to.equal(false)
      next()
    }

    testPermission(permissions, message, null, null, onDone)
  })

  it('mixes old data and cross references', (next) => {
    const permissions = getBasePermissions()
    services.cache.reset()
    services.cache.set('userA', 0, { firstname: 'Egon' }, noop)
    services.cache.set('userB', 0, { firstname: 'Mike' }, noop)
    services.cache.nextGetWillBeSynchronous = false
    permissions.record.userA = {
      read: 'oldData.firstname === "Egon" && _("userB").firstname === "Mike"'
    }

    const message = {
      topic: C.TOPIC.RECORD,
      action: C.RECORD_ACTION.READ,
      name: 'userA'
    }

    const onDone = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(true)
      expect(services.cache.getCalls.length).to.equal(2)
      expect(services.cache.hadGetFor('userA')).to.equal(true)
      expect(services.cache.hadGetFor('userB')).to.equal(true)
      setTimeout(next, 200)
    }

    testPermission(permissions, message, null, null, onDone)
  })

  it('retrieves keys from name', (next) => {
    const permissions = getBasePermissions()

    services.cache.set('some-event', 0, { firstname: 'Joe' }, noop)

    permissions.event['some-event'] = {
      publish: '_(name).firstname === "Joe"'
    }

    const message = {
      topic: C.TOPIC.EVENT,
      action: C.EVENT_ACTION.EMIT,
      name: 'some-event'
    }

    const callback = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(true)
      next()
    }

    testPermission(permissions, message, 'username', null, callback)
  })

  it('retrieves keys from variables', (next) => {
    const permissions = getBasePermissions()

    services.cache.set('userX', 0, { firstname: 'Joe' }, noop)

    permissions.event['some-event'] = {
      publish: '_(data.owner).firstname === "Joe"'
    }

    const message = {
      topic: C.TOPIC.EVENT,
      action: C.EVENT_ACTION.EMIT,
      name: 'some-event',
      data: '{"owner":"userX"}'
    }

    const callback = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(true)
      next()
    }

    testPermission(permissions, message, 'username', null, callback)
  })

  it('retrieves keys from variables again', (next) => {
    const permissions = getBasePermissions()

    services.cache.set('userX', 0, { firstname: 'Mike' }, noop)

    permissions.event['some-event'] = {
      publish: '_(data.owner).firstname === "Joe"'
    }

    const message = {
      topic: C.TOPIC.EVENT,
      action: C.EVENT_ACTION.EMIT,
      name: 'some-event',
      data: '{"owner":"userX"}'
    }

    const callback = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(null)
      expect(result).to.equal(false)
      next()
    }

    testPermission(permissions, message, 'username', null, callback)
  })

  it('handles load errors', (next) => {
    const permissions = getBasePermissions()

    permissions.event['some-event'] = {
      publish: '_("bla") < 10'
    }
    services.cache.nextOperationWillBeSuccessful = false

    const message = {
      topic: C.TOPIC.EVENT,
      action: C.EVENT_ACTION.EMIT,
      name: 'some-event',
      data: '{"price":15}'
    }

    const callback = function (socketWrapper, msg, passItOn, error, result) {
      expect(error).to.equal(C.RECORD_ACTION.RECORD_LOAD_ERROR)
      expect(result).to.equal(false)
      next()
    }

    testPermission(permissions, message, 'username', null, callback)
  })
})


text:
package it.polito.elite.enocean.enj.eep.eep26.A5.A502;

import it.polito.elite.enocean.enj.eep.EEPIdentifier;
import it.polito.elite.enocean.enj.eep.eep26.attributes.EEP26TemperatureInverseLinear;

/**
 * @author bonino
 *
 */
public class A50218 extends A502
{

	// the type definition
	public static final byte type = (byte) 0x18;
	// the used channel
	public static int CHANNEL = 0;

	/**
	 * @param version
	 */
	public A50218()
	{
		super();

		// add attributes A50218 has operative range between 20.0 and 100.0
		// Celsius
		this.addChannelAttribute(A50218.CHANNEL,
				new EEP26TemperatureInverseLinear(20.0, 100.0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see it.polito.elite.enocean.enj.eep.EEP#getEEPIdentifier()
	 */
	@Override
	public EEPIdentifier getEEPIdentifier()
	{
		// return the EEPIdentifier for this profile
		return new EEPIdentifier(A502.rorg, A502.func, A50218.type);

	}

}


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Abh. Akad. Berlin, 1838, Phys. tabell. 2, post p. 120.

#### Original name
null

### Remarks
null


text:
/*
	Audio synch data headers
*/

#include <exec/types.h>

#define AUDIO_SYNC_REC_COUNT	7941
#define AUDIO_SYNC_FREQ			50

extern UBYTE const audio_sync[7941];


text:
class Category < ActiveRecord::Base
  has_and_belongs_to_many :items, :order => "upper(name)"

  validates_presence_of :name
  validates_uniqueness_of :name

  belongs_to :updated_by, :class_name => "User", :foreign_key => "updated_by_id"
  before_update :update_history
  after_create :update_history

  def shelters_that_need
    Shelter.find_by_sql(["SELECT DISTINCT upper(shelters.name), shelters.* FROM shelters, conditions, categories_items ci WHERE ci.category_id = ? AND ci.item_id = conditions.item_id AND conditions.type = 'Need' AND conditions.shelter_id = shelters.id ORDER BY upper(shelters.name)", self.id])
  end

  def self.names_for_select
    (Category.find(:all,:order => 'name').map {|cat| [cat.name,cat.id]}).unshift(["All","All"])
  end

end


text:
<?php
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
const TESTING_BASE_PATH = __DIR__ ;
const TESTING_TMP_PATH  = TESTING_BASE_PATH . DIRECTORY_SEPARATOR . 'tmp';


text:
$i18n{trayHeader}

$i18n{trayText}

    <button class="next-button custom-appearance blue-button">
      $i18n{nextButton}
    </button>


text:
package java_integration.fixtures;

public interface ArrayReturningInterface {
    public Object[] blah();
}


text:
layout: single
title: "Accessing the jupyter notebook of a dev server from local machine"
tags: [sysadmin, tensorflow, jupyter, notebook, ssh]
date: 2017-05-19 23:59:59
---

Execute the jupyter notebook in your server, and in your local machine create a ssh tunnel between 8888 ports.

```
ssh -N -f -L localhost:8888:localhost:8888 user@server.address
```


text:
package com.example.kenjxli.cachelib.memory.impl.limited;

import android.graphics.Bitmap;

import com.example.kenjxli.cachelib.memory.LimitedMemoryCache;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by kenjxli on 2015/7/25.
 */
public abstract class ListLimitedMemoryCache extends LimitedMemoryCache {
    protected static final List<String> keys = Collections.synchronizedList(new LinkedList<String>());

    public ListLimitedMemoryCache(int maxSize) {
        super(maxSize);
    }

    @Override
    public boolean put(String key, Bitmap value) {
        if (!keys.contains(key)) {
            keys.add(key);
        }
        return super.put(key, value);
    }

    @Override
    public Bitmap get(String key) {
        return super.get(key);
    }

    @Override
    public Bitmap remove(String key) {
        keys.remove(key);
        return super.remove(key);
    }

    @Override
    public void clear() {
        keys.clear();
        super.clear();
    }

    @Override
    protected abstract String nextRemovedKey();
}


text:
-- -----------------------------------------------------
-- Table `prod`.`project_details`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `prod`.`project_details` (
  `id`                 BIGINT(20)   NOT NULL AUTO_INCREMENT,
  `created_date`       DATETIME     NOT NULL,
  `last_modified_date` DATETIME     NOT NULL,
  `version`            BIGINT(20)   NOT NULL,
  `organisation_type`  VARCHAR(255) NOT NULL,
  `organisation_name`  VARCHAR(255) NOT NULL,
  `project_name`       VARCHAR(255) NOT NULL UNIQUE,
  `owner`              VARCHAR(255) NOT NULL,
  `date_created`       DATETIME     NOT NULL,
  `is_education`       CHAR(1)      NOT NULL DEFAULT 'N',
  `is_service_tool`    CHAR(1)      NOT NULL DEFAULT 'N',
  `supported_by`       TEXT         NOT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  /*!  DEFAULT CHARACTER SET = latin1 */;

-- -----------------------------------------------------
-- Table `prod`.`project_usage`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `prod`.`project_usage` (
  `created_date`       DATETIME     NOT NULL,
  `last_modified_date` DATETIME     NOT NULL,
  `version`            BIGINT(20)   NOT NULL,
  `project_details_id` BIGINT(20)   NOT NULL,
  `month_year`         VARCHAR(255) NOT NULL,
  `monthly_usage`      INT          NOT NULL,
  PRIMARY KEY (`project_details_id`, `month_year`),
  CONSTRAINT project_usage_project_details_id_fk
  FOREIGN KEY (`project_details_id`) REFERENCES project_details (`id`)
)
  ENGINE = InnoDB
  /*!  DEFAULT CHARACTER SET = latin1 */;


text:
package com.amazonaws.services.codecommit.model;

import javax.annotation.Generated;

/**
 * <p>
 * The comment is empty. You must provide some content for a comment. The content cannot be null.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CommentContentRequiredException extends com.amazonaws.services.codecommit.model.AWSCodeCommitException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new CommentContentRequiredException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public CommentContentRequiredException(String message) {
        super(message);
    }

}


text:
module Types
  module AlertManagement
    class AlertType < BaseObject
      graphql_name 'AlertManagementAlert'
      description "Describes an alert from the project's Alert Management"

      implements(Types::Notes::NoteableType)

      authorize :read_alert_management_alert

      field :iid,
            GraphQL::ID_TYPE,
            null: false,
            description: 'Internal ID of the alert'

      field :issue_iid,
            GraphQL::ID_TYPE,
            null: true,
            description: 'Internal ID of the GitLab issue attached to the alert'

      field :title,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'Title of the alert'

      field :description,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'Description of the alert'

      field :severity,
            AlertManagement::SeverityEnum,
            null: true,
            description: 'Severity of the alert'

      field :status,
            AlertManagement::StatusEnum,
            null: true,
            description: 'Status of the alert'

      field :service,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'Service the alert came from'

      field :monitoring_tool,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'Monitoring tool the alert came from'

      field :hosts,
            [GraphQL::STRING_TYPE],
            null: true,
            description: 'List of hosts the alert came from'

      field :started_at,
            Types::TimeType,
            null: true,
            description: 'Timestamp the alert was raised'

      field :ended_at,
            Types::TimeType,
            null: true,
            description: 'Timestamp the alert ended'

      field :event_count,
            GraphQL::INT_TYPE,
            null: true,
            description: 'Number of events of this alert',
            method: :events

      field :details, # rubocop:disable Graphql/JSONType
            GraphQL::Types::JSON,
            null: true,
            description: 'Alert details'

      field :created_at,
            Types::TimeType,
            null: true,
            description: 'Timestamp the alert was created'

      field :updated_at,
            Types::TimeType,
            null: true,
            description: 'Timestamp the alert was last updated'

      field :assignees,
            Types::UserType.connection_type,
            null: true,
            description: 'Assignees of the alert'

      field :metrics_dashboard_url,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'URL for metrics embed for the alert'

      field :runbook,
            GraphQL::STRING_TYPE,
            null: true,
            description: 'Runbook for the alert as defined in alert details'

      field :todos,
            Types::TodoType.connection_type,
            null: true,
            description: 'Todos of the current user for the alert',
            resolver: Resolvers::TodoResolver

      field :details_url,
            GraphQL::STRING_TYPE,
            null: false,
            description: 'The URL of the alert detail page'

      field :prometheus_alert,
            Types::PrometheusAlertType,
            null: true,
            description: 'The alert condition for Prometheus'

      def notes
        object.ordered_notes
      end

      def runbook
        object.parsed_payload.runbook
      end
    end
  end
end


text:
import SurveyAdmin from './modules/SurveyAdmin.js';
import SurveyAssignmentAdmin from './modules/SurveyAssignmentAdmin.js';

$(() => {
  SurveyAdmin.init();
  return SurveyAssignmentAdmin.init();
});


text:
package org.hibnet.webpipes.processor.hoganjs;

import static org.junit.Assert.assertTrue;

import org.hibnet.webpipes.processor.AbstractProcessorTest;
import org.hibnet.webpipes.resource.Resource;
import org.hibnet.webpipes.resource.StringResource;
import org.junit.Test;

public class HoganJsProcessorTest extends AbstractProcessorTest {

    private HoganJsProcessor processor = new HoganJsProcessor();

    @Test
    public void testSimpleString() throws Exception {
        Resource r = new StringResource("template", "Hello {{name}}!");
        String result = processor.process(r).getContent();
        assertTrue(result.contains("Hogan.cache['template']"));
    }

    @Test
    public void testFiles() throws Exception {
        testFiles(processor, ".js", ".js");
    }

}


text:
template <class Polyhedron, class Kernel>
void translate(Polyhedron& polyhedron,
	       const typename Kernel::Vector_3& translate)
{
  typename Polyhedron::Vertex_iterator v;
  for(v = polyhedron.vertices_begin();
      v != polyhedron.vertices_end();
      v++)
    v->point() = v->point() + translate;
}

#endif // _TRANSLATE_


text:
/**
 * Created by PC on 10/1/2016.
 */
angular.module('myApp')
    .directive('myDataTableRole', function (DataTable, $state, RoleService, AlertBox) {
        return {
            restrict: 'EA',
            templateUrl: 'src/scripts/admin/role/role.directive/role.directive.html',
            scope: false,
            link: function (scope, element, attrs) {
                var options = {
                    url: 'http://localhost:8081/role/fetch',
                    columns: [
                        {'title': '', 'data': '_id'},
                        {'title': 'CODE', 'data': 'code'},
                        {'title': 'NAME', 'data': 'name'}
                    ]
                };

                DataTable.generateDataTable(options, element.find('#listDataTableRole'));
            }
        }
    });


text:
package ru.roborox.itunesconnect.api.analytics.model.enums;

public enum Period {
    DAY,
    WEEK,
    MONTH
}


text:
package org.spongycastle.openpgp;

import java.io.IOException;
import java.io.OutputStream;

class WrappedGeneratorStream
    extends OutputStream
{
    private final OutputStream    _out;
    private final StreamGenerator _sGen;

    public WrappedGeneratorStream(OutputStream out, StreamGenerator sGen)
    {
        _out = out;
        _sGen = sGen;
    }
    public void write(byte[] bytes)
        throws IOException
    {
        _out.write(bytes);
    }

    public void write(byte[] bytes, int offset, int length)
        throws IOException
    {
        _out.write(bytes, offset, length);
    }

    public void write(int b)
        throws IOException
    {
        _out.write(b);
    }

    public void flush()
        throws IOException
    {
        _out.flush();
    }

    public void close()
        throws IOException
    {
        _sGen.close();
    }
}


text:
/**
 *
 */
package com.blockwithme.lessobjects.proxy;

import javax.annotation.ParametersAreNonnullByDefault;

/**
 * The Interface ListenerSupport is extended by generated proxy
 * to provide an interface to add listeners.
 *
 * @author tarung
 */
@ParametersAreNonnullByDefault
public interface ListenerSupport {

    /**
     * Adds the listener.
     *
     * @param theListener the listener
     */
    void addListener(final ProxyValueChangeListener theListener);

    /**
     * Adds the listener only to the field(s) specified by theFieldName,
     * field name search is performed on the proxy, if exact match for the
     * field name is found that is used for attaching the listener, otherwise if a
     * child is found with the name passed all the fields of that child are
     * used for attaching the listener.
     *
     *  @throws IllegalStateException if no fields are found with the name specified.
     *  */
    void addListener(final String theFieldName,
            final ProxyValueChangeListener theListener);

    /**
     * Adds a post-commit listener.
     *
     * @param theListener the listener
     */
    void addPostCommitListener(final ProxyTransactionListener theListener);

    /**
     * Adds a pre-commit listener.
     *
     * @param theListener the listener
     */
    void addPreCommitListener(final ProxyTransactionListener theListener);

    /**
     * Removes a listener, if the listener is associated with multiple fields
     * all of them are removed. Listener's equals method is used to check
     * the equality
     *
     * @param theListener the Listener
     */
    public void removeListener(ProxyValueChangeListener theListener);

    /** Removes a listener only from the field(s) specified by theFieldName,
     * field name search is performed on the proxy, if exact match for the
     * field name is found that is used for detaching the listener, else if a
     * child is found with the name passed all the fields of that child are
     * used for detaching the listener.
     *
     *  @throws IllegalStateException if no fields are found with the name specified.
     * */
    public void removeListener(String theFieldName,
            ProxyValueChangeListener theListener);

    /**
     * Removes the post commit listener.
     *
     * @param theListener the theListener
     */
    public void removePostCommitListener(ProxyTransactionListener theListener);

    /**
     * Removes the pre commit listener.
     *
     * @param theListener the the listener
     */
    public void removePreCommitListener(ProxyTransactionListener theListener);

}


text:
import React from 'react'
import {connect} from 'react-redux'

import * as modalActions from '../../action/modal'
import * as coreActions from '../../action/core'

import {formatLocation} from '../../lib/formatter'

import Button from '../../component/button'
import Modal from '../../component/modal'
import Headline from '../../component/headline'
import Paragraph from '../../component/paragraph'

const ConfirmLocationChangeModal = ({location, previousLocation, updateLocation, closeModal}) => {
  const headline = <Headline label="Confirmation necessary" size="l" warning />
  const buttons = [
    <Button
      key="cancel"
      label="Cancel"
      onClick={() => {
        updateLocation({...previousLocation}, true)
        closeModal()
      }}
    />,
    <Button
      key="confirm"
      label="Confirm"
      text
      onClick={() => {
        updateLocation(location, true)
        closeModal()
      }}
    />
  ]

  return (
    <Modal headline={headline} buttons={buttons}>
      <Paragraph strong>
        Do you really want to change your location to <strong>{formatLocation(location)}</strong>?
      </Paragraph>
      <Paragraph>
        By changing the country you have to configure all models in your cart again.
      </Paragraph>
    </Modal>
  )
}

const mapStateToProps = () => ({})

const mapDispatchToProps = {
  updateLocation: coreActions.updateLocation,
  closeModal: modalActions.closeModal
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ConfirmLocationChangeModal)


text:
[![GoDoc](https://godoc.org/github.com/uudashr/gocognit?status.svg)](https://godoc.org/github.com/uudashr/gocognit)
# Gocognit
Gocognit calculates cognitive complexities of functions in Go source code. A measurement of how hard does the code is intuitively to understand.

## Understanding the complexity

Given code using `if` statement,
```go
func GetWords(number int) string {
    if number == 1 {            // +1
        return "one"
    } else if number == 2 {     // +1
        return "a couple"
    } else if number == 3 {     // +1
        return "a few"
    } else {                    // +1
        return "lots"
    }
} // Cognitive complexity = 4
```

Above code can be refactored using `switch` statement,
```go
func GetWords(number int) string {
    switch number {             // +1
        case 1:
            return "one"
        case 2:
            return "a couple"
        case 3:
            return "a few"
        default:
            return "lots"
    }
} // Cognitive complexity = 1
```

As you see above codes are the same, but the second code are easier to understand, that is why the cognitive complexity score are lower compare to the first one.

## Comparison with cyclometic complexity

### Example 1
#### Cyclometic complexity
```go
func GetWords(number int) string {      // +1
    switch number {
        case 1:                         // +1
            return "one"
        case 2:                         // +1
            return "a couple"
        case 3:                         // +1
             return "a few"
        default:
             return "lots"
    }
} // Cyclomatic complexity = 4
```

####  Cognitive complexity
```go
func GetWords(number int) string {
    switch number {                     // +1
        case 1:
            return "one"
        case 2:
            return "a couple"
        case 3:
            return "a few"
        default:
            return "lots"
    }
} // Cognitive complexity = 1
```

Cognitive complexity give lower score compare to cyclomatic complexity.

### Example 2
#### Cyclomatic complexity
```go
func SumOfPrimes(max int) int {         // +1
    var total int

OUT:
    for i := 1; i < max; i++ {          // +1
        for j := 2; j < i; j++ {        // +1
            if i%j == 0 {               // +1
                continue OUT
            }
        }
        total += i
    }

    return total
} // Cyclomatic complexity = 4
```

#### Cognitive complexity
```go
func SumOfPrimes(max int) int {
    var total int

OUT:
    for i := 1; i < max; i++ {          // +1
        for j := 2; j < i; j++ {        // +2 (nesting = 1)
            if i%j == 0 {               // +3 (nesting = 2)
                continue OUT            // +1
            }
        }
        total += i
    }

    return total
} // Cognitive complexity = 7
```

Cognitive complexity give higher score compare to cyclomatic complexity.

## Rules

The cognitive complexity of a function is calculated according to the
following rules:
> Note: these rules are specific for Go, please see the [original whitepaper](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) for more complete reference.

### Increments
There is an increment for each of the following:
1. `if`, `else if`, `else`
2. `switch`, `select`
3. `for`
4. `goto` LABEL, `break` LABEL, `continue` LABEL
5. sequence of binary logical operators
6. each method in a recursion cycle

### Nesting level
The following structures increment the nesting level:
1. `if`, `else if`, `else`
2. `switch`, `select`
3. `for`
4. function literal or lambda

### Nesting increments
The following structures receive a nesting increment commensurate with their nested depth inside nesting structures:
1. `if`
2. `switch`, `select`
3. `for`

## Installation

```
$ go install github.com/uudashr/gocognit/cmd/gocognit@latest
```

or

```
$ go get github.com/uudashr/gocognit/cmd/gocognit
```

## Usage

```
$ gocognit
Calculate cognitive complexities of Go functions.
Usage:
        gocognit [flags] <Go file or directory> ...
Flags:
        -over N   show functions with complexity > N only and
                  return exit code 1 if the set is non-empty
        -top N    show the top N most complex functions only
        -avg      show the average complexity over all functions,
                  not depending on whether -over or -top are set
The output fields for each line are:
<complexity> <package> <function> <file:row:column>
```

Examples:

```
$ gocognit .
$ gocognit main.go
$ gocognit -top 10 src/
$ gocognit -over 25 docker
$ gocognit -avg .
```

The output fields for each line are:
```
<complexity> <package> <function> <file:row:column>
```

## Related project
- [Gocyclo](https://github.com/fzipp/gocyclo) where the code are based on.
- [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) white paper by G. Ann Campbell.


text:
package com.facebook.buck.util.config;

import com.facebook.buck.log.Logger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/** Utility functions for working with {@link Config}s. */
public final class Configs {
  private static final Logger LOG = Logger.get(Configs.class);

  private static final String DEFAULT_BUCK_CONFIG_FILE_NAME = ".buckconfig";
  public static final String DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME = ".buckconfig.local";
  private static final String DEFAULT_BUCK_CONFIG_DIRECTORY_NAME = ".buckconfig.d";

  private static final Path GLOBAL_BUCK_CONFIG_FILE_PATH = Paths.get("/etc/buckconfig");
  private static final Path GLOBAL_BUCK_CONFIG_DIRECTORY_PATH = Paths.get("/etc/buckconfig.d");

  private Configs() {}

  /** Convienence constructor */
  public static Config createDefaultConfig(Path root) throws IOException {
    return createDefaultConfig(root, RawConfig.of(ImmutableMap.of()));
  }

  /**
   * Generates a Buck config by merging configs from specified locations on disk.
   *
   *
In order:
   *
   *

   *
{@code /etc/buckconfig}
   *
Files (in lexicographical order) in {@code /etc/buckconfig.d}
   *
{@code <HOME>/.buckconfig}
   *
Files (in lexicographical order) in {@code <HOME>/buckconfig.d}
   *
{@code <PROJECT ROOT>/.buckconfig}
   *
{@code <PROJECT ROOT>/.buckconfig.local}
   *
Any overrides (usually from the command line)
   *

   *
   * @param root Project root.
   * @param configOverrides Config overrides to merge in after the other sources.
   * @return the resulting {@code Config}.
   * @throws IOException on any exceptions during the underlying filesystem operations.
   */
  public static Config createDefaultConfig(Path root, RawConfig configOverrides)
      throws IOException {
    LOG.debug("Loading configuration for %s", root);
    ImmutableList.Builder<Path> configFileBuilder = ImmutableList.builder();

    configFileBuilder.addAll(listFiles(GLOBAL_BUCK_CONFIG_DIRECTORY_PATH));
    if (Files.isRegularFile(GLOBAL_BUCK_CONFIG_FILE_PATH)) {
      configFileBuilder.add(GLOBAL_BUCK_CONFIG_FILE_PATH);
    }

    Path homeDirectory = Paths.get(System.getProperty("user.home"));
    Path userConfigDir = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_DIRECTORY_NAME);
    configFileBuilder.addAll(listFiles(userConfigDir));
    Path userConfigFile = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME);
    if (Files.isRegularFile(userConfigFile)) {
      configFileBuilder.add(userConfigFile);
    }

    Path configFile = root.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME);
    if (Files.isRegularFile(configFile)) {
      configFileBuilder.add(configFile);
    }
    Path overrideConfigFile = root.resolve(DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME);
    if (Files.isRegularFile(overrideConfigFile)) {
      configFileBuilder.add(overrideConfigFile);
    }

    ImmutableList<Path> configFiles = configFileBuilder.build();

    RawConfig.Builder builder = RawConfig.builder();
    for (Path file : configFiles) {
      try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
        ImmutableMap<String, ImmutableMap<String, String>> parsedConfiguration =
            Inis.read(reader, file.toString());
        if (file.equals(configFile)) {
          LOG.debug("Loaded project configuration file %s", file);
          LOG.verbose("Contents of %s: %s", file, parsedConfiguration);
        } else {
          LOG.debug("Loaded a configuration file %s, %s", file, parsedConfiguration);
        }
        builder.putAll(parsedConfiguration);
      }
    }
    LOG.debug("Adding configuration overrides %s", configOverrides);
    builder.putAll(configOverrides);
    return new Config(builder.build());
  }

  private static ImmutableSortedSet<Path> listFiles(Path root) throws IOException {
    if (!Files.isDirectory(root)) {
      return ImmutableSortedSet.of();
    }
    try (DirectoryStream<Path> directory = Files.newDirectoryStream(root)) {
      return ImmutableSortedSet.<Path>naturalOrder().addAll(directory.iterator()).build();
    }
  }

  public static ImmutableMap<String, ImmutableMap<String, String>> parseConfigFile(Path file)
      throws IOException {
    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
      ImmutableMap<String, ImmutableMap<String, String>> parsedConfiguration =
          Inis.read(reader, file.toString());
      LOG.debug("Loaded a configuration file %s: %s", file, parsedConfiguration);
      return parsedConfiguration;
    }
  }
}


text:
from flask import Blueprint, render_template, jsonify
from sqlalchemy import func

#from trends_website.models.stackexchange import Tag, Question
from trends_website.database import Tag, Question
from trends_website.database import db_session

mod = Blueprint('home', __name__)

@mod.route("/")
def hello():
    """ Welcome page, loads all tags for the autocomplete.
    Context variables:
      tags: List of tags.
      from_date: Oldest date with daily available data
      to_date: Latest date with daily available data
    """

    tags = [tag.name for tag in db_session.query(Tag).all()]

    fnc_max = func.max(Question.date).label("max")
    fnc_min = func.min(Question.date).label("min")
    dates = db_session.query(fnc_max, fnc_min).one()
    return render_template('graphs.html',
                           tags=tags,
                           from_date=dates.min,
                           to_date=dates.max)

@mod.route("/get_samples")
@mod.route("/get_samples/<tag>")
def get_samples(tag=None):
    """ Autocomplete query. Returning only available daily samples.
    """
    datadb = db_session.query(Question).filter_by(tag=tag)\
             .order_by(Question.date.asc())
    if (datadb.count() == 0):
        # Tag not found in database, returning 404.
        return render_template('404.html'), 404

    # Preparing json with data
    response_data = {'samples': [el.nquestions for el in datadb]}

    return jsonify(**response_data)


text:
import traceback
import sys
import os.path
import json
from lxml import etree
from envisat.eheader import ProductHeader
import ns_opt20
import ns_sar20
import ns_xsi

XML_OPTS = {'pretty_print': True, 'xml_declaration': True, 'encoding': 'utf-8'}

def get_footprint_and_center(header):
    return []

def eop_asar(header, platform='ENVISAT:ASAR', ns_sar=None):
    ns_sar = ns_sar or ns_sar20
    ns_eop = ns_sar.ns_eop
    ns_gml = ns_sar.ns_gml
    ns_om = ns_sar.ns_om
    SAR = ns_sar.E
    EOP = ns_eop.E
    OM = ns_om.E

    def _polar(pol):
        return pol[0]+pol[2]

    time_acq_start = header.sph['FIRST_LINE_TIME'].isoformat().replace("+00:00", "Z")
    time_acq_stop = header.sph['LAST_LINE_TIME'].isoformat().replace("+00:00", "Z")
    time_prod = header.mph['PROC_TIME'].isoformat().replace("+00:00", "Z")

    if platform == "ENVISAT:ASAR":
        _platform = EOP.Platform(
            EOP.shortName("Envisat"),
            EOP.orbitType("LEO"),
        )
        _instrument = "ASAR"
        _opmode = header.mph['PRODUCT'][4:6]
        _polmode = "D" if _opmode == "AP" else "S"
        if _opmode in ("IM", "AP"):
            _wrs_code_space = "ENVISAT ASAR IM/AP"
        elif _opmode in ("WS", "GM"):
            _wrs_code_space = "ENVISAT ASAR WS"
        else:
            _wrs_code_space = "ENVISAT ASAR"
    elif platform == "ERS1:AMI-SAR":
        _platform = EOP.Platform(
            EOP.shortName("ERS"),
            EOP.serialIdentifier("1"),
            EOP.orbitType("LEO"),
        )
        _instrument = "AMI/SAR"
        _opmode = "Image"
        _polmode = "S"
        _wrs_code_space = "ERS SAR"
    elif platform == "ERS2:AMI-SAR":
        _platform = EOP.Platform(
            EOP.shortName("ERS"),
            EOP.serialIdentifier("2"),
            EOP.orbitType("LEO"),
        )
        _instrument = "AMI/SAR"
        _opmode = "Image"
        _polmode = "S"
        _wrs_code_space = "ERS SAR"

    _polchannels = [_polar(header.sph['MDS1_TX_RX_POLAR'])]
    if header.sph['MDS2_TX_RX_POLAR'] != '   ':
        _polchannels.append(_polar(header.sph['MDS2_TX_RX_POLAR']))
    if len(_polchannels) > 1:
        if _polchannels[1] == "VV":
            _polchannels = (_polchannels[1], _polchannels[0])
        if _polchannels[1] == "HH":
            _polchannels = (_polchannels[1], _polchannels[0])
    _polchannels = ", ".join(_polchannels)

    eo_equipment = EOP.EarthObservationEquipment(
        ns_gml.getRandomId(),
        EOP.platform(_platform),
        EOP.instrument(EOP.Instrument(
                EOP.shortName(_instrument)
            ),
        ),
        EOP.sensor(EOP.Sensor(
            EOP.sensorType("RADAR"),
            EOP.operationalMode(_opmode),
            EOP.swathIdentifier(header.sph['SWATH']),
        )),
        EOP.acquisitionParameters(SAR.Acquisition(
            EOP.orbitNumber("%d"%header.mph['ABS_ORBIT']),
            EOP.orbitDirection(header.sph['PASS'].strip()),
            EOP.wrsLongitudeGrid("%d"%header.mph['REL_ORBIT'],
                **{'codeSpace': _wrs_code_space}),
            SAR.polarisationMode(_polmode),
            SAR.polarisationChannels(_polchannels),
        )),
    )

    metadata = EOP.EarthObservationMetaData(
        EOP.identifier(header.mph['PRODUCT'][:-3]),
        EOP.parentIdentifier("ENVISAT:%s"%(header.mph['PRODUCT'][:9])),
        EOP.acquisitionType("NOMINAL"),
        EOP.productType(header.mph['PRODUCT'][:10]),
        EOP.status("ARCHIVED"),
        EOP.downlinkedTo(
            EOP.DownlinkInformation(
                EOP.acquisitionStation(header.mph['ACQUISITION_STATION'].strip()),
            ),
        ),
        EOP.processing(
            EOP.ProcessingInformation(
                EOP.processingCenter(header.mph['PROC_CENTER'].strip()),
                EOP.processingDate(time_prod),
                EOP.processorVersion(header.mph['SOFTWARE_VER'].strip()),
            ),
        ),
    )

    xml_eop = SAR.EarthObservation(
        ns_gml.getRandomId(),
        ns_eop.getSchemaLocation("SAR"),
        OM.phenomenonTime(ns_gml.getTimePeriod(time_acq_start, time_acq_stop)),
        #OM.resultQuality(), #optional
        OM.resultTime(ns_gml.getTimeInstant(time_acq_stop)),
        #OM.validTime(), # optional
        OM.procedure(eo_equipment),
        OM.observedProperty({ns_xsi.nil: "true", "nilReason": "inapplicable"}),
        OM.featureOfInterest(
            #ns_eop.getFootprint(*get_footprint_and_center(header))
        ),
        OM.result(EOP.EarthObservationResult(ns_gml.getRandomId())),
        EOP.metaDataProperty(metadata),
    )
    xml_eop = etree.ElementTree(xml_eop)
    #xml_eop.getroot().addprevious(ns_eop.getSchematronPI())
    return xml_eop

def eop_meris(header, ns_opt=None):
    ns_opt = ns_opt or ns_opt20
    ns_eop = ns_opt.ns_eop
    ns_gml = ns_opt.ns_gml
    ns_om = ns_opt.ns_om
    OPT = ns_opt.E
    EOP = ns_eop.E
    OM = ns_om.E

    time_acq_start = header.sph['FIRST_LINE_TIME'].isoformat().replace("+00:00", "Z")
    time_acq_stop = header.sph['LAST_LINE_TIME'].isoformat().replace("+00:00", "Z")
    time_prod = header.mph['PROC_TIME'].isoformat().replace("+00:00", "Z")

    if header.sph['FIRST_MID_LAT'] > header.sph['LAST_MID_LAT']:
        _pass = "DESCENDING"
    else:
        _pass = "ASCENDING"

    eo_equipment = EOP.EarthObservationEquipment(
        ns_gml.getRandomId(),
        EOP.platform(EOP.Platform(
            EOP.shortName("Envisat"),
            EOP.orbitType("LEO"),
        )),
        EOP.instrument(EOP.Instrument(
                EOP.shortName("MERIS")
            ),
        ),
        EOP.sensor(EOP.Sensor(
            EOP.sensorType("OPTICAL"),
            EOP.operationalMode(header.mph['PRODUCT'][4:6]),
        )),
        EOP.acquisitionParameters(EOP.Acquisition(
            EOP.orbitNumber("%d"%header.mph['ABS_ORBIT']),
            EOP.orbitDirection(_pass),
            EOP.wrsLongitudeGrid("%d"%header.mph['REL_ORBIT'],
                **{'codeSpace': "ENVISAT MERIS"}),
        )),
    )

    metadata = EOP.EarthObservationMetaData(
        EOP.identifier(header.mph['PRODUCT'][:-3]),
        EOP.parentIdentifier("ENVISAT:%s"%(header.mph['PRODUCT'][:9])),
        EOP.acquisitionType("NOMINAL"),
        EOP.productType(header.mph['PRODUCT'][:10]),
        EOP.status("ARCHIVED"),
        EOP.downlinkedTo(
            EOP.DownlinkInformation(
                EOP.acquisitionStation(header.mph['ACQUISITION_STATION'].strip()),
            ),
        ),
        EOP.processing(
            EOP.ProcessingInformation(
                EOP.processingCenter(header.mph['PROC_CENTER'].strip()),
                EOP.processingDate(time_prod),
                EOP.processorVersion(header.mph['SOFTWARE_VER'].strip()),
            ),
        ),
    )

    xml_eop = OPT.EarthObservation(
        ns_gml.getRandomId(),
        ns_eop.getSchemaLocation("OPT"),
        #EOP.parameter(), #optional
        OM.phenomenonTime(ns_gml.getTimePeriod(time_acq_start, time_acq_stop)),
        #OM.resultQuality(), #optional
        OM.resultTime(ns_gml.getTimeInstant(time_prod)),
        #OM.validTime(), # optional
        OM.procedure(eo_equipment),
        OM.observedProperty({ns_xsi.nil: "true", "nilReason": "inapplicable"}),
        OM.featureOfInterest(
            #ns_eop.getFootprint(*get_footprint_and_center(header))
        ),
        OM.result(OPT.EarthObservationResult(ns_gml.getRandomId())),
        EOP.metaDataProperty(metadata),
    )
    xml_eop = etree.ElementTree(xml_eop)
    #xml_eop.getroot().addprevious(ns_eop.getSchematronPI())
    return xml_eop

def main(fname):
    with file(fname) as fid:
        header = ProductHeader(fid)

    #print header.mph
    #print "----------------------"
    #print header.sph

    pid = header.mph["PRODUCT"]
    if pid.startswith("MER_") and pid[8] == '1':
        eop = eop_meris(header)
    elif pid.startswith("MER_") and pid[8] == '2':
        eop = eop_meris(header)
    elif pid.startswith("ASA_") and pid[6] in ('P', 'M', 'G') and pid[8] == '1':
        eop = eop_asar(header)
    elif pid.startswith("SAR_") and pid[6] in ('P', 'M', 'G') and pid[8] == '1':
        eop = eop_asar(header, platform='ERS'+pid[-1]+":AMI-SAR")
    else:
        raise ValueError("Unsupported product type %s"%pid[:9])

    print etree.tostring(eop, **XML_OPTS)

if __name__ == "__main__":
    EXENAME = os.path.basename(sys.argv[0])
    DEBUG = False

    try:
        INPUT = sys.argv[1]
        for arg in sys.argv[2:]:
            if arg == "DEBUG":
                DEBUG = True # dump debuging output

    except IndexError:
        print >>sys.stderr, "ERROR: %s: Not enough input arguments!"%EXENAME
        print >>sys.stderr
        print >>sys.stderr, "Extract EOxServer range-type (JSON) from N1 file."
        print >>sys.stderr
        print >>sys.stderr, "USAGE: %s <input-n1> [DEBUG]"%EXENAME
        sys.exit(1)

    if DEBUG:
        print >>sys.stderr, "input-n1:   ", INPUT

    try:
        main(INPUT)
    except Exception as exc:
        print >>sys.stderr, "ERROR: %s: %s "%(EXENAME, exc)
        if DEBUG:
            print >>sys.stderr, traceback.format_exc()
        sys.exit(1)


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

import static org.junit.Assert.*;

import java.util.Date;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;

import generic.test.AbstractGenericTest;
import ghidra.app.services.FunctionComparisonModel;
import ghidra.app.services.FunctionComparisonService;
import ghidra.framework.plugintool.DummyPluginTool;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.data.ByteDataType;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.*;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;

/**
 * Tests the function comparison API and data model. Each test verifies that
 * the underlying data model looks correct following a particular API method
 * call. There are a few tests that also exercise various features of the data
 * model directly.
 *
The API methods being tested: {@link FunctionComparisonService}

 *
The model being used for verification: {@link FunctionComparison}

 */
public class CompareFunctionsTest extends AbstractGhidraHeadedIntegrationTest {

	private Program program1;
	private Program program2;
	private Function foo;
	private Function bar;
	private Function junk;
	private Function stuff;
	private Function one;
	private Function two;
	private Function three;
	private Function four;
	private Function five;
	private FunctionComparisonPlugin plugin;
	private FunctionComparisonProvider provider;
	private FunctionComparisonProvider provider2;
	private FunctionComparisonModel model;

	@Before
	public void setUp() throws Exception {
		DummyPluginTool tool = new DummyPluginTool();
		plugin = new FunctionComparisonPlugin(tool);
		buildTestProgram1();
		buildTestProgram2();

		model = createTestModel();
	}

	@Test
	public void testSetNoFunctions() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet();
		provider = compare(functions);
		assertNull(provider);
	}

	@Test
	public void testSetOneFunction() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
		provider = compare(functions);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo);
	}

	@Test
	public void testSetDuplicateFunctionDifferentProviders() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
		provider = compare(functions);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo);

		provider2 = compare(functions);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, foo, foo);
	}

	@Test
	public void testSetDuplicateFunctionSameProvider() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
		provider = compare(functions);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo);

		compare(functions, provider);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo);
	}

	@Test
	public void testSetMultipleFunctions() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, junk, stuff);
		provider = compare(functions);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, junk, stuff);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, junk, stuff);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, junk, foo, junk, stuff);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, stuff, foo, junk, stuff);
	}

	@Test
	public void testSetMultipleFunctionsMultipleSets() throws Exception {
		Set<Function> functions1 = CompareFunctionsTestUtility.getFunctionsAsSet(one, two);
		Set<Function> functions2 = CompareFunctionsTestUtility.getFunctionsAsSet(three, four, five);

		provider = compare(functions1);
		provider2 = compare(functions2);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, one, two);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, one, one, two);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, two, one, two);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, three, four, five);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, three, three, four, five);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, four, three, four, five);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, five, three, four, five);
	}

	@Test
	public void testSetCombineTwoSets() throws Exception {
		Set<Function> functions1 = CompareFunctionsTestUtility.getFunctionsAsSet(foo, two);
		Set<Function> functions2 = CompareFunctionsTestUtility.getFunctionsAsSet(bar, three, four);

		provider = compare(functions1);
		compare(functions2, provider);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, two, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, two, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, two, foo, two, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, two, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, three, foo, two, bar, three,
			four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, four, foo, two, bar, three,
			four);
	}

	@Test
	public void testSetAddToSpecificProvider() throws Exception {
		Set<Function> functions1 = CompareFunctionsTestUtility.getFunctionsAsSet(foo, two);
		Set<Function> functions2 = CompareFunctionsTestUtility.getFunctionsAsSet(bar, three);
		Set<Function> functions3 = CompareFunctionsTestUtility.getFunctionsAsSet(four);
		provider = compare(functions1);
		provider2 = compare(functions2);

		compare(functions3, provider2);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, two);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, two);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, two, foo, two);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, bar, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, three, bar, three, four);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, four, bar, three, four);
	}

	@Test
	public void testRemoveFunction() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
		provider = compare(functions);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);

		remove(foo);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, bar);
	}

	@Test
	public void testRemoveFunctionTargetOnly() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
		provider = compare(functions);

		// add a target to foo, which is not also a source
		runSwing(() -> plugin.compareFunctions(foo, two, provider));

		// Verify the structure with the new target
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar, two);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);

		remove(two);

		// Verify the new target is gone
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);
	}

	@Test
	public void testRemoveFunctionMultipleProviders() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
		provider = compare(functions);
		provider2 = compare(functions);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, foo, bar);

		remove(foo);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, bar);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, bar);
	}

	@Test
	public void testRemoveNonexistentFunction() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
		provider = compare(functions);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);

		remove(two);  // nothing should happen

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);
	}

	@Test
	public void testRemoveFunctionFromSpecificProvider() throws Exception {
		Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
		provider = compare(functions);
		provider2 = compare(functions);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, bar, foo, bar);

		remove(foo, provider);

		CompareFunctionsTestUtility.checkSourceFunctions(provider, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, bar);
		CompareFunctionsTestUtility.checkSourceFunctions(provider2, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, foo, foo, bar);
		CompareFunctionsTestUtility.checkTargetFunctions(provider2, bar, foo, bar);
	}

	@Test
	public void testDualCompare() {
		provider = compare(foo, bar);
		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, bar);
	}

	@Test
	public void testDualCompareAddToExisting() {
		provider = compare(foo, bar);
		runSwing(() -> plugin.compareFunctions(foo, two, provider));

		CompareFunctionsTestUtility.checkSourceFunctions(provider, foo);
		CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, bar, two);
	}

//==================================================================================================
// Data Model tests
//==================================================================================================

	@Test
	public void testGetTargets() {
		Set<Function> targets = model.getTargetFunctions();
		assertEquals(6, targets.size());
		assertTrue(targets.contains(bar));
		assertTrue(targets.contains(two));
		assertTrue(targets.contains(three));
		assertTrue(targets.contains(four));
		assertTrue(targets.contains(five));
		assertTrue(targets.contains(stuff));
	}

	@Test
	public void testGetTargetsForSource() {
		Set<Function> targets = model.getTargetFunctions(bar);
		assertEquals(3, targets.size());
		assertTrue(targets.contains(three));
		assertTrue(targets.contains(four));
		assertTrue(targets.contains(five));
	}

	@Test
	public void getSources() {
		Set<Function> sources = model.getSourceFunctions();
		assertEquals(3, sources.size());
		assertTrue(sources.contains(foo));
		assertTrue(sources.contains(bar));
		assertTrue(sources.contains(junk));
	}

	@Test
	public void testRemoveFunctionFromModel() {
		model.removeFunction(bar);

		Set<Function> sources = model.getSourceFunctions();
		assertEquals(2, sources.size());
		assertTrue(sources.contains(foo));
		assertTrue(sources.contains(junk));

		Set<Function> targets = model.getTargetFunctions(foo);
		assertEquals(1, targets.size());
		assertTrue(targets.contains(two));

		targets = model.getTargetFunctions(junk);
		assertEquals(1, targets.size());
		assertTrue(targets.contains(stuff));
	}

	private void remove(Function f) {
		runSwing(() -> plugin.removeFunction(f));
	}

	private void remove(Function f, FunctionComparisonProvider fp) {
		runSwing(() -> plugin.removeFunction(f, fp));
	}

	private void compare(Set<Function> functions, FunctionComparisonProvider fp) {
		runSwing(() -> plugin.compareFunctions(functions, fp));
	}

	private FunctionComparisonProvider compare(Set<Function> functions) {
		return plugin.compareFunctions(functions);
	}

	private FunctionComparisonProvider compare(Function f1, Function f2) {
		return plugin.compareFunctions(f1, f2);
	}

	private ProgramBuilder buildTestProgram1() throws Exception {
		ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
		builder.createMemory(".text", "0x1001000", 0x6600);
		builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent

		// functions
		DataType dt = new ByteDataType();
		Parameter p = new ParameterImpl(null, dt, builder.getProgram());
		foo = builder.createEmptyFunction("Foo", "10018cf", 10, null, p);
		bar = builder.createEmptyFunction("Bar", "100299e", 130, null, p, p, p);
		junk = builder.createEmptyFunction("Junk", "1002cf5", 15, null, p, p, p, p, p);
		stuff = builder.createEmptyFunction("Stuff", "1003100", 20, null, p, p);

		program1 = builder.getProgram();
		AbstractGenericTest.setInstanceField("recordChanges", program1, Boolean.TRUE);
		return builder;
	}

	private ProgramBuilder buildTestProgram2() throws Exception {
		ProgramBuilder builder = new ProgramBuilder("TestPgm2", ProgramBuilder._TOY64_BE);
		builder.createMemory(".text", "0x1001000", 0x6600);
		builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent

		// functions
		DataType dt = new ByteDataType();
		Parameter p = new ParameterImpl(null, dt, builder.getProgram());
		one = builder.createEmptyFunction("One", "10017c5", 10, null, p);
		two = builder.createEmptyFunction("Two", "1001822", 130, null, p, p, p);
		three = builder.createEmptyFunction("Three", "1001944", 15, null, p, p, p, p, p);
		four = builder.createEmptyFunction("Four", "1002100", 20, null, p, p);
		five = builder.createEmptyFunction("Five", "1002200", 20, null, p, p);

		program2 = builder.getProgram();
		AbstractGenericTest.setInstanceField("recordChanges", program2, Boolean.TRUE);
		return builder;
	}

	private FunctionComparisonModel createTestModel() {
		FunctionComparisonModel newModel = new FunctionComparisonModel();

		FunctionComparison c1 = new FunctionComparison();
		c1.setSource(foo);
		c1.addTarget(bar);
		c1.addTarget(two);
		newModel.addComparison(c1);

		FunctionComparison c2 = new FunctionComparison();
		c2.setSource(bar);
		c2.addTarget(three);
		c2.addTarget(four);
		c2.addTarget(five);
		newModel.addComparison(c2);

		FunctionComparison c3 = new FunctionComparison();
		c3.setSource(junk);
		c3.addTarget(stuff);
		newModel.addComparison(c3);

		return newModel;
	}
}


text:
A Node.js module for interfacing with the Apple Push Notification service.

## Features

- Fast
- Maintains a connection to the server to maximise notification batching and throughput.
- Enhanced binary interface support, with error handling
- Automatically sends unsent notifications if an error occurs
- Feedback service support
- Complies with all best practises laid out by Apple

## Installation

Via [npm][]:

	$ npm install apn

As a submodule of your project (you will also need to install [q][q])

	$ git submodule add http://github.com/argon/node-apn.git apn
	$ git submodule update --init

## Quick Start

This is intended as a brief introduction, please refer to the documentation in `doc/` for more details.

### Load in the module

	var apn = require('apn');

### Connecting
Create a new connection to the APN gateway server, passing a dictionary of options to the constructor. If you name your certificate and key files appropriately (`cert.pem` and `key.pem`) then the defaults should be suitable to get you up and running. By default the module will connect to the sandbox environment unless the environment variable `NODE_ENV=production` is set. For more information consult the documentation (in doc/apn.markdown).

```javascript
	var options = { };

	var apnConnection = new apn.Connection(options);
```

Help with preparing the key and certificate files for connection can be found in the [wiki][certificateWiki]

### Sending a notification
To send a notification first create a `Device` object. Pass it the device token as either a hexadecimal string, or alternatively as a `Buffer` object containing the token in binary form.

	var myDevice = new apn.Device(token);

Next, create a notification object, set the relevant parameters (See the [payload documentation][pl] for more details.) and use the `pushNotification` method on the connection to send it.

	var note = new apn.Notification();

	note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
	note.badge = 3;
	note.sound = "ping.aiff";
	note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
	note.payload = {'messageFrom': 'Caroline'};

	apnConnection.pushNotification(note, myDevice);

The above options will compile the following dictionary to send to the device:

	{"messageFrom":"Caroline","aps":{"badge":3,"sound":"ping.aiff","alert":"\uD83D\uDCE7 \u2709 You have a new message"}}

### Setting up the feedback service

Apple recommends checking the feedback service periodically for a list of devices for which there were failed delivery attempts.

Using the `Feedback` object it is possible to periodically query the server for the list. Many of the options are similar to that of `Connection`.

Attach a listener to the `feedback` event to receive the output as two arguments, the `time` returned by the server (epoch time) and a `Buffer` object containing the device token - this event will be emitted for each device separately. Alternatively you can enable the `batchFeedback` option and the `feedback` event will provide an array of objects containing `time` and `device` properties.

	var options = {
		"batchFeedback": true,
		"interval": 300
	};

	var feedback = new apn.Feedback(options);
	feedback.on("feedback", function(devices) {
		devices.forEach(function(item) {
			// Do something with item.device and item.time;
		});
	});

By specifying a time interval (in seconds) `Feedback` will periodically query the service without further intervention.

More information about the feedback service can be found in the [feedback service documentation][fs].

## Debugging

If you experience difficulties sending notifications or using the feedback service you can enable debug messages within the library by running your application with `DEBUG=apn` or `DEBUG=apnfb` set as an environment variable.

You will need the `debug` module which can be installed with `npm install debug`.

You are encouraged to read the extremely informative [Troubleshooting Push Notifications][tn2265] Tech Note in the first instance, in case your query is answered there.

## Support

If you have any questions or difficulties working with the module, the [node-apn Google group][googlegroup] should be your first port of call.

Please include as much detail as possible - especially debug logs, if the problem is reproducible sample code is also extremely helpful. GitHub Issues should only be created for verified problems and enhancements, this will allow them to be tracked more easily.

## Resources

* [Local and Push Notification Programming Guide: Apple Push Notification Service][pl]
* [Apple Technical Note: Troubleshooting Push Notifications][tn2265]
* [List of Projects, Applications and Companies Using Node-apn][pacapn]

## Credits

Written and maintained by [Andrew Naylor][andrewnaylor].

Thanks to: [Ian Babrou][bobrik], [dgthistle][dgthistle], [Keith Larsen][keithnlarsen], [Mike P][mypark], [Greg Bergé][neoziro], [Asad ur Rehman][AsadR], [Nebojsa Sabovic][nsabovic], [Alberto Gimeno][gimenete], [Randall Tombaugh][rwtombaugh], [Michael Stewart][thegreatmichael], [Olivier Louvignes][mgcrea], [porsager][porsager], [Craig Hockenberry][chockenberry]

## License

Released under the MIT License

Copyright (c) 2013 Andrew Naylor

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.

[certificateWiki]:https://github.com/argon/node-apn/wiki/Preparing-Certificates "Preparing Certificates"
[errors]:https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW4 "The Binary Interface and Notification Formats"
[pl]: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW1 "Local and Push Notification Programming Guide: Apple Push Notification Service"
[fs]: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3 "The Feedback Service"
[tn2265]: http://developer.apple.com/library/ios/#technotes/tn2265/_index.html "Troubleshooting Push Notifications"
[googlegroup]:https://groups.google.com/group/node-apn "node-apn Google Group"
[pacapn]:https://github.com/argon/node-apn/wiki/Projects,-Applications,-and-Companies-Using-Node-apn "List of Projects, Applications and Companies Using Node-apn"
[andrewnaylor]: http://andrewnaylor.co.uk
[bnoordhuis]: http://bnoordhuis.nl
[npm]: https://npmjs.org
[bobrik]: http://bobrik.name
[dgthistle]: https://github.com/dgthistle
[keithnlarsen]: https://github.com/keithnlarsen
[mypark]: https://github.com/mypark
[neoziro]: https://github.com/neoziro
[AsadR]: https://github.com/AsadR
[nsabovic]: https://github.com/nsabovic
[gimenete]: https://github.com/gimenete
[rwtombaugh]: https://github.com/rwtombaugh
[thegreatmichael]: https://github.com/thegreatmichael
[mgcrea]: https://github.com/mgcrea
[porsager]: https://github.com/porsager
[q]: https://github.com/kriskowal/q
[chockenberry]: https://github.com/chockenberry


text:
package org.apache.jackrabbit.oak.spi.security.authentication.callback;

import org.apache.jackrabbit.oak.spi.security.principal.PrincipalProvider;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.assertSame;

public class PrincipalProviderCallbackTest {

    @Test
    public void testCallback() {
        PrincipalProviderCallback cb = new PrincipalProviderCallback();

        PrincipalProvider principalProvider = Mockito.mock(PrincipalProvider.class);
        cb.setPrincipalProvider(principalProvider);

        assertSame(principalProvider, cb.getPrincipalProvider());
    }

}


text:
@interface JavaLangReflectAccessibleObject : NSObject < JavaLangReflectAnnotatedElement > {
  jboolean accessible_;
}

- (jboolean)isAccessible;
- (void)setAccessibleWithBoolean:(jboolean)b;
+ (void)setAccessibleWithJavaLangReflectAccessibleObjectArray:(IOSObjectArray *)objects
                                                  withBoolean:(jboolean)b;

- (id)getAnnotationWithIOSClass:(IOSClass *)annotationClass;
- (jboolean)isAnnotationPresentWithIOSClass:(IOSClass *)annotationClass;
- (IOSObjectArray *)getAnnotations;
- (IOSObjectArray *)getDeclaredAnnotations;
- (NSString *)toGenericString;

@end

CF_EXTERN_C_BEGIN

void JavaLangReflectAccessibleObject_init(JavaLangReflectAccessibleObject *self);
JavaLangReflectAccessibleObject *new_JavaLangReflectAccessibleObject_init();

void JavaLangReflectAccessibleObject_setAccessibleWithJavaLangReflectAccessibleObjectArray_withBoolean_(
    IOSObjectArray *objects, jboolean b);

// Returns true if type can be mapped to a valid Java type.
jboolean validTypeEncoding(const char *type);

// Decodes an Objective-C type encoding, returning the associated iOS class.
// For example, the type encoding 's' is decoded as JavaLangShort.
IOSClass *decodeTypeEncoding(const char *type);

// Return a Java type name for an Objective-C type encoding.  For example,
// "byte" is returned for 'c', since a Java byte is mapped to a C char.
NSString *describeTypeEncoding(NSString *type);

CF_EXTERN_C_END

J2OBJC_EMPTY_STATIC_INIT(JavaLangReflectAccessibleObject)

J2OBJC_TYPE_LITERAL_HEADER(JavaLangReflectAccessibleObject)

#endif // _AccessibleObject_H_


text:
/*
 * Decompiled with CFR 0_79.
 */
package org.anddev.andengine.entity.particle.emitter;

import org.anddev.andengine.entity.particle.emitter.IParticleEmitter;

public abstract class BaseParticleEmitter
implements IParticleEmitter {
    protected float mCenterX;
    protected float mCenterY;

    public BaseParticleEmitter(float f, float f2) {
        this.mCenterX = f;
        this.mCenterY = f2;
    }

    public float getCenterX() {
        return this.mCenterX;
    }

    public float getCenterY() {
        return this.mCenterY;
    }

    @Override
    public void onUpdate(float f) {
    }

    @Override
    public void reset() {
    }

    public void setCenter(float f, float f2) {
        this.mCenterX = f;
        this.mCenterY = f2;
    }

    public void setCenterX(float f) {
        this.mCenterX = f;
    }

    public void setCenterY(float f) {
        this.mCenterY = f;
    }
}


text:
require 'rails_helper'
require 'models/concerns/common_locale_logic_spec'

RSpec.describe Asset, type: :model do
  describe '[before_validations on create]' do
    it 'copies base_rfc5646_locale from project if it is blank' do
      project = FactoryBot.create(:project, base_rfc5646_locale: 'es')
      asset = FactoryBot.create(:asset, base_rfc5646_locale: '', project: project)
      expect(asset.base_rfc5646_locale).to eql('es')
    end

    it 'copies targeted_rfc5646_locales from project if it is blank' do
      project = FactoryBot.create(:project, targeted_rfc5646_locales: {'fr' => true})
      asset = FactoryBot.create(:asset, targeted_rfc5646_locales: {}, project: project)
      expect(asset.targeted_rfc5646_locales).to eql({'fr' => true})
    end

    it 'should use targeted_rfc5646_locales specified' do
      project = FactoryBot.create(:project, targeted_rfc5646_locales: {'fr' => true})
      asset = FactoryBot.create(:asset, targeted_rfc5646_locales: {'it' => true}, project: project)
      expect(asset.targeted_rfc5646_locales).to eql({'it' => true})
    end
  end

  describe '[validations]' do
    it { is_expected.to have_attached_file(:file) }
    it { is_expected.to validate_attachment_presence(:file) }
    it { is_expected.to validate_attachment_content_type(:file).allowing(Asset::CONTENT_TYPES) }

    it 'does not allow saving without a name' do
      asset = FactoryBot.build(:asset, name: nil).tap(&:save)
      expect(asset).to_not be_persisted
      expect(asset.errors.full_messages).to eq(["Name can't be blank"])
    end

    it 'does not allow saving without a file name' do
      asset = FactoryBot.build(:asset, file_name: nil).tap(&:save)
      expect(asset).to_not be_persisted
      expect(asset.errors.full_messages).to eq(["File name can't be blank"])
    end

    it 'doesn\'t allow creating 2 Assets in the same project with the same name' do
      asset = FactoryBot.create(:asset, name: 'foo')
      asset_new = FactoryBot.build(:asset, name: 'foo', project: asset.project).tap(&:save)
      expect(asset_new).to_not be_persisted
      expect(asset_new.errors.messages).to eql({:name =>["already taken"]})
    end

    it 'allows creating 2 Assets with the same name under different projects' do
      FactoryBot.create(:asset, name: 'foo')
      asset_new = FactoryBot.build(:asset, name: 'foo', project: FactoryBot.create(:project)).tap(&:save)
      expect(asset_new).to be_persisted
      expect(asset_new.errors).to_not be_any
    end

    it 'doesn\'t allow updating base_rfc5646_locale to be blank' do
      project = FactoryBot.create(:project, base_rfc5646_locale: 'es')
      asset = FactoryBot.create(:asset, project: project)
      asset.update base_rfc5646_locale: nil
      expect(asset.errors.full_messages).to include("source locale can't be blank")
      expect(asset.reload.base_rfc5646_locale).to eql('es')
      asset.update base_rfc5646_locale: ''
      expect(asset.errors.full_messages).to include("source locale can't be blank")
      expect(asset.reload.base_rfc5646_locale).to eql('es')
    end

    it "doesn't allow updating targeted_rfc5646_locales to be blank" do
      project = FactoryBot.create(:project, targeted_rfc5646_locales: {'fr' => true})
      asset = FactoryBot.create(:asset, project: project)
      asset.update targeted_rfc5646_locales: nil
      expect(asset.errors.full_messages).to include("targeted localizations can't be blank")
      expect(asset.reload.targeted_rfc5646_locales).to eql({'fr' => true})
      asset.update targeted_rfc5646_locales: {}
      expect(asset.errors.full_messages).to include("targeted localizations can't be blank")
      expect(asset.reload.targeted_rfc5646_locales).to eql({'fr' => true})
    end

    it "doesn't allow name to be 'new'" do
      asset = FactoryBot.build(:asset, name: 'new').tap(&:save)
      expect(asset.errors.full_messages).to include("Name reserved")
    end
  end

  describe '[#update_import_starting_fields]' do
    it 'should update loading and ready flags' do
      asset = FactoryBot.create(:asset)
      asset.update_import_starting_fields!

      expect(asset.ready).to be false
      expect(asset.loading).to be true
    end
  end

  describe "#full_reset_ready!" do
    before(:each) { allow_any_instance_of(Asset).to receive(:import!) } # prevent auto imports

    it "resets the ready field of the Article and all of its Keys" do
      asset = FactoryBot.create(:asset, name: "test", ready: true)

      k1 = FactoryBot.create(:key, ready: true)
      k2 = FactoryBot.create(:key, ready: true)
      k3 = FactoryBot.create(:key, ready: true)

      asset.keys = [k1, k2, k3]

      asset.full_reset_ready!
      expect(asset).to_not be_ready
      expect(asset.keys.ready.exists?).to be_falsey
    end
  end

  describe "[#import!]" do
    it "resets ready fields, and calls AssetImporter" do
      asset = FactoryBot.create(:asset, name: "test", ready: true)

      FactoryBot.create(:key, project: asset.project, ready: true)
      FactoryBot.create(:key, project: asset.project, ready: true)
      FactoryBot.create(:key, project: asset.project, ready: true)

      expect(AssetImporter).to receive(:perform_once).with(asset.id).once
      allow_any_instance_of(AssetImporter::Finisher).to receive(:on_success)

      asset.import!
      asset.reload

      expect(asset).to_not be_ready
      expect(asset.loading).to be true
      expect(asset.keys.ready.exists?).to be false
    end

    it "raises a Asset::LastImportNotFinished if the previous import is not yet finished" do
      asset = FactoryBot.create(:asset)
      asset.update! loading: true
      expect { asset.import! }.to raise_error(Asset::LastImportNotFinished)
    end
  end
end


text:
var should = require('should');

var Post = require('../lib/post');
var PostCache = require('../lib/postCache');

var cache;

describe('PostCache', function () {

  beforeEach(function(){
    cache = new PostCache();
  });

  describe('ctor', function(){
    it('should be empty when first initilised', function(){
      cache.length().should.equal(0);
    });
  });

  describe('.add', function(){
    it('should be able to add an item', function(){
      var added = cache.add(new Post('testpost'));

      added.should.exist;
      added.should.have.property('slug', 'testpost');

      cache.length().should.equal(1);
    });

    it('should replace a duplicate item an not add a new one', function(){
      cache.add(new Post('testpost'));
      cache.add(new Post('testpost'));

     cache.length().should.equal(1);
    });

    it('should not allow execeeding the max cache size');
  });

  describe('.get', function(){
    it('should be able to get an item', function(){
      var slug = 'testpost';

      cache.add(new Post(slug));
      cache.length().should.equal(1);

      var p = cache.get(slug);
      p.should.exist;
      p.should.have.property('slug', slug);
    });

    it('should return undefined getting an item not added', function(){
      var p = cache.get('testpost');
      should.not.exist(p);
    });
  });

  describe('.remove', function(){
    it('should be able to remove an item', function(){
      cache.add(new Post('testpost'));
      cache.length().should.equal(1);
      cache.remove('testpost');
      cache.length().should.equal(0);
    });

    it('should be return undefined getting a removed item', function () {
      var slug = 'testpost';
      cache.add(new Post(slug));
      cache.length().should.equal(1);
      cache.remove(slug);
      cache.length().should.equal(0);
      var p = cache.get(slug);
      should.not.exist(p);
    });
  });

  describe('.length', function(){
    it('should give the correct length on the cache',function(){
      cache.length().should.equal(0);
      cache.add(new Post('one'));
      cache.length().should.equal(1);
      cache.add(new Post('two'));
      cache.length().should.equal(2);

      for (var i = 0 ;i < 30 ; i++) {
        cache.add(new Post(i.toString()));
      }
      cache.length().should.equal(32);

      cache.clear();
      cache.length().should.equal(0);
    });
  });

  describe('.clear', function(){
    it('should be empty after a clear is performed', function () {
      for (var i = 0 ; i < 30 ; i++) {
        cache.add(new Post(i.toString()));
      }
      cache.length().should.equal(30);

      cache.clear();
      cache.length().should.equal(0);
    });
  });

});


text:
package main.java.meterstanden.domain;

import java.io.IOException;
import java.util.List;

import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.google.gson.Gson;

import main.java.meterstanden.hibernate.HibernateUtil;
import main.java.meterstanden.model.Metersoorten;

/**
 * Servlet implementation class Maandverbruik
 */
@WebServlet(
		description = "Get the maandverbruik of a specific year and metersoort.",
		urlPatterns = {
				"/Maandverbruik",
				"/maandverbruik",
				"/MAANDVERBRUIK"
		})
public class Maandverbruik extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(Maandverbruik.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Maandverbruik() {
        super();
    }

	/**
	 * Get the maandverbruik for a specific year and metersoort.
	 *
	 * The year and metersoort have to be inside the request attributes.
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int year;
		int ms;

		if (
				request.getParameterMap().containsKey("year") &&
				request.getParameterMap().containsKey("ms")
		){
			year = Integer.valueOf(request.getParameter("year"));
			ms = Integer.valueOf(request.getParameter("ms"));
		} else {
			log.error("Maandverbruik requested, but no parameters were given.");
			throw new ServletException("missing parameters");
		}

		List<?> rl = getMaandverbruik(ms, year);

		Gson gson = new Gson();
		response.getWriter().append(gson.toJson(rl));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**************************************************************************
	 * PRIVATE METHODS
	**************************************************************************/

	/**
	 * Get the maandverbruik as a list
	 *
	 * @param ms the metersoort to get the verbruik for
	 * @param year the selected year
	 * @return a list of the maandverbruiken
	 */
	private List<?> getMaandverbruik(int ms, int year){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Metersoorten metersoort = session.get(Metersoorten.class, ms);

		StringBuilder hql = new StringBuilder();
		hql.append("from Maandverbruik m");
		hql.append(" where m.metersoort = :myMeter");
		hql.append(" and m.jaar = :myYear");
		hql.append(" order by m.maand asc");

		Query q = session.createQuery(hql.toString());
		q.setParameter("myMeter", metersoort);
		q.setParameter("myYear", year);
		List<?> rl = q.getResultList();

		session.close();

		return rl;
	}

}


text:
var gulp = require("gulp");
var CFG = require("./utils/config.js");
var del = require("del");

/**
 * clean
 * @see www.npmjs.org/package/del
 */
gulp.task("clean", del.bind(null, [
    CFG.DIR.dist,
    CFG.DIR.report
  ])
);