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

	FILE: gui.lua
	DESCRIPTION: The managing class for the gui system
	AUTHOR: Derick Dong
	VERSION: 0.1
	MOAI VERSION: 0.7
	CREATED: 9-9-11

	UPDATED: 5-5-12
	VERSION: 0.2
	MOAI VERSION: v1.0 r3

	Changes
	- Changed function _calcInputOver to use MOAIPartition:propListForPoint instead of MOAIPartition:propForPoint.
	  Now, windows that are set to be hidden will not accept input.
]]

local _M = {}

require "gui/support/class"

local resources = require "gui/support/resources"
local filesystem = require "gui/support/filesystem"

local array = require "gui/support/array"
local aevent = require "gui/aevent"
local factory = require "gui/factory"
local layoutparser = require "gui/layoutparser"
local theme = require "gui/theme"
local fonts = require "gui/fonts"
local textstyles = require "gui/textstyles"
local textures = require "gui/textures"

local constants = require "gui/guiconstants"

local eventtypes = require "gui/support/eventtypes"

_M.GUI = class()

local GUI_PRIORITY = 0
local BASE_PRIORITY = 0
local RESOURCE_GROUP = nil

function _M.GUI:_calcAbsValue(x, y)
	x = (x / 100.0) * self._width
	y = (y / 100.0) * self._height

	return x, y
end

function _M.GUI:_calcRelValue(x, y)
	x = (x * 100.0) / self._width
	y = (y * 100.0) / self._height

	return x, y
end

function _M.GUI:_createGUILayer(width, height)
	local layer = MOAILayer.new()

	local viewport = MOAIViewport.new()
	viewport:setSize(width, height)
	viewport:setScale(width, height)
	viewport:setOffset(-1, 1)
	layer:setViewport(viewport)

	local partition = MOAIPartition.new()
	layer:setPartition(partition)

	self._partition = partition
	self._layer = layer
	self._viewport = viewport
end

function _M.GUI:_registerHitObject(widget, prop)
	self._propToWindow[prop] = widget
end

function _M.GUI:_unregisterHitObject(prop)
	self._propToWindow[prop] = nil
end

function _M.GUI:_createProp(priority)
	priority = (priority or BASE_PRIORITY)

	local prop = MOAIProp.new()

	prop:setPriority(priority)
	prop:setLoc(0, 0)
	prop:setScl(1, 1)

	self:partition():insertProp(prop)

	return prop
end

function _M.GUI:_createQuad()
	local quad = MOAIGfxQuad2D.new()

	return quad
end

function _M.GUI:_destroyProp(prop)
	prop:setDeck(nil)
	self:partition():removeProp(prop)
end

function _M.GUI:_createMouseButtonEvent(eventType, x, y, button, down)
	local event = aevent.AEvent(eventType)

	event.x = x
	event.y = y
	event.button = button
	event.down = down

	return event
end

function _M.GUI:_createMouseMoveEvent(currX, currY, prevX, prevY)
	local event = aevent.AEvent(constants.GUI_MOUSE_MOVE)

	event.x = currX
	event.y = currY
	event.prevX = prevX
	event.prevY = prevY

	return event
end

function _M.GUI:_createMouseClickEvent(x, y, button)
	local event = aevent.AEvent(constants.GUI_MOUSE_CLICK)

	event.x = x
	event.y = y
	event.button = button

	return event
end

function _M.GUI:_createMouseEntersEvent()
	local event = aevent.AEvent(constants.GUI_MOUSE_ENTERS)

	return event
end

function _M.GUI:_createMouseLeavesEvent()
	local event = aevent.AEvent(constants.GUI_MOUSE_LEAVES)

	return event
end

function _M.GUI:_createKeyUpEvent(key)
	local event = aevent.AEvent(constants.GUI_KEY_UP)

	event.key = key

	return event
end

function _M.GUI:_createKeyDownEvent(key)
	local event = aevent.AEvent(constants.GUI_KEY_DOWN)

	event.key = key

	return event
end

function _M.GUI:_createTouchUpEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_UP)

	return event
end

function _M.GUI:_createTouchDownEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_DOWN)

	return event
end

function _M.GUI:_createTouchMoveEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_MOVE)

	return event
end

function _M.GUI:_createTouchTapEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_TAP)

	return event
end

function _M.GUI:_createTouchEntersEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_ENTERS)

	return event
end

function _M.GUI:_createTouchLeavesEvent()
	local event = aevent.AEvent(constants.GUI_TOUCH_LEAVES)

	return event
end

function _M.GUI:_createButtonEvent()
	local event = aevent.AEvent(constants.GUI_BUTTON)

	return event
end

function _M.GUI:_createMotionEvent()
	local event = aevent.AEvent(constants.GUI_MOTION)

	return event
end

function _M.GUI:_createGainFocusEvent(widget)
	local event = aevent.AEvent(constants.GUI_GAIN_FOCUS)
	event.widget = widget

	return event
end

function _M.GUI:_createLoseFocusEvent(widget)
	local event = aevent.AEvent(constants.GUI_LOSE_FOCUS)
	event.widget = widget

	return event
end

function _M.GUI:viewport()
	return self._viewport
end

function _M.GUI:partition()
	return self._partition
end

function _M.GUI:layer()
	return self._layer
end

function _M.GUI:_calcInputOver(x, y)
	local inputX, inputY = self._layer:wndToWorld(x, y)

	local props = {self._partition:propListForPoint(inputX, inputY, 0, MOAILayer.SORT_PRIORITY_DESCENDING)}
	if (nil == props or #props == 0) then return nil end

	for i, v in ipairs(props) do
		local win = self._propToWindow[v]
		if (nil ~= win) then
			if (true == win:getVisible()) then
				return win
			end
		end
	end

	return nil
end

function _M.GUI:_handleMouseOverWidget(widget)
	if (widget ~= self._over) then
		if (nil ~= self._over) then
			local event = self:_createMouseLeavesEvent()
			self._over:_handleMouseLeaves(event)
		end

		if (nil ~= widget) then
			local event = self:_createMouseEntersEvent()
			widget:_handleMouseEnters(event)
		end

		self:setOver(widget)
	end
end

function _M.GUI:_handleTouchOverWidget(widget)
	if (widget ~= self._over) then
		if (nil ~= self._over) then
			self._over:_handleTouchLeaves()
		end

		if (nil ~= widget) then
			widget:_handleTouchEnters()
		end

		self:setOver(widget)
	end
end

function _M.GUI:setFocus(win)
	if (nil == win) then
		if (nil ~= self._focus) then
			local event = self:_createLoseFocusEvent(self._focus)
			self._focus:_handleLoseFocus(event)
		end

		self._focus = nil
		return
	end

	if (self._focus ~= win) then
		local prev = self._focus
		self._focus = win

		local event = self:_createGainFocusEvent(win)
		self._focus:_handleGainFocus(event)

		if (nil ~= prev) then
			local event = self:_createLoseFocusEvent(win)
			prev:_handleLoseFocus(event)
		end
	end
end

function _M.GUI:getFocus()
	return self._focus
end

function _M.GUI:setOver(win)
	if (nil == win) then
		if (nil ~= self._over) then
			for k, v in pairs(self._mouseButtonsDown) do
				if (v == win) then
					self._mouseButtonsDown[k] = nil
					break
				end
			end
		end

		self._over = nil
		return
	end

	self._over = win
end

function _M.GUI:getOver()
	return self._over
end

function _M.GUI:moveToFront(win)
	local top = BASE_PRIORITY
	for k, v in pairs(self._windows) do
		top = math.max(top, v:getPriority())
	end

	win:_setPriority(top + 5)
end

function _M.GUI:moveToBack(win)
	for k, v in pairs(self._windows) do
		v:_setPriority(v:getPriority() + 1)
	end

	win:_setPriority(BASE_PRIORITY)
end

function _M.GUI:injectKeyDown(key)
	self._keysDown[key] = true

	local result = false
	local event = self:_createKeyDownEvent(key)
	if (nil ~= self._focus) then
		result = self._focus:_handleKeyDown(event)
	end

	return result
end

function _M.GUI:injectKeyUp(key)
	table.remove(self._keysDown, key)

	local result = false
	local event = self:_createKeyUpEvent(key)
	if (nil ~= self._focus) then
		result = self._focus:_handleKeyUp(event)
	end

	return result
end

function _M.GUI:injectMouseMove(newX, newY)
	self._prevMouseX = self._currMouseX
	self._prevMouseY = self._currMouseY
	self._currMouseX = newX
	self._currMouseY = newY

	local widget = self:_calcInputOver(newX, newY)
	self:_handleMouseOverWidget(widget)

	local result = false
	local event = self:_createMouseMoveEvent(self._currMouseX, self._currMouseY, self._prevMouseX, self._prevMouseY)
	if (nil ~= widget) then
		result = widget:_handleMouseMove(event)
	end

	if (widget ~= self._focus and nil ~= self._focus) then
		result = self._focus:_handleMouseMove(event)
	end

	return result
end

function _M.GUI:injectMouseButtonDown(button)
	self._mouseButtonsDown[button] = self._over

	self:setFocus(self._over)

	local result = false
	if (nil ~= self._focus) then
		local event = self:_createMouseButtonEvent(constants.GUI_MOUSE_BUTTON_DOWN, self._currMouseX, self._currMouseY, button, true)
		result = self._focus:_handleMouseDown(event)
	end

	return result
end

function _M.GUI:injectMouseButtonUp(button)
	local result = false
	if (nil ~= self._mouseButtonsDown[button]) then
		local event = self:_createMouseButtonEvent(constants.GUI_MOUSE_BUTTON_UP, self._currMouseX, self._currMouseY, button, false)
		self._mouseButtonsDown[button]:_handleMouseUp(event)
		if (self._mouseButtonsDown[button] == self._over) then
			local event = self:_createMouseClickEvent(self._currMouseX, self._currMouseY, button)
			result = self._over:_handleMouseClick(event)
		end
	end

	self._mouseButtonsDown[button] = nil

	return result
end

function _M.GUI:injectTouch(eventType, idx, x, y, tapCount)
	local newTouch = {}

	newTouch.type = eventType
	newTouch.x = x
	newTouch.y = y
	newTouch.tapCount = tapCount

	if (touches[idx] ~= nil) then
		newTouch.prevX = touches[idx].x
		newTouch.prevY = touches[idx].y
	end

	self._touches[idx] = newTouch

	local widget = self:_calcInputOver(x, y)
	return self:_handleTouchOverWidget(widget)
end

function _M.GUI:injectButton()

end

function _M.GUI:injectMotion()

end

function _M.GUI:_addWindow(w)
	self._windows[#self._windows + 1] = w
	self:moveToFront(w)
end

function _M.GUI:createWindow(...)
	local w = self._factory:create("window", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createLabel(...)
	local w = self._factory:create("label", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createImage(...)
	local w = self._factory:create("image", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createButton(...)
	local w = self._factory:create("button", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createCheckBox(...)
	local w = self._factory:create("check box", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createRadioButton(...)
	local w = self._factory:create("radio button", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createEditBox(...)
	local w = self._factory:create("edit box", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createVertSlider(...)
	local w = self._factory:create("vert slider", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createHorzSlider(...)
	local w = self._factory:create("horz slider", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createVertScrollBar(...)
	local w = self._factory:create("vert scroll bar", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createHorzScrollBar(...)
	local w = self._factory:create("horz scroll bar", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createProgressBar(...)
	local w = self._factory:create("progress bar", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createTextBox(...)
	local w = self._factory:create("text box", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:createWidgetList(...)
	local w = self._factory:create("widget list", ...)

	self:_addWindow(w)

	return w
end

function _M.GUI:destroyWindow(win)
	win:destroy()

	array.removeElement(self._windows, win)
end

function _M.GUI:addToResourcePath(path, priority)
	resources.addToPath(path, RESOURCE_GROUP, priority)
end

function _M.GUI:setTheme(fileName)
	fileName = resources.getPath(fileName, RESOURCE_GROUP)
	if (nil == fileName) then
		return
	end

	local t = self._themes[fileName]
	if (nil == t) then
		t = theme.Theme(fileName)
		self._themes[fileName] = t
	end

	self._currTheme = fileName
	self._factory:setTheme(t)
end

function _M.GUI:setCurrTextStyle(name)
	local style = textstyles.get(name)
	if (nil == style) then
		return
	end

	self._currTextStyle = name
	self._factory:setCurrTextStyle(style)
end

function _M.GUI:loadLayout(fileName, prefix, parent, params)
	return self._layoutParser:createFromLayout(fileName, prefix, parent, params)
end

function _M.GUI:_handleMouseMove(event, params)
	return self:injectMouseMove(event.x, event.y)
end

function _M.GUI:_handleMouseButtonDown(event, params)
	return self:injectMouseButtonDown(event.button)
end

function _M.GUI:_handleMouseButtonUp(event, params)
	return self:injectMouseButtonUp(event.button)
end

function _M.GUI:_handleKeyDown(event, params)
	return self:injectKeyDown(event.key)
end

function _M.GUI:_handleKeyUp(event, params)
	return self:injectKeyUp(event.key)
end

function _M.GUI:registerEvents(obj, func)
	obj[func](obj, eventtypes.MOUSE_MOVE, "gui", GUI_PRIORITY, self, "_handleMouseMove")
	obj[func](obj, eventtypes.MOUSE_BUTTON_DOWN, "gui", GUI_PRIORITY, self, "_handleMouseButtonDown")
	obj[func](obj, eventtypes.MOUSE_BUTTON_UP, "gui", GUI_PRIORITY, self, "_handleMouseButtonUp")
	obj[func](obj, eventtypes.KEY_DOWN, "gui", GUI_PRIORITY, self, "_handleKeyDown")
	obj[func](obj, eventtypes.KEY_UP, "gui", GUI_PRIORITY, self, "_handleKeyUp")
end

function _M.GUI:shutdown()
	textures.releaseAll()
	fonts.releaseAll()
	textstyles.releaseAll()

	for k, v in pairs(self._windows) do
		v:destroy()
	end
end

function _M.GUI:init(width, height)
	self._width = width
	self._height = height

	self._windows = {}
	self._propToWindow = {}

	self._focus = nil
	self._over = nil
	self._dragging = nil

	self._keysDown = {}
	self._currMouseX = 0
	self._currMouseY = 0
	self._prevMouseX = 0
	self._prevMouseY = 0
	self._mouseButtonsDown = {}
	self._touches = {}

	self._themes = {}
	self._currTheme = nil
	self._currFont = nil
	self._factory = factory.Factory(self)
	self._layoutParser = layoutparser.LayoutParser(self._factory)

	self:_createGUILayer(width, height)
end

return _M


text:
import 'app/main.sass';
import _ from 'lodash';

// Add mixin for lodash
_.mixin({
    mergeNotNull: (object, ...sources) => {
        // Convert all nulls to undefined
        const newSources = sources.map(source => _.mapValues(source, value => _.isNull(value) ? undefined : value));
        // Run a regular merge
        _.merge(object, ...newSources);
    }
});

// Registered as a global, capture export
import outdatedBrowser from 'imports?outdatedBrowser=>{}!exports?outdatedBrowser!outdated-browser';

outdatedBrowser({
    bgColor: '#f25648',
    color: '#ffffff',
    lowerThan: 'borderImage',
    languagePath: ''
});

// 3rd party
import angular from 'angular';
import bootstrap from 'angular-ui-bootstrap';
import elastic from 'angular-elastic';
import sanitize from 'angular-sanitize';
import router from 'angular-ui-router';
import animate from 'angular-animate';
import messages from 'angular-messages';
import { name as slider } from 'angularjs-slider';
import gAnalytic from 'angulartics-google-analytics';
import clipboard from 'ngclipboard';

// 3rd party, don't expose names
import 'angular-localforage';
const angularLocalForage = 'LocalForageModule';
import 'angular-bindonce';
const bindonce = 'pasvaz.bindonce';
import 'angular-truncate-2';
const truncate = 'truncate';
import 'angulartics';
const angulartics = 'angulartics';
import 'angular-translate';
const translate = 'pascalprecht.translate';

// Configs
import q from 'app/setup/q';
import bsTooltips from 'app/setup/bootstrap/bsTooltips';
import bsTemplates from 'app/setup/bootstrap/bsTemplates';
import localForage from 'app/setup/localForage';
import debugInfo from 'app/setup/debugInfo';

// Runs
import watcherLog from 'app/setup/watcherLog';

// Services
import Changelog from 'app/services/Changelog';
import DateTime from 'app/services/DateTime';
import DurationFormatter from 'app/services/DurationFormatter';
import PostNotifications from 'app/services/PostNotifications';
import Hosts from 'app/services/Hosts';
import HtmlNotifications from 'app/services/HtmlNotifications';
import Posts from 'app/services/Posts';
import Translations from 'app/services/translations';
import SettingImportExport from 'app/services/SettingImportExport';
import TeamStyles from 'app/services/TeamStyles';

// Directives
import appCacheUpdater from 'app/directives/appCacheUpdater';
import desktopNotificationEnabler from 'app/directives/desktopNotificationEnabler';
import markdown from 'app/directives/markdown';
import keybind from 'app/directives/keybind';
import postDetails from 'app/directives/postDetails';
import headerBar from 'app/directives/headerBar';
import footerBar from 'app/directives/footerBar';
import navbar from 'app/directives/navbar';
import clockbar from 'app/directives/clockbar';
import notInArray from 'app/directives/notInArray';
import buttonRemovalList from 'app/directives/buttonRemovalList';
import uniqueItemsEditor from 'app/directives/uniqueItemsEditor';
import titleTime from 'app/directives/titleTime';
import nightmode from 'app/directives/nightmode';
import globalAlert from 'app/directives/globalAlert';
// Removed due to english only import countryFlag                from 'app/directives/countryFlag';
import localTime from 'app/directives/localTime';
import relativeTime from 'app/directives/relativeTime';

// Pages/Controllers
import * as About from 'app/pages/About';
import * as Post from 'app/pages/Post';
import * as Post404 from 'app/pages/Post/404';
import * as PostList from 'app/pages/PostList';
import * as Help from 'app/pages/PostList/Help';
import * as Settings from 'app/pages/Settings';
import * as SettingImport from 'app/pages/SettingImport';

// Filtes
import capitalize from 'app/filters/capitalize';

const pages = [About, PostList, Help, Settings, Post, Post404, SettingImport];

function setupStates($stateProvider, $urlRouterProvider) {
    $stateProvider.state('app', {
        abstract: true,
        url: '',
        template: '<ui-view/>',
        resolve: {
            // All routes require DateTime to be loaded before continuing
            savedData: ['DateTime', function (DateTime) {
                return DateTime.initialised;
            }]
        }
    });

    pages
        .filter(page => !_.isUndefined(page.state))
        .map(page => page.state)
        .forEach(state => $stateProvider.state(state));

    $urlRouterProvider.otherwise('/list');
}
setupStates.$inject = ['$stateProvider', '$urlRouterProvider'];

function scrollToTop($rootScope, $window) {
    $rootScope.$on('$stateChangeSuccess', () => $window.scrollTo(0, 0));
}
scrollToTop.$inject = ['$rootScope', '$window'];

const app = angular.module(
    'MatchCalendarApp',
    [angularLocalForage, elastic, sanitize, router, clipboard, animate, bindonce,
        bootstrap, truncate, slider, messages, angulartics, gAnalytic, translate]
)
    .config(q)
    .config(bsTooltips)
    .config(localForage)
    .config(debugInfo)
    .config(setupStates)
    .run(watcherLog)
    .run(scrollToTop)
    .provider('Translations', Translations)
    .directive('localTime', localTime)
    .directive('relativeTime', relativeTime)
    // Removed due to english only - .directive('countryFlag', countryFlag)
    .directive('appCacheUpdater', appCacheUpdater)
    .directive('desktopNotificationEnabler', desktopNotificationEnabler)
    .directive('markdown', markdown)
    .directive('keybind', keybind)
    .directive('postDetails', postDetails)
    .directive('headerBar', headerBar)
    .directive('footerBar', footerBar)
    .directive('navbar', navbar)
    .directive('clockbar', clockbar)
    .directive('notInArray', notInArray)
    .directive('buttonRemovalList', buttonRemovalList)
    .directive('uniqueItemsEditor', uniqueItemsEditor)
    .directive('titleTime', titleTime)
    .directive('nightmode', nightmode)
    .directive('globalAlert', globalAlert)
    .service('Changelog', Changelog)
    .service('DateTime', DateTime)
    .service('DurationFormatter', DurationFormatter)
    .service('PostNotifications', PostNotifications)
    .service('Hosts', Hosts)
    .service('HtmlNotifications', HtmlNotifications)
    .service('Posts', Posts)
    .service('SettingImportExport', SettingImportExport)
    .constant('TeamStyles', TeamStyles)
    .filter('capitalize', capitalize);

pages
    .filter(page => !_.isUndefined(page.controller) && !_.isUndefined(page.controllerName))
    .forEach(page => app.controller(page.controllerName, page.controller));

_.forEach(bsTemplates, (decorator, name) => app.decorator(name, decorator));

// Setup analytics snippet without initial pageview
import DebugMode from 'app/services/DebugMode';

/* eslint-disable */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
/* eslint-enable */

ga('create', 'UA-71696797-1', DebugMode ? 'none' : 'auto');
ga('set', 'dimension3', Boolean(window.applicationCache));
ga('set', 'dimension4', APP_GLOBALS.VERSION);
ga('set', 'dimension5', APP_GLOBALS.HASH);
ga('set', 'dimension6', APP_GLOBALS.BRANCH);

redpajama_set_name: RedPajamaGithub


text:
A flexbile way to store and read data

## Configuration

### Program

The configuration is all inside the `.artscollection.yaml` file.

The structure of the configuration looks like:

    author: authorGithub
    serverPort: :8081
    collections:
            myCollection: path/to/collection
            anotherCollection: path/to/collection

### Collection

Inside of every collection there are also individual configuration possibilities. In the root folder of the collection a `conf.yaml` file is needed. This file defines all the default fields for the collection.

If there is a field with the key `title` that value is used inside the navigation. Otherwise the folder name is used as title.

    -  key: title
        name: Name
        type: string
        render:
        group: a
        order: 10
    -  key: desc
        name: Description
        type: string
        render: textarea
        group: a
        order: 20

Following types are allowed:

* string
* int
* bool
* list

The `string` type supports the `render` property. If `render: textarea` the input field is rendered as a textarea.


text:
package xcordion.impl.command;

import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Ignore;

public class TableForEachCommandTest {
    @Test
    @Ignore
    public void testPlaceholder() {
        Assert.fail("WRITE ME");
    }
}


text:
package gwt.client.view;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public interface DocTypeView<T> extends IsWidget {

    public interface Presenter {
        boolean isDocTypeCodeDuplicate(String keyString, String code);
        void addDocType(String journalTypeKeyString, String code, String name, String journalDesc);
        void editDocType(String keyString, String journalTypeKeyString, String code, String name, String journalDesc);
    }

    Widget asWidget();
    void init(Presenter presenter);
    void setDocType(T t, String keyString, boolean editable);
    void addDocTypeBtnClicked();
    void editDocTypeBtnClicked();
}


text:
package org.jboss.pnc.rest.provider;

import org.jboss.pnc.common.Configuration;
import org.jboss.pnc.common.json.ConfigurationParseException;
import org.jboss.pnc.common.json.moduleconfig.MavenRepoDriverModuleConfig;
import org.jboss.pnc.common.json.moduleprovider.PncConfigProvider;
import org.jboss.pnc.datastore.limits.DefaultSortInfoProducer;
import org.jboss.pnc.datastore.predicates.SpringDataRSQLPredicateProducer;
import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.model.ArtifactRepo;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.rest.provider.collection.CollectionInfo;
import org.jboss.pnc.rest.restmodel.ArtifactRest;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.SortInfoProducer;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
 * Date: 5/10/16
 * Time: 10:58 AM
 */
public class ArtifactProviderTest {

    private final SpringDataRSQLPredicateProducer predicateProvider = new SpringDataRSQLPredicateProducer();
    private final SortInfoProducer sortInfoProducer = new DefaultSortInfoProducer();

    private final Artifact a1 = createArtifact(100, "booya", "asdf");
    private final Artifact a2 = createArtifact(1, "woohoo", "fdsa");
    private final Artifact a3 = createArtifact(2, "aaa", "gggg");

    private String intrernalPath = "http://path.to/deploy/";
    private String publicPath = "http://path.to/public/";

    private final ArtifactRest a1Rest = new ArtifactRest(a1, intrernalPath + a1.getDeployPath(), publicPath + a1.getDeployPath());
    private final ArtifactRest a2Rest = new ArtifactRest(a2, intrernalPath + a2.getDeployPath(), publicPath + a2.getDeployPath());
    private final ArtifactRest a3Rest = new ArtifactRest(a3, intrernalPath + a3.getDeployPath(), publicPath + a3.getDeployPath());

    private Artifact createArtifact(int id, String filename, String checkSum) {
        return Artifact.Builder.newBuilder()
            .id(id)
            .filename(filename)
            .md5("md-fake-" + checkSum)
            .sha1("sha1-fake-" + checkSum)
            .sha256("sha256-fake-" + checkSum)
            .repoType(ArtifactRepo.Type.MAVEN)
            .deployPath("deployed/to/" + filename)
            .build();
    }

    @Test
    public void shouldSortBuiltArtifactsByFilename() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();
        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, "=asc=filename", null, 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a3Rest, a1Rest, a2Rest);
    }

    @Test
    public void shouldSortBuiltArtifactsById() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();
        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, "=asc=id", null, 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a2Rest, a3Rest, a1Rest);
    }

    @Test
    public void shouldFilterBuiltArtifactsByFilename() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();
        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, null, "filename==woohoo", 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a2Rest);
    }

    @Test
    public void shouldFilterBuiltArtifactsByFilenameIdOrChecksum() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();
        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, null, "id==2 or sha256 == sha256-fake-asdf or filename==woohoo", 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().contains(a1Rest, a2Rest, a3Rest);
    }

    @Test
    public void shouldFilterBuiltArtifactsByFilenameIdAndChecksum() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();

        String matchingFilter = "id==100 and sha256 == sha256-fake-asdf and filename==booya";
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, null, matchingFilter, 12);
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a1Rest);

        String nonMatchingFilter = "id==100 and sha256 == sha256-fake-asdf and filename==woohoo";
        artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, null, nonMatchingFilter, 12);
        assertThat(artifacts.getContent()).isEmpty();
    }

    @Test
    public void shouldReturnAllWithoutFilterAndSort() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();
        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 100, null, null, 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().contains(a1Rest, a2Rest, a3Rest);
    }

    @Test
    public void shouldPaginateProperly() {
        // given
        ArtifactProvider provider = artifactProviderWithBuiltResult();

        //when
        CollectionInfo<ArtifactRest> artifacts = provider.getBuiltArtifactsForBuildRecord(0, 1, null, "id == 2 or sha256 == sha256-fake-asdf", 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a1Rest);
        assertThat(artifacts.getTotalPages()).isEqualTo(2);

        //when
        artifacts = provider.getBuiltArtifactsForBuildRecord(1, 1, null, "id == 2 or sha256 == sha256-fake-asdf", 12);
        // then
        assertThat(artifacts.getContent()).usingFieldByFieldElementComparator().containsExactly(a3Rest);
        assertThat(artifacts.getTotalPages()).isEqualTo(2);
    }

    private ArtifactProvider artifactProviderWithBuiltResult() {
        BuildRecord record = new BuildRecord();
        record.setBuiltArtifacts(new HashSet<>(Arrays.asList(a1, a2, a3)));

        BuildRecordRepository recordRepo = mock(BuildRecordRepository.class);
        when(recordRepo.queryById(any())).thenReturn(record);

        return new ArtifactProvider(null, predicateProvider, sortInfoProducer, null, recordRepo, mockConfiguration());
    }

    private Configuration mockConfiguration() {

        PncConfigProvider<MavenRepoDriverModuleConfig> configProvider = new PncConfigProvider<>(
                MavenRepoDriverModuleConfig.class);

        MavenRepoDriverModuleConfig moduleConfig = mock(MavenRepoDriverModuleConfig.class);
        when(moduleConfig.getInternalRepositoryMvnPath()).thenReturn(intrernalPath);
        when(moduleConfig.getExternalRepositoryMvnPath()).thenReturn(publicPath);

        Configuration configuration = mock(Configuration.class);
        try {
            when(configuration.getModuleConfig(any())).thenReturn(moduleConfig);
        } catch (ConfigurationParseException e) {
            Assert.fail(e.getMessage());
        }
        return configuration;
    }
}


text:
{-|
Module      :
Description :
Copyright   : (c) Alexander Vieth, 2015
Licence     : BSD3
Maintainer  : aovieth@gmail.com
Stability   : experimental
Portability : non-portable (GHC only)
-}

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text as T
import Control.Monad
import Control.Monad.Free (iterM)
import Data.String
import Data.Proxy
import Data.Relational
import Data.Relational.RelationalF
import Data.Relational.Interpreter
import Data.Relational.PostgreSQL
import Database.PostgreSQL.Simple
import System.Environment

type IdColumn = '( "id", T.Text )

idColumn :: Column IdColumn
idColumn = column

type KeyColumn = '( "key", T.Text )

keyColumn :: Column KeyColumn
keyColumn = column

type ValueColumn = '( "value", T.Text )

valueColumn :: Column ValueColumn
valueColumn = column

type PropertiesSchema = '[ IdColumn, KeyColumn, ValueColumn ]

propertiesSchema :: Schema PropertiesSchema
propertiesSchema = schema Proxy

type PropertiesTable = '( "properties", PropertiesSchema )

propertiesTable :: Table PropertiesTable
propertiesTable = table propertiesSchema

type ExampleDatabase = '[ PropertiesTable ]

makeSelect :: [(T.Text, T.Text)] -> Relational ExampleDatabase [Row '[IdColumn]]
makeSelect = rfrelation . makeSelect'

makeSelect' :: [(T.Text, T.Text)] -> Relation ExampleDatabase '[IdColumn]
makeSelect' lst = case lst of
    [(key, val)] -> makeSelect1 (key, val)
    x : rest -> Intersection (makeSelect1 x) (makeSelect' rest)

makeSelect1 :: (T.Text, T.Text) -> Relation ExampleDatabase '[IdColumn]
makeSelect1 (key, value) = Selection (Select propertiesTable projection condition)
  where
    projection = idColumn :+| EndProject
    condition = keyColumn .==. key .||. false .&&. valueColumn .==. value .||. false .&&. true

makeInsert :: T.Text -> T.Text -> T.Text -> Relational ExampleDatabase ()
makeInsert id key value = rfinsert (Insert propertiesTable row)
  where
    row =   (fromColumnAndValue idColumn id)
        :&| (fromColumnAndValue keyColumn key)
        :&| (fromColumnAndValue valueColumn value)
        :&| EndRow

makeUpdate :: T.Text -> T.Text -> T.Text -> Relational ExampleDatabase ()
makeUpdate id key value = rfupdate (Update propertiesTable projection condition row)
  where
    projection = valueColumn :+| EndProject
    row = (fromColumnAndValue valueColumn value) :&| EndRow
    condition = idColumn .==. id .||. false .&&. keyColumn .==. key .||. false .&&. true

makeDelete :: T.Text -> T.Text -> Relational ExampleDatabase ()
makeDelete id key = rfdelete (Delete propertiesTable condition)
  where
    condition = idColumn .==. id .||. false .&&. keyColumn .==. key .||. false .&&. true

main = do
    args <- getArgs
    let action = head args
    let parameters = fmap fromString (tail args) :: [T.Text]
    case action of
        "select" -> mainSelect parameters
        "insert" -> mainInsert parameters
        "update" -> mainUpdate parameters
        "delete" -> mainDelete parameters

mainSelect args =
    let keysVals = makePairs args
        proxy :: Proxy (PostgresInterpreter IO)
        proxy = Proxy
        term = iterM (interpreter proxy) (makeSelect keysVals)
    in  do outcome <- runPostgresT (defaultConnectInfo { connectUser="alex" }) Prelude.id term
           print outcome
  where
    makePairs list = case list of
        [] -> []
        x : y : rest -> (x, y) : (makePairs rest)

mainInsert args =
    let id = args !! 0
        key = args !! 1
        value = args !! 2
        proxy :: Proxy (PostgresInterpreter IO)
        proxy = Proxy
        term = iterM (interpreter proxy) (makeInsert id key value)
    in  runPostgresT (defaultConnectInfo { connectUser="alex" }) Prelude.id term

mainUpdate args =
    let id = args !! 0
        key = args !! 1
        value = args !! 2
        proxy :: Proxy (PostgresInterpreter IO)
        proxy = Proxy
        term = iterM (interpreter proxy) (makeUpdate id key value)
    in  runPostgresT (defaultConnectInfo { connectUser="alex" }) Prelude.id term

mainDelete args =
    let id = args !! 0
        key = args !! 1
        proxy :: Proxy (PostgresInterpreter IO)
        proxy = Proxy
        term = iterM (interpreter proxy) (makeDelete id key)
    in  runPostgresT (defaultConnectInfo { connectUser="alex" }) Prelude.id term


text:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLXML;
import java.sql.Statement;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class sqlxmlExample {

    public static void main(String[] args) {

        // Declare the JDBC objects.
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        String serverName = null;
        String portNumber = null;
        String databaseName = null;
        String username = null;
        String password = null;

        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.print("Enter server name: ");
            serverName = br.readLine();
            System.out.print("Enter port number: ");
            portNumber = br.readLine();
            System.out.print("Enter database name: ");
            databaseName = br.readLine();
            System.out.print("Enter username: ");
            username = br.readLine();
            System.out.print("Enter password: ");
            password = br.readLine();

            // Create a variable for the connection string.
            String connectionUrl = "jdbc:sqlserver://" + serverName + ":" + portNumber + ";" + "databaseName=" + databaseName + ";username="
                    + username + ";password=" + password + ";";

            // Establish the connection.
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(connectionUrl);

            // Create initial sample data.
            createSampleTables(con);

            // The showGetters method demonstrates how to parse the data in the
            // SQLXML object by using the SAX, ContentHandler and XMLReader.
            showGetters(con);

            // The showSetters method demonstrates how to set the xml column
            // by using the SAX, ContentHandler, and ResultSet.
            showSetters(con);

            // The showTransformer method demonstrates how to get an XML data
            // from one table and insert that XML data to another table
            // by using the SAX and the Transformer.
            showTransformer(con);
        }
        // Handle any errors that may have occurred.
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (rs != null)
                try {
                    rs.close();
                }
                catch (Exception e) {
                }
            if (stmt != null)
                try {
                    stmt.close();
                }
                catch (Exception e) {
                }
            if (con != null)
                try {
                    con.close();
                }
                catch (Exception e) {
                }
        }
    }

    private static void showGetters(Connection con) {

        try {
            // Create an instance of the custom content handler.
            ExampleContentHandler myHandler = new ExampleContentHandler();

            // Create and execute an SQL statement that returns a
            // set of data.
            String SQL = "SELECT * FROM TestTable1";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(SQL);

            rs.next();

            SQLXML xmlSource = rs.getSQLXML("Col3");

            // Send SAX events to the custom content handler.
            SAXSource sxSource = xmlSource.getSource(SAXSource.class);
            XMLReader xmlReader = sxSource.getXMLReader();
            xmlReader.setContentHandler(myHandler);

            System.out.println("showGetters method: Parse an XML data in TestTable1 => ");
            xmlReader.parse(sxSource.getInputSource());

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void showSetters(Connection con) {

        try {
            // Create and execute an SQL statement, retrieving an updatable result set.
            String SQL = "SELECT * FROM TestTable1;";
            Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery(SQL);

            // Create an empty SQLXML object.
            SQLXML sqlxml = con.createSQLXML();

            // Set the result value from SAX events.
            SAXResult sxResult = sqlxml.setResult(SAXResult.class);
            ContentHandler myHandler = sxResult.getHandler();

            // Set the XML elements and attributes into the result.
            myHandler.startDocument();
            myHandler.startElement(null, "contact", "contact", null);
            myHandler.startElement(null, "name", "name", null);
            myHandler.endElement(null, "name", "name");
            myHandler.startElement(null, "phone", "phone", null);
            myHandler.endElement(null, "phone", "phone");
            myHandler.endElement(null, "contact", "contact");
            myHandler.endDocument();

            // Update the data in the result set.
            rs.moveToInsertRow();
            rs.updateString("Col2", "C");
            rs.updateSQLXML("Col3", sqlxml);
            rs.insertRow();

            // Display the data.
            System.out.println("showSetters method: Display data in TestTable1 => ");
            while (rs.next()) {
                System.out.println(rs.getString("Col1") + " : " + rs.getString("Col2"));
                SQLXML xml = rs.getSQLXML("Col3");
                System.out.println("XML column : " + xml.getString());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void showTransformer(Connection con) {

        try {
            // Create and execute an SQL statement that returns a
            // set of data.
            String SQL = "SELECT * FROM TestTable1";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(SQL);

            rs.next();

            // Get the value of the source SQLXML object from the database.
            SQLXML xmlSource = rs.getSQLXML("Col3");

            // Get a Source to read the XML data.
            SAXSource sxSource = xmlSource.getSource(SAXSource.class);

            // Create a destination SQLXML object without any data.
            SQLXML xmlDest = con.createSQLXML();

            // Get a Result to write the XML data.
            SAXResult sxResult = xmlDest.setResult(SAXResult.class);

            // Transform the Source to a Result by using the identity transform.
            SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
            Transformer identity = stf.newTransformer();
            identity.transform(sxSource, sxResult);

            // Insert the destination SQLXML object into the database.
            PreparedStatement psmt = con.prepareStatement("INSERT INTO TestTable2" + " (Col2, Col3, Col4, Col5) VALUES (?, ?, ?, ?)");
            psmt.setString(1, "A");
            psmt.setString(2, "Test data");
            psmt.setInt(3, 123);
            psmt.setSQLXML(4, xmlDest);
            psmt.execute();

            // Execute the query and display the data.
            SQL = "SELECT * FROM TestTable2";
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);

            System.out.println("showTransformer method : Display data in TestTable2 => ");
            while (rs.next()) {
                System.out.println(rs.getString("Col1") + " : " + rs.getString("Col2"));
                System.out.println(rs.getString("Col3") + " : " + rs.getInt("Col4"));

                SQLXML xml = rs.getSQLXML("Col5");
                System.out.println("XML column : " + xml.getString());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createSampleTables(Connection con) {

        try {
            Statement stmt = con.createStatement();

            // Drop the tables.
            stmt.executeUpdate("if exists (select * from sys.objects where name = 'TestTable1')" + "drop table TestTable1");

            stmt.executeUpdate("if exists (select * from sys.objects where name = 'TestTable2')" + "drop table TestTable2");

            // Create empty tables.
            stmt.execute("CREATE TABLE TestTable1 (Col1 int IDENTITY, Col2 char, Col3 xml)");
            stmt.execute("CREATE TABLE TestTable2 (Col1 int IDENTITY, Col2 char, Col3 varchar(50), Col4 int, Col5 xml)");

            // Insert two rows to the TestTable1.
            String row1 = "<contact><name>Contact Name 1</name><phone>XXX-XXX-XXXX</phone></contact>";
            String row2 = "<contact><name>Contact Name 2</name><phone>YYY-YYY-YYYY</phone></contact>";

            stmt.executeUpdate("insert into TestTable1" + " (Col2, Col3) values('A', '" + row1 + "')");
            stmt.executeUpdate("insert into TestTable1" + " (Col2, Col3) values('B', '" + row2 + "')");

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class ExampleContentHandler implements ContentHandler {

    public void startElement(String namespaceURI,
            String localName,
            String qName,
            Attributes atts) throws SAXException {
        System.out.println("startElement method: localName => " + localName);
    }

    public void characters(char[] text,
            int start,
            int length) throws SAXException {
        System.out.println("characters method");
    }

    public void endElement(String namespaceURI,
            String localName,
            String qName) throws SAXException {
        System.out.println("endElement method: localName => " + localName);
    }

    public void setDocumentLocator(Locator locator) {
        System.out.println("setDocumentLocator method");
    }

    public void startDocument() throws SAXException {
        System.out.println("startDocument method");
    }

    public void endDocument() throws SAXException {
        System.out.println("endDocument method");
    }

    public void startPrefixMapping(String prefix,
            String uri) throws SAXException {
        System.out.println("startPrefixMapping method: prefix => " + prefix);
    }

    public void endPrefixMapping(String prefix) throws SAXException {
        System.out.println("endPrefixMapping method: prefix => " + prefix);
    }

    public void skippedEntity(String name) throws SAXException {
        System.out.println("skippedEntity method: name => " + name);
    }

    public void ignorableWhitespace(char[] text,
            int start,
            int length) throws SAXException {
        System.out.println("ignorableWhiteSpace method");
    }

    public void processingInstruction(String target,
            String data) throws SAXException {
        System.out.println("processingInstruction method: target => " + target);
    }
}


text:
var assert = require('assert');
var jmespath = require('../jmespath');
var tokenize = jmespath.tokenize;
var compile = jmespath.compile;
var strictDeepEqual = jmespath.strictDeepEqual;

describe('tokenize', function() {
    it('should tokenize unquoted identifier', function() {
        assert.deepEqual(tokenize('foo'),
                         [{type: "UnquotedIdentifier",
                          value: "foo",
                          start: 0}]);
    });
    it('should tokenize unquoted identifier with underscore', function() {
        assert.deepEqual(tokenize('_underscore'),
                          [{type: "UnquotedIdentifier",
                           value: "_underscore",
                           start: 0}]);
    });
    it('should tokenize unquoted identifier with numbers', function() {
        assert.deepEqual(tokenize('foo123'),
                          [{type: "UnquotedIdentifier",
                           value: "foo123",
                           start: 0}]);
    });
    it('should tokenize dotted lookups', function() {
        assert.deepEqual(
            tokenize('foo.bar'),
            [{type: "UnquotedIdentifier", value: "foo", start: 0},
             {type: "Dot", value: ".", start: 3},
             {type: "UnquotedIdentifier", value: "bar", start: 4},
            ]);
    });
    it('should tokenize numbers', function() {
        assert.deepEqual(
            tokenize('foo[0]'),
            [{type: "UnquotedIdentifier", value: "foo", start: 0},
             {type: "Lbracket", value: "[", start: 3},
             {type: "Number", value: 0, start: 4},
             {type: "Rbracket", value: "]", start: 5},
            ]);
    });
    it('should tokenize numbers with multiple digits', function() {
        assert.deepEqual(
            tokenize("12345"),
            [{type: "Number", value: 12345, start: 0}]);
    });
    it('should tokenize negative numbers', function() {
        assert.deepEqual(
            tokenize("-12345"),
            [{type: "Number", value: -12345, start: 0}]);
    });
    it('should tokenize quoted identifier', function() {
        assert.deepEqual(tokenize('"foo"'),
                         [{type: "QuotedIdentifier",
                          value: "foo",
                          start: 0}]);
    });
    it('should tokenize quoted identifier with unicode escape', function() {
        assert.deepEqual(tokenize('"\\u2713"'),
                         [{type: "QuotedIdentifier",
                          value: "✓",
                          start: 0}]);
    });
    it('should tokenize literal lists', function() {
        assert.deepEqual(tokenize("`[0, 1]`"),
                         [{type: "Literal",
                          value: [0, 1],
                          start: 0}]);
    });
    it('should tokenize literal dict', function() {
        assert.deepEqual(tokenize("`{\"foo\": \"bar\"}`"),
                         [{type: "Literal",
                          value: {"foo": "bar"},
                          start: 0}]);
    });
    it('should tokenize literal strings', function() {
        assert.deepEqual(tokenize("`\"foo\"`"),
                         [{type: "Literal",
                          value: "foo",
                          start: 0}]);
    });
    it('should tokenize json literals', function() {
        assert.deepEqual(tokenize("`true`"),
                         [{type: "Literal",
                          value: true,
                          start: 0}]);
    });
    it('should not requiring surrounding quotes for strings', function() {
        assert.deepEqual(tokenize("`foo`"),
                         [{type: "Literal",
                          value: "foo",
                          start: 0}]);
    });
    it('should not requiring surrounding quotes for numbers', function() {
        assert.deepEqual(tokenize("`20`"),
                         [{type: "Literal",
                           value: 20,
                           start: 0}]);
    });
    it('should tokenize literal lists with chars afterwards', function() {
        assert.deepEqual(
            tokenize("`[0, 1]`[0]"), [
                {type: "Literal", value: [0, 1], start: 0},
                {type: "Lbracket", value: "[", start: 8},
                {type: "Number", value: 0, start: 9},
                {type: "Rbracket", value: "]", start: 10}
        ]);
    });
    it('should tokenize two char tokens with shared prefix', function() {
        assert.deepEqual(
            tokenize("[?foo]"),
            [{type: "Filter", value: "[?", start: 0},
             {type: "UnquotedIdentifier", value: "foo", start: 2},
             {type: "Rbracket", value: "]", start: 5}]
        );
    });
    it('should tokenize flatten operator', function() {
        assert.deepEqual(
            tokenize("[]"),
            [{type: "Flatten", value: "[]", start: 0}]);
    });
    it('should tokenize comparators', function() {
        assert.deepEqual(tokenize("<"),
                         [{type: "LT",
                          value: "<",
                          start: 0}]);
    });
    it('should tokenize two char tokens without shared prefix', function() {
        assert.deepEqual(
            tokenize("=="),
            [{type: "EQ", value: "==", start: 0}]
        );
    });
    it('should tokenize not equals', function() {
        assert.deepEqual(
            tokenize("!="),
            [{type: "NE", value: "!=", start: 0}]
        );
    });
    it('should tokenize the OR token', function() {
        assert.deepEqual(
            tokenize("a||b"),
            [
                {type: "UnquotedIdentifier", value: "a", start: 0},
                {type: "Or", value: "||", start: 1},
                {type: "UnquotedIdentifier", value: "b", start: 3}
            ]
        );
    });
    it('should tokenize function calls', function() {
        assert.deepEqual(
            tokenize("abs(@)"),
            [
                {type: "UnquotedIdentifier", value: "abs", start: 0},
                {type: "Lparen", value: "(", start: 3},
                {type: "Current", value: "@", start: 4},
                {type: "Rparen", value: ")", start: 5}
            ]
        );
    });
});

describe('parsing', function() {
    it('should parse field node', function() {
        assert.deepEqual(compile('foo'),
                          {type: 'Field', name: 'foo'});
    });
});

describe('strictDeepEqual', function() {
    it('should compare scalars', function() {
        assert.strictEqual(strictDeepEqual('a', 'a'), true);
    });
    it('should be false for different types', function() {
        assert.strictEqual(strictDeepEqual('a', 2), false);
    });
    it('should be false for arrays of different lengths', function() {
        assert.strictEqual(strictDeepEqual([0, 1], [1, 2, 3]), false);
    });
    it('should be true for identical arrays', function() {
        assert.strictEqual(strictDeepEqual([0, 1], [0, 1]), true);
    });
    it('should be true for nested arrays', function() {
        assert.strictEqual(
            strictDeepEqual([[0, 1], [2, 3]], [[0, 1], [2, 3]]), true);
    });
    it('should be true for nested arrays of strings', function() {
        assert.strictEqual(
            strictDeepEqual([["a", "b"], ["c", "d"]],
                            [["a", "b"], ["c", "d"]]), true);
    });
    it('should be false for different arrays of the same length', function() {
        assert.strictEqual(strictDeepEqual([0, 1], [1, 2]), false);
    });
    it('should handle object literals', function() {
        assert.strictEqual(strictDeepEqual({a: 1, b: 2}, {a: 1, b: 2}), true);
    });
    it('should handle keys in first not in second', function() {
        assert.strictEqual(strictDeepEqual({a: 1, b: 2}, {a: 1}), false);
    });
    it('should handle keys in second not in first', function() {
        assert.strictEqual(strictDeepEqual({a: 1}, {a: 1, b: 2}), false);
    });
    it('should handle nested objects', function() {
        assert.strictEqual(
            strictDeepEqual({a: {b: [1, 2]}},
                            {a: {b: [1, 2]}}), true);
    });
    it('should handle nested objects that are not equal', function() {
        assert.strictEqual(
            strictDeepEqual({a: {b: [1, 2]}},
                            {a: {b: [1, 4]}}), false);
    });
});


text:
// FIXME: access to IO.h from down here is a bit hacky :/
#include "IO/IO.h"

namespace Oryol {
namespace _priv {

OryolClassImpl(ioLane);

//------------------------------------------------------------------------------
ioLane::ioLane() {
    // let our thread wake up from time to time
    this->SetTickDuration(100);
}

//------------------------------------------------------------------------------
ioLane::~ioLane() {
    o_assert(this->threadStopped);
}

//------------------------------------------------------------------------------
void
ioLane::onThreadEnter() {
    ThreadedQueue::onThreadEnter();

    // setup a Dispatcher to route messages to safely route messages
    // to this object's callback methods
    Ptr<Dispatcher<IOProtocol>> disp = Dispatcher<IOProtocol>::Create();
    using namespace std::placeholders;
    disp->Subscribe<IOProtocol::Request>(std::bind(&ioLane::onRequest, this, _1));
    disp->Subscribe<IOProtocol::notifyFileSystemAdded>(std::bind(&ioLane::onNotifyFileSystemAdded, this, _1));
    disp->Subscribe<IOProtocol::notifyFileSystemReplaced>(std::bind(&ioLane::onNotifyFileSystemReplaced, this, _1));
    disp->Subscribe<IOProtocol::notifyFileSystemRemoved>(std::bind(&ioLane::onNotifyFileSystemRemoved, this, _1));
    this->forwardingPort = disp;
}

//------------------------------------------------------------------------------
void
ioLane::onThreadLeave() {
    this->forwardingPort = 0;
    this->fileSystems.Clear();
    ThreadedQueue::onThreadLeave();
}

//------------------------------------------------------------------------------
void
ioLane::onTick() {
    ThreadedQueue::onTick();

    // also tick our file systems
    for (const auto& kvp : this->fileSystems) {
        kvp.Value()->DoWork();
    }
}

//------------------------------------------------------------------------------
Ptr<FileSystem>
ioLane::fileSystemForURL(const URL& url) {
    StringAtom scheme = url.Scheme();
    if (this->fileSystems.Contains(scheme)) {
        return this->fileSystems[scheme];
    }
    else {
        o_warn("ioLane::fileSystemForURL: no filesystem registered for URL scheme '%s'!\n", scheme.AsCStr());
        return Ptr<FileSystem>();
    }
}

//------------------------------------------------------------------------------
void
ioLane::onRequest(const Ptr<IOProtocol::Request>& msg) {
    if (msg->Cancelled()) {
        // message has been cancelled, don't waste time with it
        msg->SetStatus(IOStatus::Cancelled);
        msg->SetHandled();
    }
    else {
        Ptr<FileSystem> fs = this->fileSystemForURL(msg->GetURL());
        if (fs) {
            fs->onRequest(msg);
        }
    }
}

//------------------------------------------------------------------------------
void
ioLane::onNotifyFileSystemAdded(const Ptr<IOProtocol::notifyFileSystemAdded>& msg) {
    const StringAtom& urlScheme = msg->GetScheme();
    o_assert(!this->fileSystems.Contains(urlScheme));
    Ptr<FileSystem> newFileSystem = IO::getSchemeRegistry()->CreateFileSystem(urlScheme);
    this->fileSystems.Add(urlScheme, newFileSystem);
}

//------------------------------------------------------------------------------
void
ioLane::onNotifyFileSystemReplaced(const Ptr<IOProtocol::notifyFileSystemReplaced>& msg) {
    const StringAtom& urlScheme = msg->GetScheme();
    o_assert(this->fileSystems.Contains(urlScheme));
    Ptr<FileSystem> newFileSystem = IO::getSchemeRegistry()->CreateFileSystem(urlScheme);
    this->fileSystems[urlScheme] = newFileSystem;
}

//------------------------------------------------------------------------------
void
ioLane::onNotifyFileSystemRemoved(const Ptr<IOProtocol::notifyFileSystemRemoved>& msg) {
    const StringAtom& urlScheme = msg->GetScheme();
    o_assert(this->fileSystems.Contains(urlScheme));
    this->fileSystems.Erase(urlScheme);
}

} // namespace _priv
} // namespace Oryol


text:
package main

import (
	"fmt"
	"math/big"
	"os"

	"github.com/okcoin/go-okcoin/cmd/utils"
	"gopkg.in/urfave/cli.v1"
)

var gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)

var (
	app = utils.NewApp(gitCommit, "the evm command line interface")

	DebugFlag = cli.BoolFlag{
		Name:  "debug",
		Usage: "output full trace logs",
	}
	MemProfileFlag = cli.StringFlag{
		Name:  "memprofile",
		Usage: "creates a memory profile at the given path",
	}
	CPUProfileFlag = cli.StringFlag{
		Name:  "cpuprofile",
		Usage: "creates a CPU profile at the given path",
	}
	StatDumpFlag = cli.BoolFlag{
		Name:  "statdump",
		Usage: "displays stack and heap memory information",
	}
	CodeFlag = cli.StringFlag{
		Name:  "code",
		Usage: "EVM code",
	}
	CodeFileFlag = cli.StringFlag{
		Name:  "codefile",
		Usage: "File containing EVM code. If '-' is specified, code is read from stdin ",
	}
	GasFlag = cli.Uint64Flag{
		Name:  "gas",
		Usage: "gas limit for the evm",
		Value: 10000000000,
	}
	PriceFlag = utils.BigFlag{
		Name:  "price",
		Usage: "price set for the evm",
		Value: new(big.Int),
	}
	ValueFlag = utils.BigFlag{
		Name:  "value",
		Usage: "value set for the evm",
		Value: new(big.Int),
	}
	DumpFlag = cli.BoolFlag{
		Name:  "dump",
		Usage: "dumps the state after the run",
	}
	InputFlag = cli.StringFlag{
		Name:  "input",
		Usage: "input for the EVM",
	}
	VerbosityFlag = cli.IntFlag{
		Name:  "verbosity",
		Usage: "sets the verbosity level",
	}
	CreateFlag = cli.BoolFlag{
		Name:  "create",
		Usage: "indicates the action should be create rather than call",
	}
	GenesisFlag = cli.StringFlag{
		Name:  "prestate",
		Usage: "JSON file with prestate (genesis) config",
	}
	MachineFlag = cli.BoolFlag{
		Name:  "json",
		Usage: "output trace logs in machine readable format (json)",
	}
	SenderFlag = cli.StringFlag{
		Name:  "sender",
		Usage: "The transaction origin",
	}
	ReceiverFlag = cli.StringFlag{
		Name:  "receiver",
		Usage: "The transaction receiver (execution context)",
	}
	DisableMemoryFlag = cli.BoolFlag{
		Name:  "nomemory",
		Usage: "disable memory output",
	}
	DisableStackFlag = cli.BoolFlag{
		Name:  "nostack",
		Usage: "disable stack output",
	}
)

func init() {
	app.Flags = []cli.Flag{
		CreateFlag,
		DebugFlag,
		VerbosityFlag,
		CodeFlag,
		CodeFileFlag,
		GasFlag,
		PriceFlag,
		ValueFlag,
		DumpFlag,
		InputFlag,
		MemProfileFlag,
		CPUProfileFlag,
		StatDumpFlag,
		GenesisFlag,
		MachineFlag,
		SenderFlag,
		ReceiverFlag,
		DisableMemoryFlag,
		DisableStackFlag,
	}
	app.Commands = []cli.Command{
		compileCommand,
		disasmCommand,
		runCommand,
		stateTestCommand,
	}
}

func main() {
	if err := app.Run(os.Args); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}


text:
> A Vue.js project that uses GraphQL, and the Graph.cool service

This is a Hacker News web app, built by following the following **excellent** tutorial:

https://www.howtographql.com/vue-apollo/0-introduction/

The app uses the Apollo client for GraphQL, and the https://www.graph.cool/ service for its backend.

## Build Setup

``` bash
# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build

# build for production and view the bundle analyzer report
npm run build --report

# run unit tests
npm run unit

# run all tests
npm test

# build and deploy to surge.sh
npm run deploy
```


text:
let assert = require('assert');
let Promise = require('bluebird');
let knownStringerImplementors = {};

function _isFunction(toCheck){
  return toString.call(toCheck) === "[object Function]";
}

class Stringer{
  constructor(baseObject, options){
    let {fromString: fromStringFunc, toString: toStringFunc} = options;
    assert(_isFunction(fromStringFunc));
    assert(_isFunction(toStringFunc));
    let constructorName = Object.getPrototypeOf(baseObject).constructor.name;
    this.baseObject = baseObject;
    this.constructorName = constructorName;
    this.fromStringFunc = fromStringFunc;
    this.toStringFunc = toStringFunc;
  }
  static toString(objectToString){
    return Promise.coroutine(function* (){
      let stringerInstance = objectToString.__Stringer;
      if(!stringerInstance){
        throw new Error("Object is not using Stringer mixin");
      }
      var toJson = {
        ConstructorName: stringerInstance.constructorName,
        Obj: stringerInstance.toStringFunc.call(stringerInstance.baseObject, stringerInstance.baseObject)
      }
      toJson.Obj = yield Promise.cast(toJson.Obj);
      return JSON.stringify(toJson);
    })();
  }
  static fromString(stringToObject, context){
    let {ConstructorName, Obj} = JSON.parse(stringToObject)
    let fromStringFunc = knownStringerImplementors[ConstructorName];
    if(!fromStringFunc){
      throw new Error(`Constructor ${ConstructorName} is not a known Stringer mixin implementor`);
    }
    return fromStringFunc.call(context, Obj);
  }
}
Stringer.onMixinInheriting = function(subtype, mixinOpts){
  let {fromString} = mixinOpts;
  knownStringerImplementors[subtype.name] = fromString;
}

module.exports = Stringer;