text:
extern CGFloat const kLocationCardHorizontalInset;
extern CGFloat const kLocationCardVerticalInset;
extern CGFloat const kLocationCardFlickVelocity;


text:
@interface AB_ScrollPageSectionViewController ()
{
    UIView* scrollContent;
    NSArray* controllers;
}

@end

@implementation AB_ScrollPageSectionViewController

- (void) setupWithFrame:(CGRect)frame
{
    [super setupWithFrame:frame];

    scrollContent = [[UIView alloc] initWithFrame:scrollView.bounds];
    scrollContent.userInteractionEnabled = YES;
    scrollContent.backgroundColor = [UIColor clearColor];
    scrollContent.autoresizesSubviews = NO;
    [scrollView addSubview:scrollContent];

    controllers = @[];

    NSArray* controllersToLoad = [self controllers];
    [self expandScrollContentTo:controllersToLoad.count];

    int index = 0;
    for ( NSDictionary* controllerType in [self controllers] )
    {
        [self loadController:controllerType[@"name"]
                    withData:[controllerType objectForKey:@"data"] ? [controllerType objectForKey:@"data"] : nil
                     atIndex:index];
        ++index;
    }

    scrollView.delegate = self;

    [self showButtons];
}

- (NSArray*) controllers
{
    return @[];
}

- (void) expandScrollContentTo:(NSUInteger)size
{
    size = MAX(1, size);

    CGRect scrollContentFrame = scrollContent.frame;
    scrollContentFrame.size.width = scrollView.bounds.size.width * size;
    scrollContent.frame = scrollContentFrame;
    scrollView.contentSize = scrollContentFrame.size;
}

- (void) loadController:(id)controllerName withData:(id)data atIndex:(int)index
{
    [self expandScrollContentTo:controllers.count + 1];

    AB_Controller page = [getController() controllerForTag:controllerName];

    CGRect newPageFrame = scrollView.bounds;
    newPageFrame.origin.x = index * scrollView.bounds.size.width;

    [page setupWithFrame:newPageFrame];
    [page openInView:scrollContent
      withViewParent:self
           inSection:self];

    page.data = data;

    NSMutableArray* mutableControllers = [controllers mutableCopy];
    [mutableControllers addObject:page];
    controllers = [NSArray arrayWithArray:mutableControllers];
}

- (void) pageUpdatedTo:(AB_Controller)page
{

}

- (void) showButtonsForPage:(NSUInteger)pageNum
{
    leftButton.hidden = pageNum == 0;
    rightButton.hidden = pageNum >= controllers.count - 1;

    [self pageUpdatedTo:controllers[pageNum]];
}

- (void) showButtons
{
    NSUInteger pageNum = [self pageNum];
    [self showButtonsForPage:pageNum];
}

- (NSUInteger) pageNum
{
    return MAX(0, MIN(controllers.count - 1, ( scrollView.contentOffset.x + 4.f ) / scrollView.frame.size.width));
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self showButtons];
}

- (void) goToPage:(NSUInteger)pageNum
{
    [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width * pageNum, 0.f) animated:YES];
    [self showButtonsForPage:pageNum];
}

- (IBAction) goLeft:(id)sender
{
    NSUInteger pageNum = [self pageNum];
    if ( pageNum > 0 )
    {
        [self goToPage:pageNum - 1];
    }
}

- (IBAction) goRight:(id)sender
{
    NSUInteger pageNum = [self pageNum];
    if ( pageNum < controllers.count - 1 )
    {
        [self goToPage:pageNum + 1];
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
Postfeed.js is a simple Javascript library for fetching blog posts and embed them into your own website. It focuses on Title and Content within blog posts in the source blog. Currently it only supports "Tumblr" blogs.

## Installation

Clone the GitHub repository and use postfeed.js to add into your ```<script></script>``` tag

```
$ git clone https://github.com/sidgujrathi/postfeed.js.git
```
Now add postfeed.js file to your website root folder and include it in your HTML page

```<script src="postfeed.js"></script>```

## Usage

Postfeed.js requires a couple of configurations to be done in order to fetch the blog posts from the source blog. The following example demonstrates how to configure it manually.

```
<script>
	Postfeed.options = {
		url:"http://blog.siddharthgujrathi.com",
		target:"target-div-id"
	}
</script>
```
By default ```Postfeed.options.url and Postfeed.options.target``` are set to ```http://staff.tumblr.com``` and ```<body/>``` respectively.

Optionally you can set following options for configuration.
```
Postfeed.options = {
		headline:"h1", //How you want to put blog post title as.
		post_count:"3" //Number of blog post you want to fetch.
	}
```

## License

Postfeed.js is distributed under the [MIT](https://github.com/sidgujrathi/postfeed.js/blob/master/LICENSE) license.


text:
from ryu.lib.packet import arp
from ryu.ofproto import ether

from dragonflow.controller.common import constants as const
from dragonflow.controller.common import utils

class ArpResponder(object):
    """
    A class for creating and removing ARP responders.
    @param network_id The network ID in which the port exists
    @param interface_ip The port's IPv4 address
    @param interface_mac The port's physical address. Optional only in case
            of remove.
    """
    def __init__(self, datapath, network_id, interface_ip,
                 interface_mac=None, table_id=const.ARP_TABLE):
        self.datapath = datapath
        self.network_id = network_id
        self.interface_ip = interface_ip
        self.mac_address = interface_mac
        self.table_id = table_id

    def _get_match(self):
        parser = self.datapath.ofproto_parser
        match = parser.OFPMatch()
        match.set_dl_type(ether.ETH_TYPE_ARP)
        match.set_arp_tpa(utils.ipv4_text_to_int(str(self.interface_ip)))
        match.set_arp_opcode(arp.ARP_REQUEST)
        if self.network_id is not None:
            match.set_metadata(self.network_id)
        return match

    def _get_instructions(self):
        ofproto = self.datapath.ofproto
        parser = self.datapath.ofproto_parser
        actions = [parser.OFPActionSetField(arp_op=arp.ARP_REPLY),
                   parser.NXActionRegMove(src_field='arp_sha',
                                          dst_field='arp_tha',
                                          n_bits=48),
                   parser.NXActionRegMove(src_field='arp_spa',
                                          dst_field='arp_tpa',
                                          n_bits=32),
                   parser.OFPActionSetField(eth_src=self.mac_address),
                   parser.OFPActionSetField(arp_sha=self.mac_address),
                   parser.OFPActionSetField(arp_spa=self.interface_ip),
                   parser.OFPActionOutput(ofproto.OFPP_IN_PORT, 0)]
        instructions = [parser.OFPInstructionActions(
            ofproto.OFPIT_APPLY_ACTIONS, actions)]
        return instructions

    def add(self):
            match = self._get_match()
            instructions = self._get_instructions()
            ofproto = self.datapath.ofproto
            parser = self.datapath.ofproto_parser
            msg = parser.OFPFlowMod(datapath=self.datapath,
                                    table_id=self.table_id,
                                    cookie=utils.set_aging_cookie_bits(0),
                                    command=ofproto.OFPFC_ADD,
                                    priority=const.PRIORITY_MEDIUM,
                                    match=match, instructions=instructions,
                                    flags=ofproto.OFPFF_SEND_FLOW_REM)
            self.datapath.send_msg(msg)

    def remove(self):
        ofproto = self.datapath.ofproto
        parser = self.datapath.ofproto_parser
        match = self._get_match()

        msg = parser.OFPFlowMod(datapath=self.datapath,
                                cookie=utils.set_aging_cookie_bits(0),
                                cookie_mask=0,
                                table_id=self.table_id,
                                command=ofproto.OFPFC_DELETE,
                                priority=const.PRIORITY_MEDIUM,
                                out_port=ofproto.OFPP_ANY,
                                out_group=ofproto.OFPG_ANY,
                                match=match)
        self.datapath.send_msg(msg)


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.ClaimCheckOperation;
import org.junit.Test;

public class ClaimCheckEipPushPopRemoveHeaderTest extends ContextTestSupport {

    @Test
    public void testPushPopBodyRemoveHeader() throws Exception {
        getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
        getMockEndpoint("mock:a").expectedHeaderReceived("foo", 123);
        getMockEndpoint("mock:a").expectedHeaderReceived("bar", "Moes");
        getMockEndpoint("mock:b").expectedBodiesReceived("Bye World");
        getMockEndpoint("mock:b").expectedHeaderReceived("foo", 456);
        getMockEndpoint("mock:b").expectedHeaderReceived("bar", "Jacks");
        getMockEndpoint("mock:c").expectedBodiesReceived("Bye World");
        getMockEndpoint("mock:c").expectedHeaderReceived("foo", 123);
        getMockEndpoint("mock:c").message(0).header("bar").isNull();

        template.sendBodyAndHeader("direct:start", "Hello World", "foo", 123);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .setHeader("bar", constant("Moes"))
                    .to("mock:a")
                    .claimCheck(ClaimCheckOperation.Push)
                    .transform().constant("Bye World")
                    .setHeader("foo", constant(456))
                    .setHeader("bar", constant("Jacks"))
                    .to("mock:b")
                    // skip the body and remove the bar header
                    .claimCheck(ClaimCheckOperation.Pop, null, "-body,--header:bar")
                    .to("mock:c");
            }
        };
    }
}


text:
package com.keekan.serve.impl;

import java.util.List;

import com.keekan.bean.AlbumBean;
import com.keekan.dao.AlbumDao;
import com.keekan.serve.AlbumServe;

@SuppressWarnings("unchecked")
public class AlbumServeImpl implements AlbumServe {

	private AlbumDao albumDao;
	/**
     * 添加相册
     * @param albumName 相册的名字
     * @param albumDescribe 相册描述
     * @param albumGroup 相册所属分类
     * @param albumGroupId 相册分类ID
     * @return 新增相册的ID
     */
	public Integer addAlbum(Integer keeno, String albumName, String albumDescribe, Integer ownAlbumGroupId, String  createDate, String updateDate) throws Exception {
		try {
			AlbumBean a = new AlbumBean();
			a.setKeeno(keeno);
			a.setAlbumName(albumName);
			a.setAlbumDescribe(albumDescribe);
			a.setOwnAlbumGroupId(ownAlbumGroupId);
			a.setCreateDate(createDate);
			a.setUpdateDate(updateDate);
			albumDao.addAlbum(a);
			return a.getAlbumId();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("添加相册时出现异常!");
		}
	}

	/**
     * 查看全部相册
     * @param keenum KEE号
     * @return 新增相册的ID
     */

	public List viewAllAlbum(Integer[] albumGroupIds) throws Exception {
		try {
			List albumList = albumDao.viewAllAlbum(albumGroupIds);
			return albumList;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("查看全部相册时出现异常!");
		}
	}

	/**
	 * 根据KEE号码查询所有相册
	 * @param keeno
	 * @return
	 */
	public List viewAllAlbumByKeeno(Integer keeno) throws Exception {
		try {
			List albumNameList = albumDao.viewAllAlbumByKeeno(keeno);
			return albumNameList;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("根据KEE号码查看全部相册!");
		}
	}

	public void setAlbumDao(AlbumDao albumDao) {
		this.albumDao = albumDao;
	}
	public AlbumDao getAlbumDao() {
		return albumDao;
	}

	/**
	 * 获取相册ID
	 */
	public Integer getAlbumId(Integer keeno, String albumName) throws Exception {
		try {
			List albumList = albumDao.getAlbumId(keeno, albumName);
			return (Integer) albumList.get(0);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("获取相册ID异常!");
		}
	}

	/**
	 * 根据相册ID查询相册
	 */
	public List viewAlbumByAlbumId(Integer albumId) throws Exception {
		try {
			List albumList = albumDao.viewAlbumByAlbumId(albumId);
			return albumList;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("根据相册ID查询相册异常!");
		}
	}
}


text:
typedef enum {
  CONFIRM_PAGES = (1<<0),
  CONFIRM_MEMORY = (1<<1),
  CONFIRM_PRINT = (1<<2)
} ConfirmationKind;

gboolean confirm_export_size (Diagram *dia, GtkWindow *parent, guint flags);


text:
const test = require('ava')
const Trie = require('../index')

test('trie simple put() / get()', t => {
	const { subject } = t.context
	const key = [1, 2, 3]
	const value = 'foo'
	subject.put(key, value)
	t.is(subject.get(key), value)
})

test('trie keys can be any iterable that has more than zero values', t => {
	const { subject } = t.context
	const iterable = new TestIterator(2)
	subject.put(iterable, 'foo')
	t.deepEqual(Array.from(subject), ['foo'])
	t.is(subject.get([1, 2]), 'foo')
})

test('trie put throws an error if iterable has zero values', t => {
	const { subject } = t.context
	const iterable = new TestIterator(0)

	const error = t.throws(() => {
		subject.put(iterable, 'foo')
	})

	t.is(error.message, 'invalid key')
})

test('trie put() same key, different value', t => {
	const { subject } = t.context
	const key = [1, 2, 3]
	const v1 = 'foo'
	const v2 = 'foo'
	subject.put(key, v1)
	subject.put(key, v2)

	t.is(subject.get(key), v1)
})

test('trie put() string)', t => {
	const { subject } = t.context
	const key = 'strings also work'
	const v1 = 'foo'
	subject.put(key, v1)

	t.is(subject.get(key), v1) // works with string
	t.is(subject.get(key.split('')), v1) // also an array with the same chars
})

test('trie put() object)', t => {
	const { subject } = t.context

	const key = [{ foo: 'bar' }, { bar: 'foo' }]
	const v1 = 'foo'
	subject.put(key, v1)

	t.is(subject.get(key), v1) // works with string
})

test('trie keys can be longer than one character', t => {
	const { subject } = t.context
	const key = ['foo', 'bar', 'meow']
	subject.put(key, 1)

	t.is(subject.get(key), 1)
})

test('trie put() invalid key', t => {
	const { subject } = t.context
	const error = t.throws(() => {
		subject.put(1, 1)
	})
	t.is(error.message, 'invalid key')
})

test('trie get() a non existent key', t => {
	const { subject } = t.context

	t.is(subject.get(['1']), undefined)
})

test('trie get() empty key', t => {
	const { subject } = t.context

	const error = t.throws(() => {
		// empty iterable
		subject.get('')
	})
	t.is(error.message, 'invalid key')
})

test('trie get() invalid key', t => {
	const { subject } = t.context

	const error = t.throws(() => {
		// not iterable
		subject.get(1)
	})
	t.is(error.message, 'invalid key')
})

test('trie getSubTrie()', t => {
	const { subject } = t.context
	createMediumGraph(subject)
	const subTrie = subject.getSubTrie([1, 2, 3])

	// [1,2,3,4] in original trie
	t.is(subTrie.get([4]), 'zoo')

	// [1,2,3,5] in original trie
	t.is(subTrie.get([5]), 'goo')
})

test('trie getSubTrie() shallow === true', t => {
	const { subject } = t.context
	createMediumGraph(subject)
	const subTrie = subject.getSubTrie([1, 2, 3], true)

	// [1,2,3,4] in original trie
	t.is(subTrie.get([4]), 'zoo')

	// [1,2,3,5] in original trie
	t.is(subTrie.get([5]), 'goo')
})

test('trie remove()', t => {
	const { subject } = t.context
	createMediumGraph(subject)
	const removed = subject.remove([1, 2, 3])

	// [1,2,3,4] in original trie
	t.is(removed.get([4]), 'zoo')

	// [1,2,3,5] in original trie
	t.is(removed.get([5]), 'goo')

	t.is(subject.get([1, 2, 3]), undefined)
})

test('trie remove() a non existent key', t => {
	const { subject } = t.context
	subject.put('abc', 'foo')
	const removed = subject.remove('bar')
	t.is(removed, undefined)
	t.is(subject.get('abc'), 'foo')
})

test('trie remove() empty key', t => {
	const { subject } = t.context

	const error = t.throws(() => {
		subject.remove('')
	})
	t.is(error.message, 'invalid key')
})

test('trie remove() invalid key', t => {
	const { subject } = t.context

	const error = t.throws(() => {
		subject.remove(1)
	})
	t.is(error.message, 'invalid key')
})

test('iteration order is DFS by default', t => {
	const { subject } = t.context
	createBigGraph(subject)
	const iterationOrder = Array.from(subject)

	t.deepEqual(iterationOrder, EXPECTED_DFS_ITERATION_ORDER)
})

test('Specify DFS iteration order in Ctor', t => {
	const subject = Trie.create({ iterationOrder: Trie.DFS })
	createBigGraph(subject)
	const iterationOrder = Array.from(subject)

	t.deepEqual(iterationOrder, EXPECTED_DFS_ITERATION_ORDER)
})

test('explicit DFS iterator', t => {
	const subject = Trie.create({ iterationOrder: Trie.BFS })
	createBigGraph(subject)
	const iterationOrder = Array.from(subject.dfsIterator())

	t.deepEqual(iterationOrder, EXPECTED_DFS_ITERATION_ORDER)
})

test('Specify BFS iteration order in Ctor', t => {
	const subject = Trie.create({ iterationOrder: Trie.BFS })
	createBigGraph(subject)
	const iterationOrder = Array.from(subject)

	t.deepEqual(iterationOrder, EXPECTED_BFS_ITERATION_ORDER)
})

test('explicit BFS iterator', t => {
	const subject = Trie.create({ iterationOrder: Trie.DFS })
	createBigGraph(subject)
	const iterationOrder = Array.from(subject.bfsIterator())

	t.deepEqual(iterationOrder, EXPECTED_BFS_ITERATION_ORDER)
})

test('trie clone', t => {
	const { subject } = t.context
	subject.put('ab', 'moo')
	subject.put('abc', 'foo')

	const clone = subject.clone()

	t.is(clone.get('ab'), 'moo')
	t.is(clone.get('abc'), 'foo')

	// make sure that stuff that's added to the
	// clone dont show up on the original
	clone.put('abcd', 'floop')
	t.is(subject.get('abcd'), undefined)

	// other way around
	subject.put('cbd', 'cbd')
	t.is(clone.get('cbd'), undefined)
})

test('trie search(prefix)', t => {
	const { subject } = t.context
	createBigGraph(subject)
	const results = Array.from(subject.search([1, 2, 3]))
	t.deepEqual(results, ['foo', 'goo', 'zoo', 'fee'])
})

test('trie search(prefix) include keys', t => {
	const { subject } = t.context
	createBigGraph(subject)
	const results = Array.from(subject.search([1, 2, 3], { includeKeys: true }))

	t.deepEqual(results, [
		[
			[1, 2, 3], 'foo'
		],
		[
			[1, 2, 3, 5], 'goo'
		],
		[
			[1, 2, 3, 4], 'zoo'
		],
		[
			[1, 2, 3, 4, 1], 'fee'
		]
	])
})

test('trie search(prefix) invalid key', t => {
	const { subject } = t.context

	const error = t.throws(() => {
		subject.search(1)
	})
	t.is(error.message, 'invalid key')
})

test('trie search(prefix) non existent prefix', t => {
	const { subject } = t.context
	const results = subject.search('kjhasd')
	t.deepEqual(Array.from(results), [])
})

test('trie create() with invalid iteration ordering', t => {
	const error = t.throws(() => {
		Trie.create({ iterationOrder: 'bla' })
	})
	t.is(error.message, 'invalid iteration order, try Trie.BFS or Trie.DFS')
})

test.beforeEach(t => {
	t.context.subject = Trie.create()
})

const EXPECTED_BFS_ITERATION_ORDER = ['moo', 'foo', 'bar', 'zoo', 'goo', 'shmoo', 'fee']
const EXPECTED_DFS_ITERATION_ORDER = ['moo', 'bar', 'shmoo', 'foo', 'goo', 'zoo', 'fee']

function createBigGraph(subject) {
	subject.put([1, 2], 'moo')
	subject.put([1, 2, 3], 'foo')
	subject.put([1, 2, 4], 'bar')
	subject.put([1, 2, 4, 1], 'shmoo')
	subject.put([1, 2, 3, 4], 'zoo')
	subject.put([1, 2, 3, 5], 'goo')
	subject.put([1, 2, 3, 4, 1], 'fee')
}

function createMediumGraph(subject) {
	subject.put([1, 2], 'moo')
	subject.put([1, 2, 3], 'foo')
	subject.put([1, 2, 4], 'bar')
	subject.put([1, 2, 3, 4], 'zoo')
	subject.put([1, 2, 3, 5], 'goo')
}

class TestIterator {
	constructor(count) {
		this._count = count
		this._value = undefined
		this._done = false
	}

	next() {
		if (this._value === undefined) {
			this._value = 0
		}

		if (this._value === this._count) {
			this._done = true
		}

		this._value++

		return this
	}

	get value() {
		return this._value
	}

	get done() {
		return this._done
	}

	[Symbol.iterator]() {
		return this
	}
}


text:
require "fit_commit/validators/base"

module FitCommit
  module Validators
    class SummaryPeriod < Base
      def validate_line(lineno, text, _branch_name)
        if lineno == 1 && text.end_with?(".")
          add_error(lineno, "Do not end your summary with a period.")
        end
      end
    end
  end
end


text:
///
///  Project
///
var Project = Class.create( Storable, {

	//
	// initialize() - sets up the object..
	// 		if obj is passed in, it should contain default properties..
	//
	initialize: function($super, obj) {
        Mojo.Log.info("Project#initialize()..");

		this.name = '';
		this.budget = 0;		// in minutes
		this.total = 0;			// in minutes
		this.budgetDisplay = '';
		this.totalDisplay = '';
		$super(obj);
	},

	//
	// beforeSave() - prepares item for save.. setup sql and params..
	//
	beforeSave: function() {
 		Mojo.Log.info("Project#beforeSave()..");

		if (this.deleted == true) {
			if (this.id == -1) {
				// row was never saved.. ignore..
				return false;
			}
			else {
				// deleting existing row.. DELETE..
				this.sql =
					"DELETE FROM Projects WHERE id = ?;";
				this.params = [ this.id ];
			}
		}
		else {
			if (this.id == -1) {
				this.sql =
					"INSERT INTO Projects (sortOrder, name, budget, total) 		\
					 VALUES (?, ?, ?, ?);";
				this.params = [this.sortOrder, escape(this.name), this.budget, this.total];
			}
			else {
				// row was saved.. UPDATE..
				this.sql =
					"UPDATE Projects											\
					 SET sortOrder = ?, name = ?, budget = ?, total = ? 		\
					 WHERE id = ?;";
				this.params = [this.sortOrder, escape(this.name), this.budget, this.total, this.id];
			}
		}

		return true;
	},

	//
	// afterSave() - called after the item is saved..
	//
	afterSave: function(tx, result) {
 		Mojo.Log.info("Project#afterSave()..");
		return true;
	},

	//
	// afterSetProps() - called after item properties are changed..
	//
	afterSetProps: function() {
 		Mojo.Log.info("Project#afterSetProps()..");
		var hrs = 0;

		// calculate Budget display value..
		if (this.budget == 0) {
			this.budgetDisplay = 'Unlimited';
		} else {
			hrs = this.budget / 60;
			if (hrs != hrs.toFixed(2) ) {	// truncate floating point, if needed..
				hrs = hrs.toFixed(2);
			}
			this.budgetDisplay = (hrs.toString() + ' hrs');
		}

		// calculate Total display value..
		hrs = this.total / 60;
		if (hrs != hrs.toFixed(2) ) {	// truncate floating point, if needed..
			hrs = hrs.toFixed(2);
		}
		this.totalDisplay = (hrs.toString() + ' hrs');

	}

});

///
/// ProjectList
///
var ProjectList = Class.create( StorableList, {

	//
	// initialize() - sets up the object..
	//
	initialize: function($super) {
        Mojo.Log.info("ProjectList#initialize()..");
		$super();
	},

	//
	// loadWhere() - load some items from the database using a where clause..
	//		conditions          text add to where clause.. e.g. 'date_added > ?'
	//		params              parameters to replace '?" in conditions.. e.g. ['2009-01-01']
	//		successCallback		function(transaction, SQLResultSet)
	//		failureCallback		function(transaction, error)
	//
	loadWhere: function(conditions, params, successCallback, failureCallback) {
		Mojo.Log.info("ProjectList#loadWhere().. _items before = " + Object.toJSON(this._items) );
		TimeTracker.db.transaction(
			(function (tx) {
				var sql = "SELECT * FROM Projects WHERE (" + conditions + ") ORDER BY sortOrder ASC;";
				tx.executeSql(sql, params,

					// SUCCESS CALLBACK..
					(function(tx, result) {
						try {
							// this toJSON call fails in WebOS 1.3.1 - DOMException.INVALID_ACCESS_ERR
							// Mojo.Log.info("ProjectList#loadWhere() success.. result = " + Object.toJSON(result));
							Mojo.Log.info("ProjectList#loadWhere() success callback.. row count = " + result.rows.length);
							for (var i=0; i<result.rows.length; i++) {
								var t = new Project( result.rows.item(i) );
								this.loadItem(t)
							}
							Mojo.Log.info("ProjectList#loadWhere().. _items after = " + Object.toJSON(this._items) );
							Object.isFunction(successCallback) && successCallback(tx, result);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#loadWhere() success callback. EXCEPTION: " + err);
						}

					}).bind(this),

					// ERROR CALLBACK..
					function(tx, error) {
						try {
							Mojo.Log.warn("ProjectList#loadWhere() error callback.. (" + error.code + ") " + error.message);
							Object.isFunction(failureCallback) && failureCallback(tx, error);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#loadWhere() error callback. EXCEPTION: " + err);
						}
					}

				);
			}).bind(this)
		);
	},

	//
	// createDB() - try to create the necessary table structure in the database..
	//
	createDB: function(successCallback, failureCallback) {
        Mojo.Log.info("ProjectList#createDB()..");
		var seedFn = this.seedDB.bind(this);

		TimeTracker.db.transaction(
			function (tx) {
				var sql =
					"CREATE TABLE Projects (							\
						id			INTEGER NOT NULL PRIMARY KEY,		\
						sortOrder	INTEGER NOT NULL,					\
						name		VARCHAR(50) NOT NULL,				\
						budget		INTEGER NOT NULL,					\
						total		INTEGER NOT NULL					\
			 		);";
				tx.executeSql(sql, [],

					// SUCCESS CALLBACK..
					function(tx, result) {
						try {
							Mojo.Log.info("ProjectList#createDB() success callback.. result = " + Object.toJSON(result));
							seedFn(successCallback, failureCallback);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#createDB() success callback. EXCEPTION: " + err);
						}
					},

					// ERROR CALLBACK..
					function(tx, error) {
						try {
							Mojo.Log.warn("ProjectList#createDB() error callback.. (" + error.code + ") " + error.message);
   							// error callback here is normal - means the table exists.
							Object.isFunction(successCallback) && successCallback(tx, null);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#createDB() error callback. EXCEPTION: " + err);
						}
					}

				);
			}
		);
	},

	//
	// seedDB() - inserts seed data into the database..
	//
	seedDB: function(successCallback, failureCallback) {
		Mojo.Log.info("ProjectList#seedDB()..");
		TimeTracker.db.transaction(
			function (tx) {
				var sql =
					"INSERT INTO Projects (id, sortOrder, name, budget, total) 		\
					 VALUES (1, 1, 'Default Project', 0, 0);";
				tx.executeSql(sql, [],

					// SUCCESS CALLBACK..
					function(tx, result) {
						try {
							Mojo.Log.info("ProjectList#seedDB() success callback.. result = " + Object.toJSON(result));
							Object.isFunction(successCallback) && successCallback(tx, result);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#seedDB() success callback. EXCEPTION: " + err);
						}
					},

					// ERROR CALLBACK..
					function(tx, error) {
						try {
							Mojo.Log.warn("ProjectList#seedDB() error callback.. (" + error.code + ") " + error.message);
							Object.isFunction(failureCallback) && failureCallback(tx, error);
						}
						catch(err) {
					 		Mojo.Log.error("ProjectList#seedDB() error callback. EXCEPTION: " + err);
						}
					}

				);
			}
		);
	}

});


text:
package org.eclipse.mat.snapshot.model;

import org.eclipse.mat.snapshot.ISnapshot;

/**
 * Value of a field if it is a pseudo references. Some references do not
 * actually exist in the heap dump but are automatically generated because they
 * are maintained by the JVM. Examples are the link from an instance to the
 * class and from the class to the class loader.
 */
public class PseudoReference extends NamedReference
{
    private static final long serialVersionUID = 1L;

    public PseudoReference(ISnapshot snapshot, long address, String name)
    {
        super(snapshot, address, name);
    }
}


text:
import Stage from './Stage';
import { Icons } from '../constants';

export default class Item extends Stage {
    constructor (id, name, pointable = false, help = null, color = 'white', icon = Icons.NOICON) {
        super(id, name, true, pointable, help);
        this.color = color;
        this.icon = icon;
    }
}


text:
<?php
namespace Faker\Extension\Faker\Type;

use Faker\Components\Faker\Exception as FakerException,
    Faker\Components\Faker\Type\Type,
    Faker\Components\Faker\Type\Date,
    Faker\Components\Faker\Utilities,
    Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

class UnixTimestamp extends Date
{

    //  -------------------------------------------------------------------------

    /**
     * Generate a value
     *
     * @return string
     */
    public function generate($row,$values = array())
    {
        $date = parent::generate($row,$values);
        return $date->format('U');
    }

}
/* End of File */


text:
package org.synyx.urlaubsverwaltung.ui.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.synyx.urlaubsverwaltung.ui.Page;

import java.time.LocalDate;

import static java.time.format.DateTimeFormatter.ofPattern;

public class SickNotePage implements Page {

    private static final By PERSON_SELECTOR = By.cssSelector("[data-test-id=person-select]");
    private static final By SICKNOTE_TYPE_SELECTOR = By.cssSelector("[data-test-id=sicknote-type-select]");
    private static final By DAY_TYPE_FULL_SELECTOR = By.cssSelector("[data-test-id=day-type-full]");
    private static final By DAY_TYPE_MORNING_SELECTOR = By.cssSelector("[data-test-id=day-type-morning]");
    private static final By DAY_TYPE_NOON_SELECTOR = By.cssSelector("[data-test-id=day-type-noon]");
    private static final By FROM_SELECTOR = By.cssSelector("[data-test-id=sicknote-from-date]");
    private static final By TO_SELECTOR = By.cssSelector("[data-test-id=sicknote-to-date]");
    private static final By AUB_FROM_SELECTOR = By.cssSelector("[data-test-id=sicknote-aub-from]");
    private static final By AUB_TO_SELECTOR = By.cssSelector("[data-test-id=sicknote-aub-from]");
    private static final By SUBMIT_SELECTOR = By.cssSelector("[data-test-id=sicknote-submit-button]");

    private final WebDriver driver;

    private enum Type {
        SICK_NOTE("1000"),
        CHILD_SICK_NOTE("2000");

        final String value;

        Type(String value) {
            this.value = value;
        }
    }

    public SickNotePage(WebDriver driver) {
        this.driver = driver;
    }

    @Override
    public boolean isVisible(WebDriver driver) {
        return !driver.findElements(SUBMIT_SELECTOR).isEmpty();
    }

    public void startDate(LocalDate startDate) {
        setDate(startDate, FROM_SELECTOR);
    }

    public void toDate(LocalDate toDate) {
        setDate(toDate, TO_SELECTOR);
    }

    public void selectTypeChildSickNote() {
        final Select select = new Select(driver.findElement(SICKNOTE_TYPE_SELECTOR));
        select.selectByValue(Type.CHILD_SICK_NOTE.value);
    }

    public void aubStartDate(LocalDate aubStartDate) {
        setDate(aubStartDate, AUB_FROM_SELECTOR);
    }

    /**
     * Submits the sick note form. Note that this method doesn't wait until something happens (e.g. submit button is stale for instance).
     * You may have to add a wait yourself after calling this method.
     */
    public void submit() {
        driver.findElement(SUBMIT_SELECTOR).click();
    }

    public boolean dayTypeFullSelected() {
        return driver.findElement(DAY_TYPE_FULL_SELECTOR).isSelected();
    }

    public boolean typeSickNoteSelected() {
        final String value = driver.findElement(SICKNOTE_TYPE_SELECTOR).getAttribute("value");
        return Type.SICK_NOTE.value.equals(value);
    }

    public boolean showsToDate(LocalDate fromDate) {
        final String value = driver.findElement(TO_SELECTOR).getAttribute("value");
        final String expectedDateString = ofPattern("dd.MM.yyyy").format(fromDate);
        return value.equals(expectedDateString);
    }

    public boolean showsAubToDate(LocalDate fromDate) {
        final String value = driver.findElement(AUB_TO_SELECTOR).getAttribute("value");
        final String expectedDateString = ofPattern("dd.MM.yyyy").format(fromDate);
        return value.equals(expectedDateString);
    }

    /**
     * Check if the given name matches the selected person.
     *
     * @param name the displayed username
     * @return true when the given name is the selected element, false otherwise
     */
    public boolean personSelected(String name) {
        final WebElement selectElement = driver.findElement(PERSON_SELECTOR);
        final String value = selectElement.getAttribute("value");
        final WebElement optionElement = selectElement.findElement(By.cssSelector("option[value=\"" + value + "\"]"));
        return optionElement.getText().strip().equals(name);
    }

    private void setDate(LocalDate date, By selector) {
        final String dateString = ofPattern("dd.MM.yyyy").format(date);
        final WebElement input = driver.findElement(selector);
        input.clear();
        input.sendKeys(dateString);
    }
}


text:
package bropals.lib.simplegame.gui;

import java.util.ArrayList;

/**
 * Makes it easier to group GuiElements together.
 * @author Jonathon
 */
public class GuiGroup {

    private ArrayList<GuiElement> group = new ArrayList<GuiElement>();
    private boolean enabled = true;

    /**
     * Adds an element to this GuiGroup
     * @param element the element to add
     */
    public void addElement(GuiElement element) {
        group.add(element);
    }

    /**
     * Removes an element from this GuiGroup
     * @param element the element to remove
     */
    public void removeElement(GuiElement element) {
        group.remove(element);
    }

    /**
     * Checks to see if this GuiGroup is enabled.
     * @return the enabled state of this GuiGroup.
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Sets the enabled state of this GuiGroup. When this GuiGroup is not
     * enabled, then it will not draw, update, or react to input even when
     * its functions are called.
     * @param enabled the new enabled state.
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * Updates all elements in this GuiGroup
     * @param mouseX the current X mouse position
     * @param mouseY the current Y mouse position
     */
    public void update(int mouseX, int mouseY) {
        if (!isEnabled())
            return;
        for (GuiElement element : group) {
            element.update(mouseX, mouseY);
        }
    }

    /**
     * Draws all elements in this GuiGroup
     * @param graphicsObject the graphics object to draw this GuiGroup with
     */
    public void render(Object graphicsObject) {
        if (!isEnabled())
            return;
        for (GuiElement element : group) {
            element.render(graphicsObject);
        }
    }

    /**
     * Sends mouse pressed input to all elements in this GuiGroup
     * @param mouseX the X mouse position
     * @param mouseY the Y mouse position
     */
    public void mouseInput(int mouseX, int mouseY) {
        if (!isEnabled())
            return;
        for (GuiElement element : group) {
            element.mouseInput(mouseX, mouseY);
        }
    }
}


text:
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbHeader
* @restrict E
* @function
* @description
* The header on an editor that contains tabs using bootstrap tabs - THIS IS OBSOLETE, use umbTabHeader instead
**/
angular.module("umbraco.directives")
.directive('umbHeader', function ($parse, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        transclude: 'true',
        templateUrl: 'views/directives/umb-header.html',
        //create a new isolated scope assigning a tabs property from the attribute 'tabs'
        //which is bound to the parent scope property passed in
        scope: {
            tabs: "="
        },
        link: function (scope, iElement, iAttrs) {

            scope.showTabs = iAttrs.tabs ? true : false;
            scope.visibleTabs = [];

            //since tabs are loaded async, we need to put a watch on them to determine
            // when they are loaded, then we can close the watch
            var tabWatch = scope.$watch("tabs", function (newValue, oldValue) {

                angular.forEach(newValue, function(val, index){
                        var tab = {id: val.id, label: val.label};
                        scope.visibleTabs.push(tab);
                });

                //don't process if we cannot or have already done so
                if (!newValue) {return;}
                if (!newValue.length || newValue.length === 0){return;}

                //we need to do a timeout here so that the current sync operation can complete
                // and update the UI, then this will fire and the UI elements will be available.
                $timeout(function () {

                    //use bootstrap tabs API to show the first one
                    iElement.find(".nav-tabs a:first").tab('show');

                    //enable the tab drop
                    iElement.find('.nav-pills, .nav-tabs').tabdrop();

                    //ensure to destroy tabdrop (unbinds window resize listeners)
                    scope.$on('$destroy', function () {
                        iElement.find('.nav-pills, .nav-tabs').tabdrop("destroy");
                    });

                    //stop watching now
                    tabWatch();
                }, 200);

            });
        }
    };
});


text:
'use strict';

System.register(['aurelia-framework'], function (_export, _context) {
  "use strict";

  var inject, customElement, bindable, _dec, _dec2, _class, VGridElementFooterPager;

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  return {
    setters: [function (_aureliaFramework) {
      inject = _aureliaFramework.inject;
      customElement = _aureliaFramework.customElement;
      bindable = _aureliaFramework.bindable;
    }],
    execute: function () {
      _export('VGridElementFooterPager', VGridElementFooterPager = (_dec = customElement('v-grid-pager'), _dec2 = inject(Element), _dec(_class = _dec2(_class = function () {
        function VGridElementFooterPager(element) {
          _classCallCheck(this, VGridElementFooterPager);

          this.info = "";

          this.element = element;
        }

        VGridElementFooterPager.prototype.bind = function bind(parent) {
          this.parent = parent;
          this.vGrid = parent.vGrid;
          this.vGridConfig = parent.vGrid.vGridConfig;
          this.vGrid.vGridPager = this;
        };

        VGridElementFooterPager.prototype.attached = function attached() {
          this.statusNextButton = false;
          this.statusLastButton = false;
          this.statusFirstButton = false;
          this.statusPrevButton = false;

          this.statusNextButtonTitle = this.getLang("pagerBtnNext") || "Next";
          this.statusLastButtonTitle = this.getLang("pagerBtnLast") || "Last";
          this.statusFirstButtonTitle = this.getLang("pagerBtnFirst") || "First";
          this.statusPrevButtonTitle = this.getLang("pagerBtnLast") || "Last";

          this.pagerStringPage = this.getLang("pagerStringPage") || "Page ";
          this.pagerStringOf = this.getLang("pagerStringOf") || " of ";
          this.pagerStringTotalEntities = this.getLang("pagerStringTotalEntities") || ", Total entities:";
          this.pagerStringPageSize = this.getLang("pagerStringPageSize") || ", page size ";
        };

        VGridElementFooterPager.prototype.getLang = function getLang(value) {
          return this.vGrid.vGridConfig.attLanguage[value];
        };

        VGridElementFooterPager.prototype.updatePager = function updatePager(data) {
          this.collectionLength = data.length;
          this.limit = data.limit;
          this.offset = data.offset;

          this.page = this.offset ? Math.ceil(this.offset / this.limit) + 1 : 1;

          if (this.page === 1) {
            this.statusFirstButton = false;
            this.statusPrevButton = false;
          } else {
            this.statusFirstButton = true;
            this.statusPrevButton = true;
          }

          if (this.offset >= this.collectionLength - this.limit) {
            this.statusNextButton = false;
            this.statusLastButton = false;
          } else {
            this.statusNextButton = true;
            this.statusLastButton = true;
          }

          if (!this.vGridConfig.attHidePagerInfo) {
            this.info = '' + this.pagerStringPage + this.page + this.pagerStringOf + Math.ceil(this.collectionLength / this.limit) + this.pagerStringTotalEntities + this.collectionLength + this.pagerStringPageSize + this.limit;
          }

          this.vGrid.raiseEvent("v-remote-collection-event", {
            evt: "v-remote-collection-event",
            page: this.page,
            pages: Math.ceil(this.collectionLength / this.limit),
            length: this.collectionLength,
            pageSize: this.limit
          });
        };

        VGridElementFooterPager.prototype.firstBtn = function firstBtn() {
          this.vGrid.loading = true;
          this.vGridConfig.remoteOffset = 0;
          this.vGridConfig.remoteCall();
        };

        VGridElementFooterPager.prototype.nextBtn = function nextBtn() {
          this.vGrid.loading = true;
          this.vGridConfig.remoteOffset = this.vGridConfig.remoteOffset + this.vGridConfig.remoteLimit;
          this.vGridConfig.remoteCall();
        };

        VGridElementFooterPager.prototype.prevBtn = function prevBtn() {
          this.vGrid.loading = true;
          this.vGridConfig.remoteOffset = this.vGridConfig.remoteOffset - this.vGridConfig.remoteLimit;
          this.vGridConfig.remoteCall();
        };

        VGridElementFooterPager.prototype.lastBtn = function lastBtn() {
          this.vGrid.loading = true;
          this.vGridConfig.remoteOffset = this.vGridConfig.remoteLength - this.vGridConfig.remoteLimit;
          this.vGridConfig.remoteCall();
        };

        return VGridElementFooterPager;
      }()) || _class) || _class));

      _export('VGridElementFooterPager', VGridElementFooterPager);
    }
  };
});


text:
cask 'http-toolkit' do
  version '0.1.22'
  sha256 '85c4b4252a581d79ac01cf1e9ba8e08ea2edba663a20d7869925056a4e117cf8'

  # github.com/httptoolkit/httptoolkit-desktop/ was verified as official when first introduced to the cask
  url "https://github.com/httptoolkit/httptoolkit-desktop/releases/download/v#{version}/HTTP.Toolkit.dmg"
  appcast 'https://github.com/httptoolkit/httptoolkit-desktop/releases.atom'
  name 'HTTP Toolkit'
  homepage 'https://httptoolkit.tech/'

  app 'HTTP Toolkit.app'

  zap trash: [
               '~/Library/Application Support/HTTP Toolkit',
               '~/Library/Caches/httptoolkit-server',
               '~/Library/Logs/HTTP Toolkit',
               '~/Library/Preferences/httptoolkit',
               '~/Library/Preferences/tech.httptoolkit.desktop.plist',
               '~/Library/Saved Application State/tech.httptoolkit.desktop.savedState',
             ]
end


text:
using namespace std;

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// SHA-256 hash algorithm specializations
// (arises frequently in applications)
//

cryptl::SHA256 HASH256(const uint32_t& dummy) {
    return cryptl::SHA256();
}

cryptl::SHA256 HASH256(const vector<uint32_t>& dummy) {
    return cryptl::SHA256();
}

} // namespace snarkfront


text:
"""System info module."""

import datetime
import logging
import os
import socket
import subprocess

import netifaces
import psutil

logger = logging.getLogger("fm.system.info")  # pylint: disable=invalid-name

def get_ip_of_interface(interface, broadcast=False):
    """Get the ip address of a given interface."""
    # pylint: disable=invalid-name

    if not broadcast:
        ip = netifaces.ifaddresses(interface)[2][0]["addr"]

    else:
        ip = netifaces.ifaddresses(interface)[2][0]["broadcast"]

    return ip

def get_uptime():
    """Get uptime of device."""
    logger.debug("getting uptime")
    uptime = subprocess.check_output(["uptime", "-p"], universal_newlines=True)
    return uptime[3:]

def get_cpu_temperature():
    """Get CPU temperature."""
    logger.debug("getting CPU temperature")
    filepath = "/sys/class/thermal/thermal_zone0/temp"
    res = subprocess.check_output(["cat", filepath], universal_newlines=True)
    return float(int(res) / 1000)

def get_service_status():
    """Get service status."""
    logger.debug("getting service status")
    raise NotImplementedError

def get_device_name():
    """Get device name."""
    logger.debug("getting device name")
    device_name = socket.gethostname()
    return device_name

def get_serial():
    """Get serial number."""
    logger.debug("getting serial number")
    # Extract serial from cpuinfo file
    cpuserial = "0000000000000000"
    try:
        with open("/proc/cpuinfo", "r") as f:
            for line in f:
                if line[0:6] == "Serial":
                    cpuserial = line[10:26]
    except FileNotFoundError:
        cpuserial = "ERROR000000000"

    return cpuserial

def get_system_data():
    """Get system data."""
    logger.debug("getting system data")
    system_data = {}
    system_data["uptime"] = get_uptime()
    system_data["current_time"] = datetime.datetime.now()
    system_data["load_avg"] = os.getloadavg()
    system_data["cpu_temp"] = get_cpu_temperature()

    return system_data

def get_system_memory():
    """Get system memory."""
    logger.debug("getting system memory")
    system_mem = {}

    virtual_mem = psutil.virtual_memory()
    disk = psutil.disk_usage("/")

    system_mem["ram_used"] = virtual_mem.used // 2**20  # MB
    system_mem["ram_total"] = virtual_mem.total // 2**20  # MB
    system_mem["ram_free"] = virtual_mem.free // 2**20  # MB
    system_mem["disk_used"] = round(float(disk.used) / 2**30, 3)  # GB
    system_mem["disk_total"] = round(float(disk.total) / 2**30, 3)  # GB
    system_mem["disk_free"] = round(float(disk.free) / 2**30, 3)  # GB

    return system_mem


text:
"""Changelog routes."""

from typing import cast

import bottle
from pymongo.database import Database

from shared.utils.type import MetricId, ReportId, SourceId, SubjectId

from database import measurements, reports

def _get_changelog(database: Database, nr_changes: str, **uuids: str):
    """Return the recent most nr_changes changes from the changelog."""
    limit = int(nr_changes)
    changes = [
        dict(
            delta=item["delta"]["description"],
            email=item["delta"].get("email", ""),
            timestamp=item.get("timestamp") or item["start"],
        )
        for item in list(measurements.changelog(database, limit, **uuids))
        + list(reports.changelog(database, limit, **uuids))
    ]
    return dict(changelog=sorted(changes, reverse=True, key=lambda change: cast(str, change["timestamp"]))[:limit])

@bottle.get("/api/v3/changelog/source/<source_uuid>/<nr_changes>", authentication_required=False)
def get_source_changelog(source_uuid: SourceId, nr_changes: str, database: Database):
    """Return the recent most nr_changes changes from the source changelog."""
    return _get_changelog(database, nr_changes, source_uuid=source_uuid)

@bottle.get("/api/v3/changelog/metric/<metric_uuid>/<nr_changes>", authentication_required=False)
def get_metric_changelog(metric_uuid: MetricId, nr_changes: str, database: Database):
    """Return the recent most nr_changes changes from the metric changelog."""
    return _get_changelog(database, nr_changes, metric_uuid=metric_uuid)

@bottle.get("/api/v3/changelog/subject/<subject_uuid>/<nr_changes>", authentication_required=False)
def get_subject_changelog(subject_uuid: SubjectId, nr_changes: str, database: Database):
    """Return the recent most nr_changes changes from the subject changelog."""
    return _get_changelog(database, nr_changes, subject_uuid=subject_uuid)

@bottle.get("/api/v3/changelog/report/<report_uuid>/<nr_changes>", authentication_required=False)
def get_report_changelog(report_uuid: ReportId, nr_changes: str, database: Database):
    """Return the recent most nr_changes changes from the report changelog."""
    return _get_changelog(database, nr_changes, report_uuid=report_uuid)

@bottle.get("/api/v3/changelog/<nr_changes>", authentication_required=False)
def get_changelog(nr_changes: str, database: Database):
    """Return the recent most nr_changes changes from the changelog."""
    return _get_changelog(database, nr_changes)


text:
package ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax;

/**
 * UI Response for successfully creating an item.  Since all items in IRIDA require an id,
 * the identifier is returned to the client on successful creation.
 */
public class AjaxCreateItemSuccessResponse extends AjaxResponse {
	private final long id;

	public AjaxCreateItemSuccessResponse(long id) {
		this.id = id;
	}

	public long getId() {
		return id;
	}
}


text:
using System.Collections.Generic;

namespace Spect.Net.Assembler.Assembler
{
    /// <summary>
    /// This class represents the input options of the compiler
    /// </summary>
    public class AssemblerOptions
    {
        /// <summary>
        /// Predefined compilation symbols
        /// </summary>
        public List<string> PredefinedSymbols { get; } = new List<string>();

        /// <summary>
        /// The default start address of the compilation
        /// </summary>
        public ushort? DefaultStartAddress { get; set; } = null;

        /// <summary>
        /// The default displacement address of the compilation
        /// </summary>
        public int? DefaultDisplacement { get; set; } = null;

        /// <summary>
        /// The current ZX Spectrum model
        /// </summary>
        public SpectrumModelType CurrentModel { get; set; } = SpectrumModelType.Spectrum48;

        /// <summary>
        /// The maximum number of errors to report within a loop
        /// </summary>
        public int MaxLoopErrorsToReport { get; set; } = 16;
    }
}


text:
package com.github.benmanes.caffeine.cache;

import static java.util.Objects.requireNonNull;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

/**
 * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache} or
 * {@link AsyncLoadingCache}.
 *

 * Most implementations will only need to implement {@link #load}. Other methods may be
 * overridden as desired.
 *

 * Usage example:
 *
{@code
 *   CacheLoader<Key, Graph> loader = key -> createExpensiveGraph(key);
 *   LoadingCache<Key, Graph> cache = Caffeine.newBuilder().build(loader);
 * }

 *
 * @author ben.manes@gmail.com (Ben Manes)
 */
@FunctionalInterface
public interface CacheLoader<K, V> {

  /**
   * Computes or retrieves the value corresponding to {@code key}.
   *
   * @param key the non-null key whose value should be loaded
   * @return the value associated with {@code key} or {@code null} if not found
   * @throws RuntimeException or Error, in which case the mapping is unchanged
   */
  @CheckForNull
  V load(@Nonnull K key);

  /**
   * Computes or retrieves the values corresponding to {@code keys}. This method is called by
   * {@link LoadingCache#getAll}.
   *

   * If the returned map doesn't contain all requested {@code keys} then the entries it does contain
   * will be cached and {@code getAll} will return the partial results. If the returned map contains
   * extra keys not present in {@code keys} then all returned entries will be cached, but only the
   * entries for {@code keys} will be returned from {@code getAll}.
   *

   * This method should be overridden when bulk retrieval is significantly more efficient than many
   * individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls to
   * {@link LoadingCache#get} if this method is not overridden.
   *
   * @param keys the unique, non-null keys whose values should be loaded
   * @return a map from each key in {@code keys} to the value associated with that key; may not
   *         contain null values
   * @throws RuntimeException or Error, in which case the mappings are unchanged
   */
  @Nonnull
  default Map<K, V> loadAll(@Nonnull Iterable<? extends K> keys) {
    throw new UnsupportedOperationException();
  }

  /**
   * Asynchronously computes or retrieves the value corresponding to {@code key}.
   *
   * @param key the non-null key whose value should be loaded
   * @param executor the executor that asynchronously loads the entry
   * @return the future value associated with {@code key} or {@code null} if not computable
   */
  @CheckForNull
  default CompletableFuture<V> asyncLoad(@Nonnull K key, @Nonnull Executor executor) {
    requireNonNull(key);
    requireNonNull(executor);
    return CompletableFuture.supplyAsync(() -> load(key), executor);
  }

  /**
   * Asynchronously computes or retrieves the values corresponding to {@code keys}. This method is
   * called by {@link AsyncLoadingCache#getAll}.
   *

   * If the returned map doesn't contain all requested {@code keys} then the entries it does contain
   * will be cached and {@code getAll} will return the partial results. If the returned map contains
   * extra keys not present in {@code keys} then all returned entries will be cached, but only the
   * entries for {@code keys} will be returned from {@code getAll}.
   *

   * This method should be overridden when bulk retrieval is significantly more efficient than many
   * individual lookups. Note that {@link AsyncLoadingCache#getAll} will defer to individual calls
   * to {@link AsyncLoadingCache#get} if this method is not overridden.
   *
   * @param keys the unique, non-null keys whose values should be loaded
   * @param executor the executor that with asynchronously loads the entries
   * @return a future containing the map from each key in {@code keys} to the value associated with
   *         that key; may not contain null values
   */
  @Nonnull
  default CompletableFuture<Map<K, V>> asyncLoadAll(
      Iterable<? extends K> keys, @Nonnull Executor executor) {
    requireNonNull(keys);
    requireNonNull(executor);
    return CompletableFuture.supplyAsync(() -> loadAll(keys), executor);
  }

  /**
   * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. If
   * the replacement value is not found then the mapping will be removed if {@code null} is
   * returned. This method is called when an existing cache entry is refreshed by
   * {@link Caffeine#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
   *

   * Note: all exceptions thrown by this method will be logged and then swallowed.
   *
   * @param key the non-null key whose value should be loaded
   * @param oldValue the non-null old value corresponding to {@code key}
   * @return the new value associated with {@code key}, or {@code null} if the mapping is to be
   *         removed
   * @throws RuntimeException or Error, in which case the mapping is unchanged
   */
  @CheckForNull
  default V reload(@Nonnull K key, @Nonnull V oldValue) {
    return load(key);
  }
}


text:
describe ManageIQ::Providers::NativeOperationWorkflow do
  context '.create_job' do
    it 'leaves job waiting to start' do
      options = {}
      job = described_class.create_job(options)

      expect(job.state).to eq('waiting_to_start')
    end
  end

  context 'state transitions' do
    before do
      @job = described_class.create_job({})
    end

    context 'waiting_to_start' do
      before do
        @job.state = 'waiting_to_start'
      end

      it 'allows start signal' do
        expect(@job).to receive(:start)
        @job.signal(:start)
      end

      it 'doesn\'t allow poll_native_task signal' do
        expect { @job.signal(:poll_native_task) }.to raise_error(RuntimeError, /poll_native_task is not permitted at state waiting_to_start/)
      end

      it 'doesn\'t allow refresh signal' do
        expect { @job.signal(:refresh) }.to raise_error(RuntimeError, /refresh is not permitted at state waiting_to_start/)
      end

      it 'doesn\'t allow poll_refresh signal' do
        expect { @job.signal(:poll_refresh) }.to raise_error(RuntimeError, /poll_refresh is not permitted at state waiting_to_start/)
      end
    end

    context 'running' do
      before do
        @job.state = 'running'
      end

      it 'allows poll_native_task signal' do
        expect(@job).to receive(:poll_native_task)
        @job.signal(:poll_native_task)
      end

      it 'allows refresh signal' do
        expect(@job).to receive(:refresh)
        @job.signal(:refresh)
      end

      it 'doesn\'t allow start signal' do
        expect { @job.signal(:start) }.to raise_error(RuntimeError, /start is not permitted at state running/)
      end
    end

    context 'refreshing' do
      before do
        @job.state = 'refreshing'
      end

      it 'allows poll_refresh signal' do
        expect(@job).to receive(:poll_refresh)
        @job.signal(:poll_refresh)
      end

      it 'allows notify signal' do
        expect(@job).to receive(:notify)
        @job.signal(:notify)
      end

      it 'doesn\'t allow start signal' do
        expect { @job.signal(:start) }.to raise_error(RuntimeError, /start is not permitted at state refreshing/)
      end

      it 'doesn\'t allow poll_native_task signal' do
        expect { @job.signal(:poll_native_task) }.to raise_error(RuntimeError, /poll_native_task is not permitted at state refreshing/)
      end

      it 'doesn\'t allow refresh signal' do
        expect { @job.signal(:refresh) }.to raise_error(RuntimeError, /refresh is not permitted at state refreshing/)
      end
    end
  end

  context "refresh" do
    before do
      vm = FactoryGirl.create(:vm)

      options = {
        :target_id    => vm.id,
        :target_class => vm.class.name,
      }

      @job = described_class.create_job(options)
      @job.state = 'running'
    end

    it 'sets the refresh_task_ids in the context' do
      refresh_task = FactoryGirl.create(:miq_task)
      expect(EmsRefresh).to receive(:queue_refresh_task).and_return([refresh_task.id])
      expect(@job).to receive(:queue_signal).with(:poll_refresh)

      @job.signal(:refresh)

      expect(@job.context[:refresh_task_ids]).to eq([refresh_task.id])
    end

    it 'calls error if queuing the refresh failed' do
      expect(EmsRefresh).to receive(:queue_refresh_task).and_return(nil)
      expect(@job).to receive(:queue_signal).with(:notify)

      @job.signal(:refresh)

      expect(@job.status).to  eq("error")
      expect(@job.message).to eq("Failed to queue refresh")
    end
  end

  context "poll_refresh" do
    before do
      @job = described_class.create_job({})
      @job.state = 'refreshing'
    end

    it 'with a refresh task that is still running' do
      refresh_task = FactoryGirl.create(:miq_task)
      @job.context[:refresh_task_ids] = [refresh_task.id]

      expect(@job).to receive(:queue_signal).with(:poll_refresh, anything)

      @job.signal(:poll_refresh)
    end

    it 'with a refresh task that failed' do
      refresh_task = FactoryGirl.create(:miq_task, :status => MiqTask::STATUS_ERROR)
      @job.context[:refresh_task_ids] = [refresh_task.id]

      expect(@job).to receive(:queue_signal).with(:notify)

      @job.signal(:poll_refresh)

      expect(@job.status).to  eq("error")
      expect(@job.message).to eq("Refresh failed")
    end

    it 'with a refresh task that is still running' do
      refresh_task = FactoryGirl.create(:miq_task, :state => MiqTask::STATE_FINISHED)
      @job.context[:refresh_task_ids] = [refresh_task.id]

      expect(@job).to receive(:queue_signal).with(:notify)

      @job.signal(:poll_refresh)
    end
  end

  context "notify" do
    before do
      vm = FactoryGirl.create(:vm)

      options = {
        :target_id    => vm.id,
        :target_class => vm.class.name,
      }

      @job = described_class.create_job(options)
      @job.state = 'refreshing'
    end

    it 'with a successful job' do
      @job.status = "ok"

      expect(Notification).to receive(:create)
      @job.signal(:notify)
    end

    it 'with an unsuccessful job' do
      @job.status = "error"

      expect(Notification).to receive(:create)
      @job.signal(:notify)
    end
  end
end


text:
import React from 'react';
import { Router, Route } from 'react-router';

import Catalog from './pages/Catalog';
import Hamburger from './pages/Hamburger';
import HamburgerTouch from './pages/HamburgerTouch';
import Home from './pages/Home';
import Viewer from './pages/Viewer';

const Routes = (props) => (
    <Router {...props}>
        <Route path="/" component={Home} />
        <Route path="/Catalog*" component={Catalog} />
        <Route path="/Hamburger" component={Hamburger} />
        <Route path="/Hamburger/Touch" component={HamburgerTouch} />
        <Route path="/Viewer" component={Viewer} />
    </Router>
);

export default Routes;


text:
fail=0
i=0
MAX_ITER=1000
source version.sh

while [ $fail -ne 1 -a $i -lt $MAX_ITER ]
do
        java -Xbootclasspath/p:/home/mwdalton/java-taint/test/lib/jt-sql-mockobj-bootlib${VER}.jar -cp /home/mwdalton/java-taint/test/build/${VER}/common:/home/mwdalton/java-taint/test/build/${VER}/tests:/home/mwdalton/java-taint/test/build/${VER}/mockobj/sql $VER_FLAGS jtaint.DerbySqlTest -n 1024 -l 1024
        if [ $? -ne 0 ]
        then
                echo "FAILURE"
                fail=1
        else
                let "i++"
                echo "success: $i iterations"
        fi
done


text:
package google

import (
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

type (
	// Function handling for polling for a resource
	PollReadFunc func() (resp map[string]interface{}, respErr error)

	// Function to check the response from polling once
	PollCheckResponseFunc func(resp map[string]interface{}, respErr error) PollResult

	PollResult *resource.RetryError
)

// Helper functions to construct result of single pollRead as return result for a PollCheckResponseFunc
func ErrorPollResult(err error) PollResult {
	return resource.NonRetryableError(err)
}

func PendingStatusPollResult(status string) PollResult {
	return resource.RetryableError(fmt.Errorf("got pending status %q", status))
}

func SuccessPollResult() PollResult {
	return nil
}

func PollingWaitTime(pollF PollReadFunc, checkResponse PollCheckResponseFunc, activity string,
	timeout time.Duration, targetOccurrences int) error {
	log.Printf("[DEBUG] %s: Polling until expected state is read", activity)
	log.Printf("[DEBUG] Target occurrences: %d", targetOccurrences)
	if targetOccurrences == 1 {
		return resource.Retry(timeout, func() *resource.RetryError {
			readResp, readErr := pollF()
			return checkResponse(readResp, readErr)
		})
	}
	return RetryWithTargetOccurrences(timeout, targetOccurrences, func() *resource.RetryError {
		readResp, readErr := pollF()
		return checkResponse(readResp, readErr)
	})
}

// RetryWithTargetOccurrences is a basic wrapper around StateChangeConf that will retry
// a function until it returns the specified amount of target occurrences continuously.
// Adapted from the Retry function in the go SDK.
func RetryWithTargetOccurrences(timeout time.Duration, targetOccurrences int,
	f resource.RetryFunc) error {
	// These are used to pull the error out of the function; need a mutex to
	// avoid a data race.
	var resultErr error
	var resultErrMu sync.Mutex

	c := &resource.StateChangeConf{
		Pending:                   []string{"retryableerror"},
		Target:                    []string{"success"},
		Timeout:                   timeout,
		MinTimeout:                500 * time.Millisecond,
		ContinuousTargetOccurence: targetOccurrences,
		Refresh: func() (interface{}, string, error) {
			rerr := f()

			resultErrMu.Lock()
			defer resultErrMu.Unlock()

			if rerr == nil {
				resultErr = nil
				return 42, "success", nil
			}

			resultErr = rerr.Err

			if rerr.Retryable {
				return 42, "retryableerror", nil
			}
			return nil, "quit", rerr.Err
		},
	}

	_, waitErr := c.WaitForState()

	// Need to acquire the lock here to be able to avoid race using resultErr as
	// the return value
	resultErrMu.Lock()
	defer resultErrMu.Unlock()

	// resultErr may be nil because the wait timed out and resultErr was never
	// set; this is still an error
	if resultErr == nil {
		return waitErr
	}
	// resultErr takes precedence over waitErr if both are set because it is
	// more likely to be useful
	return resultErr
}

/**
 * Common PollCheckResponseFunc implementations
 */

// PollCheckForExistence waits for a successful response, continues polling on 404,
// and returns any other error.
func PollCheckForExistence(_ map[string]interface{}, respErr error) PollResult {
	if respErr != nil {
		if isGoogleApiErrorWithCode(respErr, 404) {
			return PendingStatusPollResult("not found")
		}
		return ErrorPollResult(respErr)
	}
	return SuccessPollResult()
}

// PollCheckForExistenceWith403 waits for a successful response, continues polling on 404 or 403,
// and returns any other error.
func PollCheckForExistenceWith403(_ map[string]interface{}, respErr error) PollResult {
	if respErr != nil {
		if isGoogleApiErrorWithCode(respErr, 404) || isGoogleApiErrorWithCode(respErr, 403) {
			return PendingStatusPollResult("not found")
		}
		return ErrorPollResult(respErr)
	}
	return SuccessPollResult()
}

// PollCheckForAbsence waits for a 404/403 response, continues polling on a successful
// response, and returns any other error.
func PollCheckForAbsenceWith403(_ map[string]interface{}, respErr error) PollResult {
	if respErr != nil {
		if isGoogleApiErrorWithCode(respErr, 404) || isGoogleApiErrorWithCode(respErr, 403) {
			return SuccessPollResult()
		}
		return ErrorPollResult(respErr)
	}
	return PendingStatusPollResult("found")
}

// PollCheckForAbsence waits for a 404 response, continues polling on a successful
// response, and returns any other error.
func PollCheckForAbsence(_ map[string]interface{}, respErr error) PollResult {
	if respErr != nil {
		if isGoogleApiErrorWithCode(respErr, 404) {
			return SuccessPollResult()
		}
		return ErrorPollResult(respErr)
	}
	return PendingStatusPollResult("found")
}


text:
source "content/en/docs/setup/upgrade/helm/common.sh"

set -e
set -u

set -o pipefail

# @setup profile=none

_install_istio_helm

snip_canary_upgrade_recommended_1
_rewrite_helm_repo snip_canary_upgrade_recommended_2
_wait_for_deployment istio-system istiod-canary

# shellcheck disable=SC2154
_verify_lines snip_canary_upgrade_recommended_3 "
+ default
+ canary
"

snip_canary_upgrade_recommended_4
_rewrite_helm_repo snip_canary_upgrade_recommended_5

_rewrite_helm_repo helm template istiod istio/istiod -s templates/revision-tags.yaml --set revisionTags="{prod-stable}" --set revision=1-9-5 -n istio-system | kubectl delete -f -
_rewrite_helm_repo helm template istiod istio/istiod -s templates/revision-tags.yaml --set revisionTags="{prod-canary}" --set revision=1-10-0 -n istio-system | kubectl delete -f -
helm uninstall istiod-canary -n istio-system
_remove_istio_helm

# @cleanup


text:
<?php

namespace Yoast\WP\SEO\Actions\Indexation;

use wpdb;
use Yoast\WP\SEO\Builders\Indexable_Link_Builder;
use Yoast\WP\SEO\Models\SEO_Links;
use Yoast\WP\SEO\Repositories\Indexable_Repository;

/**
 * Reindexation action for link indexables.
 */
abstract class Abstract_Link_Indexing_Action implements Indexation_Action_Interface {

	/**
	 * The transient name.
	 *
	 * @var string
	 */
	const UNINDEXED_COUNT_TRANSIENT = null;

	/**
	 * The link builder.
	 *
	 * @var Indexable_Link_Builder
	 */
	protected $link_builder;

	/**
	 * The indexable repository.
	 *
	 * @var Indexable_Repository
	 */
	protected $repository;

	/**
	 * The WordPress database instance.
	 *
	 * @var wpdb
	 */
	protected $wpdb;

	/**
	 * Indexable_Post_Indexing_Action constructor
	 *
	 * @param Indexable_Link_Builder $link_builder The indexable link builder.
	 * @param Indexable_Repository   $repository   The indexable repository.
	 * @param wpdb                   $wpdb         The WordPress database instance.
	 */
	public function __construct(
		Indexable_Link_Builder $link_builder,
		Indexable_Repository $repository,
		wpdb $wpdb
	) {
		$this->link_builder = $link_builder;
		$this->repository   = $repository;
		$this->wpdb         = $wpdb;
	}

	/**
	 * @inheritDoc
	 */
	public function get_total_unindexed() {
		$transient = \get_transient( static::UNINDEXED_COUNT_TRANSIENT );

		if ( $transient !== false ) {
			return (int) $transient;
		}

		$query = $this->get_query( true );

		$result = $this->wpdb->get_var( $query );

		if ( \is_null( $result ) ) {
			return false;
		}

		\set_transient( static::UNINDEXED_COUNT_TRANSIENT, $result, \DAY_IN_SECONDS );

		return (int) $result;
	}

	/**
	 * Creates indexables for unindexed objects.
	 *
	 * @return SEO_Links[] The created SEO links.
	 */
	public function index() {
		$objects = $this->get_objects();

		$indexables = [];
		foreach ( $objects as $object ) {
			$indexable = $this->repository->find_by_id_and_type( $object->id, $object->type );

			// It's possible the indexable was created without having it's links indexed.
			if ( $indexable->link_count === null ) {
				$this->link_builder->build( $indexable, $object->content );
				$indexable->save();
			}

			$indexables[] = $indexable;
		}

		\delete_transient( static::UNINDEXED_COUNT_TRANSIENT );

		return $indexables;
	}

	/**
	 * @inheritDoc
	 */
	public function get_limit() {
		/**
		 * Filter 'wpseo_link_indexing_limit' - Allow filtering the amount of texts indexed during each link indexing pass.
		 *
		 * @api int The maximum number of texts indexed.
		 */
		return \apply_filters( 'wpseo_link_indexing_limit', 5 );
	}

	/**
	 * Returns objects to be indexed.
	 *
	 * @return array Objects to be indexed, should be an array of objects with object_id, object_type and content.
	 */
	abstract protected function get_objects();

	/**
	 * Queries the database for unindexed term IDs.
	 *
	 * @param bool $count Whether or not it should be a count query.
	 * @param int  $limit The maximum amount of term IDs to return.
	 *
	 * @return string The query.
	 */
	abstract protected function get_query( $count, $limit = 1 );
}


text:
package shapeless
package syntax

import scala.annotation.tailrec

/**
 * Carrier for `HList` operations.
 *
 * These methods are implemented here and pimped onto the minimal `HList` types to avoid issues that would otherwise be
 * caused by the covariance of `::[H, T]`.
 *
 * @author Miles Sabin
 */
final class HListOps[L <: HList](l : L) {
  import ops.hlist._

  /**
   * Returns the head of this `HList`. Available only if there is evidence that this `HList` is composite.
   */
  def head(implicit c : IsHCons[L]) : c.H = c.head(l)

  /**
   * Returns the tail of this `HList`. Available only if there is evidence that this `HList` is composite.
   */
  def tail(implicit c : IsHCons[L]) : c.T = c.tail(l)

  /**
   * Prepend the argument element to this `HList`.
   */
  def ::[H](h : H) : H :: L = shapeless.::(h, l)

  /**
   * Prepend the argument element to this `HList`.
   */
  def +:[H](h : H) : H :: L = shapeless.::(h, l)

  /**
   * Append the argument element to this `HList`.
   */
  def :+[T](t : T)(implicit prepend : Prepend[L, T :: HNil]) : prepend.Out = prepend(l, t :: HNil)

  /**
   * Append the argument `HList` to this `HList`.
   */
  def ++[S <: HList](suffix : S)(implicit prepend : Prepend[L, S]) : prepend.Out = prepend(l, suffix)

  /**
   * Prepend the argument `HList` to this `HList`.
   */
  def ++:[P <: HList](prefix : P)(implicit prepend : Prepend[P, L]) : prepend.Out = prepend(prefix, l)

  /**
   * Prepend the argument `HList` to this `HList`.
   */
  def :::[P <: HList](prefix : P)(implicit prepend : Prepend[P, L]) : prepend.Out = prepend(prefix, l)

  /**
   * Prepend the reverse of the argument `HList` to this `HList`.
   */
  def reverse_:::[P <: HList](prefix : P)(implicit prepend : ReversePrepend[P, L]) : prepend.Out = prepend(prefix, l)

  /**
   * Returns the ''nth'' element of this `HList`. An explicit type argument must be provided. Available only if there is
   * evidence that this `HList` has at least ''n'' elements.
   */
  def apply[N <: Nat](implicit at : At[L, N]) : at.Out = at(l)

  /**
   * Returns the ''nth'' element of this `HList`. Available only if there is evidence that this `HList` has at least ''n''
   * elements.
   */
  def apply(n : Nat)(implicit at : At[L, n.N]) : at.Out = at(l)

  /**
   * Returns the ''nth'' element of this `HList`. An explicit type argument must be provided. Available only if there is
   * evidence that this `HList` has at least ''n'' elements.
   */
  def at[N <: Nat](implicit at : At[L, N]) : at.Out = at(l)

  /**
   * Returns the ''nth'' element of this `HList`. Available only if there is evidence that this `HList` has at least ''n''
   * elements.
   */
  def at(n : Nat)(implicit at : At[L, n.N]) : at.Out = at(l)

  /**
   * Returns the last element of this `HList`. Available only if there is evidence that this `HList` is composite.
   */
  def last(implicit last : Last[L]) : last.Out = last(l)

  /**
   * Returns an `HList` consisting of all the elements of this `HList` except the last. Available only if there is
   * evidence that this `HList` is composite.
   */
  def init(implicit init : Init[L]) : init.Out = init(l)

  /**
   * Returns the first element of type `U` of this `HList`. An explicit type argument must be provided. Available only
   * if there is evidence that this `HList` has an element of type `U`.
   */
  def select[U](implicit selector : Selector[L, U]) : U = selector(l)

  /**
   * Returns all elements of type `U` of this `HList`. An explicit type argument must be provided.
   */
  def filter[U](implicit filter : Filter[L, U]) : filter.Out  = filter(l)

  /**
   * Returns all elements of type different than `U` of this `HList`. An explicit type argument must be provided.
   */
  def filterNot[U](implicit filter : FilterNot[L, U]) : filter.Out  = filter(l)

  /**
   * Returns the first element of type `U` of this `HList` plus the remainder of the `HList`. An explicit type argument
   * must be provided. Available only if there is evidence that this `HList` has an element of type `U`.
   *
   * The `Elem` suffix is here to avoid creating an ambiguity with RecordOps#remove and should be removed if
   * SI-5414 is resolved in a way which eliminates the ambiguity.
   */
  def removeElem[U](implicit remove : Remove[L, U]): remove.Out = remove(l)

  /**
   * Returns the first elements of this `HList` that have types in `SL` plus the remainder of the `HList`. An expicit
   * type argument must be provided. Available only if there is evidence that this `HList` contains elements with
   * types in `SL`.
   */
  def removeAll[SL <: HList](implicit removeAll : RemoveAll[L, SL]): removeAll.Out = removeAll(l)

  /**
   * Replaces the first element of type `U` of this `HList` with the supplied value, also of type `U` returning both
   * the replaced element and the updated `HList`. Available only if there is evidence that this `HList` has an element
   * of type `U`.
   */
  def replace[U](u : U)(implicit replacer : Replacer[L, U, U]): replacer.Out = replacer(l, u)

  class ReplaceTypeAux[U] {
    def apply[V](v : V)(implicit replacer : Replacer[L, U, V]): replacer.Out = replacer(l, v)
  }

  /**
   * Replaces the first element of type `U` of this `HList` with the supplied value of type `V`, returning both the
   * replaced element and the updated `HList`. An explicit type argument must be provided for `U`. Available only if
   * there is evidence that this `HList` has an element of type `U`.
   */
  def replaceType[U] = new ReplaceTypeAux[U]

  /**
   * Replaces the first element of type `U` of this `HList` with the supplied value, also of type `U`. Available only
   * if there is evidence that this `HList` has an element of type `U`.
   *
   * The `Elem` suffix is here to avoid creating an ambiguity with RecordOps#updated and should be removed if
   * SI-5414 is resolved in a way which eliminates the ambiguity.
   */
  def updatedElem[U, Out <: HList](u : U)
    (implicit replacer : Replacer.Aux[L, U, U, (U, Out)]) : Out = replacer(l, u)._2

  class UpdatedTypeAux[U] {
    def apply[V, Out <: HList](v : V)
      (implicit replacer : Replacer.Aux[L, U, V, (U, Out)]) : Out = replacer(l, v)._2
  }

  /**
   * Replaces the first element of type `U` of this `HList` with the supplied value of type `V`. An explicit type
   * argument must be provided for `U`. Available only if there is evidence that this `HList` has an element of
   * type `U`.
   */
  def updatedType[U] = new UpdatedTypeAux[U]

  class UpdatedAtAux[N <: Nat] {
    def apply[U, V, Out <: HList](u : U)(implicit replacer : ReplaceAt.Aux[L, N, U, (V, Out)]) : Out = replacer(l, u)._2
  }

  /**
   * Replaces the ''nth' element of this `HList` with the supplied value of type `U`. An explicit type argument
   * must be provided for `N`. Available only if there is evidence that this `HList` has at least ''n'' elements.
   */
  def updatedAt[N <: Nat] = new UpdatedAtAux[N]

  /**
   * Replaces the ''nth' element of this `HList` with the supplied value of type `U`. Available only if there is
   * evidence that this `HList` has at least ''n'' elements.
   */
  def updatedAt[U, V, Out <: HList](n: Nat, u : U)(implicit replacer : ReplaceAt.Aux[L, n.N, U, (V, Out)]) : Out = replacer(l, u)._2

  /**
   * Returns the first ''n'' elements of this `HList`. An explicit type argument must be provided. Available only if
   * there is evidence that this `HList` has at least ''n'' elements.
   */
  def take[N <: Nat](implicit take : Take[L, N]) : take.Out = take(l)

  /**
   * Returns the first ''n'' elements of this `HList`. Available only if there is evidence that this `HList` has at
   * least ''n'' elements.
   */
  def take(n : Nat)(implicit take : Take[L, n.N]) : take.Out = take(l)

  /**
   * Returns all but the  first ''n'' elements of this `HList`. An explicit type argument must be provided. Available
   * only if there is evidence that this `HList` has at least ''n'' elements.
   */
  def drop[N <: Nat](implicit drop : Drop[L, N]) : drop.Out = drop(l)

  /**
   * Returns all but the  first ''n'' elements of this `HList`. Available only if there is evidence that this `HList`
   * has at least ''n'' elements.
   */
  def drop(n : Nat)(implicit drop : Drop[L, n.N]) : drop.Out = drop(l)

  /**
   * Splits this `HList` at the ''nth'' element, returning the prefix and suffix as a pair. An explicit type argument
   * must be provided. Available only if there is evidence that this `HList` has at least ''n'' elements.
   */
  def split[N <: Nat](implicit split : Split[L, N]) : split.Out = split(l)

  /**
   * Splits this `HList` at the ''nth'' element, returning the prefix and suffix as a pair. Available only if there is
   * evidence that this `HList` has at least ''n'' elements.
   */
  def split(n : Nat)(implicit split : Split[L, n.N]) : split.Out = split(l)

  /**
   * Splits this `HList` at the ''nth'' element, returning the reverse of the prefix and suffix as a pair. An explicit
   * type argument must be provided. Available only if there is evidence that this `HList` has at least ''n'' elements.
   */
  def reverse_split[N <: Nat](implicit split : ReverseSplit[L, N]) : split.Out = split(l)

  /**
   * Splits this `HList` at the ''nth'' element, returning the reverse of the prefix and suffix as a pair. Available
   * only if there is evidence that this `HList` has at least ''n'' elements.
   */
  def reverse_split(n : Nat)(implicit split : ReverseSplit[L, n.N]) : split.Out = split(l)

  /**
   * Splits this `HList` at the first occurrence of an element of type `U`, returning the prefix and suffix as a pair.
   * An explicit type argument must be provided. Available only if there is evidence that this `HList` has an element
   * of type `U`.
   */
  def splitLeft[U](implicit splitLeft : SplitLeft[L, U]) : splitLeft.Out = splitLeft(l)

  /**
   * Splits this `HList` at the first occurrence of an element of type `U`, returning reverse of the prefix and suffix
   * as a pair. An explicit type argument must be provided. Available only if there is evidence that this `HList` has
   * an element of type `U`.
   */
  def reverse_splitLeft[U](implicit splitLeft : ReverseSplitLeft[L, U]) : splitLeft.Out = splitLeft(l)

  /**
   * Splits this `HList` at the last occurrence of an element of type `U`, returning the prefix and suffix as a pair.
   * An explicit type argument must be provided. Available only if there is evidence that this `HList` has an element
   * of type `U`.
   */
  def splitRight[U](implicit splitRight : SplitRight[L, U]) : splitRight.Out = splitRight(l)

  /**
   * Splits this `HList` at the last occurrence of an element of type `U`, returning reverse of the prefix and suffix
   * as a pair. An explicit type argument must be provided. Available only if there is evidence that this `HList` has
   * an element of type `U`.
   */
  def reverse_splitRight[U](implicit splitRight : ReverseSplitRight[L, U]) : splitRight.Out = splitRight(l)

  /**
   * Permutes this `HList` into the same order as another `HList`. An explicit type argument must be supplied.
   * Available only if both `HList`s have elements of the same types.
   */
  def align[M <: HList](implicit align: Align[L, M]): M = align(l)

  /**
   * Permutes this `HList` into the same order as the supplied `HList` with the same element types. Available only if
   * both `HList`s have elements of the same types.
   */
  def align[M <: HList](m: M)(implicit align: Align[L, M]): M = align(l)

  /**
   * Reverses this `HList`.
   */
  def reverse(implicit reverse : Reverse[L]) : reverse.Out = reverse(l)

  /**
   * Maps a higher rank function across this `HList`.
   */
  def map(f : Poly)(implicit mapper : Mapper[f.type, L]) : mapper.Out = mapper(l)

  /**
   * Flatmaps a higher rank function across this `HList`.
   */
  def flatMap(f : Poly)(implicit mapper : FlatMapper[f.type, L]) : mapper.Out = mapper(l)

  /**
   * Replaces each element of this `HList` with a constant value.
   */
  def mapConst[C](c : C)(implicit mapper : ConstMapper[C, L]) : mapper.Out = mapper(c, l)

  /**
   * Maps a higher rank function ''f'' across this `HList` and folds the result using monomorphic combining operator
   * `op`. Available only if there is evidence that the result type of `f` at each element conforms to the argument
   * type of ''op''.
   */
  def foldMap[R](z : R)(f : Poly)(op : (R, R) => R)(implicit folder : MapFolder[L, R, f.type]) : R = folder(l, z, op)

  /**
   * Computes a left fold over this `HList` using the polymorphic binary combining operator `op`. Available only if
   * there is evidence `op` can consume/produce all the partial results of the appropriate types.
   */
  def foldLeft[R](z : R)(op : Poly)(implicit folder : LeftFolder[L, R, op.type]) : folder.Out = folder(l, z)

  /**
   * Computes a right fold over this `HList` using the polymorphic binary combining operator `op`. Available only if
   * there is evidence `op` can consume/produce all the partial results of the appropriate types.
   */
  def foldRight[R](z : R)(op : Poly)(implicit folder : RightFolder[L, R, op.type]) : folder.Out = folder(l, z)

  /**
   * Computes a left reduce over this `HList` using the polymorphic binary combining operator `op`. Available only if
   * there is evidence that this `HList` has at least one element and that `op` can consume/produce all the partial
   * results of the appropriate types.
   */
  def reduceLeft(op : Poly)(implicit reducer : LeftReducer[L, op.type]) : reducer.Out = reducer(l)

  /**
   * Computes a right reduce over this `HList` using the polymorphic binary combining operator `op`. Available only if
   * there is evidence that this `HList` has at least one element and that `op` can consume/produce all the partial
   * results of the appropriate types.
   */
  def reduceRight(op : Poly)(implicit reducer : RightReducer[L, op.type]) : reducer.Out = reducer(l)

  /**
   * Zips this `HList` with its argument `HList` returning an `HList` of pairs.
   */
  def zip[R <: HList](r : R)(implicit zipper : Zip[L :: R :: HNil]) : zipper.Out = zipper(l :: r :: HNil)

  /**
   * Zips this `HList` of monomorphic function values with its argument `HList` of correspondingly typed function
   * arguments returning the result of each application as an `HList`. Available only if there is evidence that the
   * corresponding function and argument elements have compatible types.
   */
  def zipApply[A <: HList](a : A)(implicit zipper : ZipApply[L, A]) : zipper.Out = zipper(l, a)

  /**
   * Zips this `HList` of `HList`s returning an `HList` of tuples. Available only if there is evidence that this
   * `HList` has `HList` elements.
   */
  def zip(implicit zipper : Zip[L]) : zipper.Out = zipper(l)

  /**
   * Zips this `HList` of `HList`s returning an `HList` of tuples. Available only if there is evidence that this
   * `HList` has `HList` elements.
   */
  @deprecated("Use zip instead", "2.0.0")
  def zipped(implicit zipper : Zip[L]) : zipper.Out = zipper(l)

  /**
   * Unzips this `HList` of tuples returning a tuple of `HList`s. Available only if there is evidence that this
   * `HList` has tuple elements.
   */
  def unzip(implicit unzipper : Unzip[L]) : unzipper.Out = unzipper(l)

  /**
   * Unzips this `HList` of tuples returning a tuple of `HList`s. Available only if there is evidence that this
   * `HList` has tuple elements.
   */
  @deprecated("Use unzip instead", "2.0.0")
  def unzipped(implicit unzipper : Unzip[L]) : unzipper.Out = unzipper(l)

  /**
   * Zips this `HList` with its argument `HList` of `HList`s, returning an `HList` of `HList`s with each element of
   * this `HList` prepended to the corresponding `HList` element of the argument `HList`.
   */
  def zipOne[T <: HList](t : T)(implicit zipOne : ZipOne[L, T]) : zipOne.Out = zipOne(l, t)

  /**
   * Zips this `HList` with a constant, resulting in an `HList` of tuples of the form
   * ({element from this `HList`}, {supplied constant})
   */
  def zipConst[C](c: C)(implicit zipConst: ZipConst[C, L]): zipConst.Out = zipConst(c, l)

  /**
   * Zips this 'HList' with its argument 'HList' using argument 'Poly2', returning an 'HList'.
   * Doesn't require this to be the same length as its 'HList' argument, but does require evidence that its
   * 'Poly2' argument is defined at their intersection.
   */
  def zipWith[R <: HList, P <: Poly2](r: R)(p: P)(implicit zipWith: ZipWith[L, R, P]): zipWith.Out =
    zipWith(l, r)

  /**
   * Transposes this `HList`.
   */
  def transpose(implicit transpose : Transposer[L]) : transpose.Out = transpose(l)

  /**
   * Returns an `HList` typed as a repetition of the least upper bound of the types of the elements of this `HList`.
   */
  def unify(implicit unifier : Unifier[L]) : unifier.Out = unifier(l)

  /**
   * Returns an `HList` with all elements that are subtypes of `B` typed as `B`.
   */
  def unifySubtypes[B](implicit subtypeUnifier : SubtypeUnifier[L, B]) : subtypeUnifier.Out = subtypeUnifier(l)

  /**
   * Converts this `HList` to a correspondingly typed tuple.
   */
  def tupled(implicit tupler : Tupler[L]) : tupler.Out = tupler(l)

  /**
   * Compute the length of this `HList`.
   */
  def length(implicit length : Length[L]) : length.Out = length()

  /**
   * Compute the length of this `HList` as a runtime Int value.
   */
  def runtimeLength: Int = {
    @tailrec def loop(l: HList, acc: Int): Int = l match {
      case HNil => acc
      case hd :: tl => loop(tl, acc+1)
    }

    loop(l, 0)
  }

  /**
   * Converts this `HList` to an ordinary `List` of elements typed as the least upper bound of the types of the elements
   * of this `HList`.
   */
  def toList[Lub](implicit toList : ToList[L, Lub]) : List[Lub] = toList(l)

  /**
   * Converts this `HList` to an `Array` of elements typed as the least upper bound of the types of the elements
   * of this `HList`.
   *
   * It is advisable to specify the type parameter explicitly, because for many reference types, case classes in
   * particular, the inferred type will be too precise (ie. `Product with Serializable with CC` for a typical case class
   * `CC`) which interacts badly with the invariance of `Array`s.
   */
  def toArray[Lub](implicit toArray : ToArray[L, Lub]) : Array[Lub] = toArray(runtimeLength, l, 0)

  /**
   * Converts this `HList` of values into a record with the provided keys.
   */
  def zipWithKeys[K <: HList](keys: K)(implicit withKeys: ZipWithKeys[K, L]): withKeys.Out = withKeys(keys, l)
}


text:
function getIsAdmin ( )
{

    // Obtain an XMLHttpRequest instance
    var req = newXMLHttpRequest();

    // Set the handler function to receive callback notifications
    // from the request object
    var handlerFunction = getReadyStateHandler(req, parseIsAdmin );
    req.onreadystatechange = handlerFunction;

    // Open an HTTP POST connection to the shopping cart servlet.
    // Third parameter specifies request is asynchronous.
    req.open("POST", "AuthenticationServlet" , true );

    // Specify that the body of the request contains form data
    req.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");

    var parameterToSend ="isAdmin=get" ;

    req.send( parameterToSend  );

}
function logout ()
{
    // Obtain an XMLHttpRequest instance
    var req = newXMLHttpRequest();

    // Set the handler function to receive callback notifications
    // from the request object
    var handlerFunction = getReadyStateHandler(req, parselogOut );
    req.onreadystatechange = handlerFunction;

    // Open an HTTP POST connection to the shopping cart servlet.
    // Third parameter specifies request is asynchronous.
    req.open("POST", "AuthenticationServlet", true );

    // Specify that the body of the request contains form data
    req.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");

    var parameterToSend ="logout=yes" ;

    req.send( parameterToSend  );
}
function parselogOut(resultXML )
{

    window.location = 'index.html?refresh=true';
    isAdmin = false ;
}

function parseIsAdmin(resultXML )
{
    var messageResult 	=  resultXML.getElementsByTagName("response")[0] ;
    var isAuthenticated = messageResult.getAttribute("isAuthenticated");
    var page = messageResult.getAttribute("page");
    var numResByPage =  messageResult.getAttribute("numberResultByPage");
    var company      =  messageResult.getAttribute("company");
    var ip           = messageResult.getAttribute("ip") ;

    if ( page != "null" ) currentPage  = page        ;
    if ( numResByPage != "null" ) nbByPage = numResByPage      ;

    if (  isAuthenticated == "true" )
    {
        isAdmin = true ;
    }
    else
    {
        isAdmin = false ;
    }

    if ( ip != "" && !isAdmin )
    {
        ipOfClient = ip ;
    }
    else if ( isAdmin )
    {
        ipOfClient = "" ;
    }

    init_() ;
    if ( company == "Unknown" )
    {
        dd.elements.modalCompanyName.show(true);

    }

}

function replaceIPEmail ( name , email )
{

    if ( checkMail(email) )
    {
        // Obtain an XMLHttpRequest instance
        var req = newXMLHttpRequest();

        // Set the handler function to receive callback notifications
        // from the request object
        var handlerFunction = getReadyStateHandler(req, replaceIPResult );
        req.onreadystatechange = handlerFunction;

        // Open an HTTP POST connection to the shopping cart servlet.
        // Third parameter specifies request is asynchronous.
        req.open("Get", "AuthenticationServlet?company="+ escape(name) + "&email=" + escape(email) , true );

        // Specify that the body of the request contains form data
        req.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded");
        req.send( null ) ;
    }
}
function replaceIPResult ( resultXML )
{
    dd.elements.modalCompanyName.hide(true);
}


text:
import Reflux from "reflux";

import Queries from "../api/Queries";
import Commands from "../api/Commands";

import TicketActions from "./TicketActions";
import {sugarDocument} from "../util/document";

var TicketStore = Reflux.createStore({
	listenables: [TicketActions],
	getInitialState() {
		this.ticket = {};
		return this.ticket;
	},
	onChangeTitle(ticket, newTitle) {
		ticket.title = newTitle;
		this.trigger(this.ticket);
	},
	onChangeDescription(ticket, description) {
		ticket.description = description;
		Commands({
			type: "ChangeDocumentAttributes",
			aggregateId: ticket.id,
			attributeChanges: [
				{
					attribute: "description",
					newValue: ticket.description
				}
			]
		});
		this.ticket = ticket;
		this.trigger(this.ticket);
	},
	onLoadTicket(ticketNumber) {
		Queries.getDocuments({kind: "ticket", number: ticketNumber}).then(result => {
			this.ticket = sugarDocument(result.documents[0]);
			this.trigger(this.ticket);
		});
	}
});

//module.exports = TicketStore;
export default TicketStore;