text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global $, renderingData, folderData, bodymovin, LocalStorageManager, Mustache */
var compRenderController = (function () {
    'use strict';
    var view, renders, csInterface, compositions, cancelButton, returnButton;
    var ob = {};

    var fontsStorage, textHelper;

    function addFolderEvent(elem, data) {
        elem.on('click', function () {
            var eScript = 'bm_compsManager.browseFolder(' + data.id + ')';
            csInterface.evalScript(eScript);
        });
        elem.on('mouseover', function () {
            data.folderAnim.goToAndStop(0);
            data.folderAnim.play();
        });
    }

    function destroyCompositions() {
        if (compositions) {
            var i, len = compositions.length;
            for (i = 0; i < len; i += 1) {
                compositions[i].anim.destroy();
                compositions[i].folderAnim.destroy();
            }
        }
    }

    function renderStartHandler(ev) {
        renders.empty();
        compositions = messageParser.parse(ev.data);
        var i, len = compositions.length, elem;
        for (i = 0; i < len; i += 1) {
            var template = document.getElementById('elementTemplate').innerHTML;
            var output = Mustache.render(template, compositions[i]);
            elem = $(output);
            //elem.find('.compName').html(compositions[i].name);
            elem.find('.statusText').html('Queued');
            addFolderEvent(elem.find('.buttonHover'), compositions[i]);

            compositions[i].elem = elem;
            renders.append(elem);

            var animContainer = elem.find('.compAnim')[0];
            var animData = JSON.parse(renderingData);
            var params = {
                animType: 'svg',
                wrapper: animContainer,
                loop: true,
                autoplay: true,
                prerender: true,
                animationData: animData
            };
            var anim = bodymovin.loadAnimation(params);
            compositions[i].anim = anim;

            animContainer = elem.find('.folder')[0];
            animData = JSON.parse(folderData);
            params = {
                animType: 'svg',
                wrapper: animContainer,
                loop: false,
                autoplay: false,
                prerender: true,
                animationData: animData
            };
            anim = bodymovin.loadAnimation(params);
            compositions[i].folderAnim = anim;
        }
        cancelButton.show();
        returnButton.hide();
    }

    function renderUpdateHandler(ev) {
        var messageData = ev.data;
        var id = messageData.compId.toString();
        var i = 0, len = compositions.length;
        while (i < len) {
            if (id === compositions[i].id.toString()) {
                break;
            }
            i += 1;
        }
        var compData = compositions[i];
        var elem = compData.elem;
        if (messageData.type === 'update') {
            elem.find('.statusText').html(messageData.message);
            if (messageData.progress) {
                elem.find('.progressBar').css('width', (messageData.progress * 100) + '%');
            }
        }
        if (messageData.isFinished) {
            elem.addClass('rendered');
            compData.fsPath = messageData.fsPath;
        }
    }

    function getStoredFontData(name) {
        var i = 0, len = fontsStorage.length;
        while (i < len) {
            if (fontsStorage[i].fName === name) {
                return fontsStorage[i];
            }
            i += 1;
        }
        var ob = {
            fName : name,
            fFamily : name,
            fWeight : 'normal',
            fStyle : 'normal',
            fPath : '',
            fClass : '',
            fOrigin: 'p'
        };
        fontsStorage.push(ob);
        return ob;
    }

    function saveFontsData(fontsContainer, fonts) {
        var fontsList = fontsContainer.find('.fontsList');
        var fontsInfo = {
            list: []
        };
        var fontOb;
        var list = fontsInfo.list;
        var children = fontsList.children();
        children.each(function (index, item) {
            fontOb = {};
            fontOb.fName = fonts[index].name;
            fontOb.fPath = $(item).find('.fontPath')[0].value;
            fontOb.fClass = $(item).find('.fontClass')[0].value;
            fontOb.fFamily = $(item).find('.fontFamily')[0].value;
            fontOb.fWeight = $(item).find('.fontWeight')[0].value;
            fontOb.fStyle = $(item).find('.fontStyle')[0].value;
            var checked = $(item).find('input[type=radio]:checked');
            var radioVal = checked.val();
            fontOb.fOrigin = radioVal || 'n';
            var storedOb = getStoredFontData(fonts[index].name);
            storedOb.fPath = fontOb.fPath;
            storedOb.fClass = fontOb.fClass;
            storedOb.fFamily = fontOb.fFamily;
            storedOb.fWeight = fontOb.fontWeight;
            storedOb.fStyle = fontOb.fontStyle;
            storedOb.fOrigin = fontOb.fOrigin;
            list.push(fontOb);
        });
        LocalStorageManager.setItem('fonts', fontsStorage);
        var fontsInfoString = JSON.stringify(fontsInfo);
        var eScript = 'bm_renderManager.setFontData(' + fontsInfoString + ')';
        csInterface.evalScript(eScript);
    }

    function renderFontsHandler(ev) {
        var messageData = ev.data;
        var id = messageData.compId.toString();
        var i = 0, len = compositions.length;
        while (i < len) {
            if (id === compositions[i].id.toString()) {
                break;
            }
            i += 1;
        }
        var compData = compositions[i];
        var elem = compData.elem;
        var fonts = messageParser.parse(messageData.fonts);
        elem.find('.statusText').html('Select font families and font paths if necessary.');
        var fontsContainer = elem.find('.fontsContainer');
        fontsContainer.show();
        var fontsList = fontsContainer.find('.fontsList');
        len = fonts.length;
        var fontElem, storedData, template, output;
        for (i = 0; i < len; i += 1) {
            fonts[i].__index = i;
            storedData = getStoredFontData(fonts[i].name);

            template = document.getElementById('fontTemplate').innerHTML;
            output = Mustache.render(template, {fontData: fonts[i], storedData: storedData});
            fontElem = $(output);
            if (storedData.fOrigin) {
                fontElem.find("input[type=radio][value=" + storedData.fOrigin + "]").prop('checked', true);
            }
            fontsList.append(fontElem);
        }
        fontsContainer.find('button.continue').on('click', function () {
            saveFontsData(fontsContainer, fonts);
            fontsContainer.hide();
        });
    }

    function renderCharsHandler(ev) {
        var messageData = ev.data;
        var chars = messageParser.parse(messageData.chars);

        var i, len = chars.length;
        for (i = 0; i < len; i += 1) {
            var styles = chars[i].style.split(' ');
            var j, jLen = styles.length;
            var fStyle = 'normal';
            var fWeight = 'normal';
            for (j = 0; j < jLen; j += 1) {
                if (styles[j].toLowerCase() === 'italic') {
                    fStyle = 'italic';
                } else if (styles[j].toLowerCase() === 'black') {
                    fWeight = '900';
                } else if (styles[j].toLowerCase() === 'extrabold') {
                    fWeight = '800';
                } else if (styles[j].toLowerCase() === 'bold') {
                    fWeight = '700';
                } else if (styles[j].toLowerCase() === 'semibold') {
                    fWeight = '600';
                } else if (styles[j].toLowerCase() === 'medium') {
                    fWeight = '500';
                } else if (styles[j].toLowerCase() === 'regular' || styles[j].toLowerCase() === 'normal') {
                    fWeight = '400';
                } else if (styles[j].toLowerCase() === 'extralight') {
                    fWeight = '300';
                } else if (styles[j].toLowerCase() === 'light' || styles[j].toLowerCase() === 'thin') {
                    fWeight = '200';
                }
            }

            textHelper.setAttribute('font-style', fStyle);
            textHelper.setAttribute('font-weight', fWeight);
            textHelper.setAttribute('font-family', chars[i].fFamily);
            textHelper.setAttribute('font-size', chars[i].size);
            textHelper.setAttribute('font-size', 100);
            textHelper.textContent = chars[i].ch === ' ' ? '\u00A0' : chars[i].ch;
            /* Not using this for now.
            var cLength = textHelper.getComputedTextLength();
            chars[i].w = cLength;
            */
            delete chars[i].font;
        }
        var charsInfoString = JSON.stringify(chars);
        var eScript = 'bm_renderManager.setCharsData(' + charsInfoString + ')';
        csInterface.evalScript(eScript);
    }

    function renderCompleteHandler() {
        cancelButton.hide();
        returnButton.show();
    }

    function init(csIntfc) {
        fontsStorage = LocalStorageManager.getItem('fonts');
        if (fontsStorage === null) {
            fontsStorage = [];
            LocalStorageManager.setItem('fonts', fontsStorage);
        }
        view = $('#compsRender');
        renders = view.find('.renders');
        view.hide();
        csInterface = csIntfc;
        csInterface.addEventListener('bm:render:start', renderStartHandler);
        csInterface.addEventListener('bm:render:update', renderUpdateHandler);
        csInterface.addEventListener('bm:render:complete', renderCompleteHandler);
        csInterface.addEventListener('bm:render:fonts', renderFontsHandler);
        csInterface.addEventListener('bm:render:chars', renderCharsHandler);

        cancelButton = view.find('.cancel');
        returnButton = view.find('.return');
        cancelButton.on('click', function () {
            var eScript = 'bm_compsManager.cancel()';
            csInterface.evalScript(eScript);
        });
        returnButton.on('click', function () {
            var eScript = 'bm_compsManager.cancel()';
            csInterface.evalScript(eScript);
        });
        returnButton.hide();
        textHelper = document.getElementById('textHelper');
        textHelper.setAttributeNS("http://www.w3.org/XML/1998/namespace",  "xml:space", "preserve");
    }

    function show() {
        view.show();
    }

    function hide() {
        if (compositions) {
            var i, len = compositions.length;
            for (i = 0; i < len; i += 1) {
                compositions[i].anim.goToAndStop(0);
            }
        }
        view.hide();
    }

    function getCompositions() {
        return compositions;
    }

    ob.init = init;
    ob.show = show;
    ob.hide = hide;
    ob.getCompositions = getCompositions;

    return ob;
}());


text:
Cordova IAP plugin
====================

# Overview #
in app purchase

[android, ios, wp8] [cordova cli] [xdk] [cocoon] [phonegap build service]

Requires google play developer account https://play.google.com/apps/publish/
Requires apple developer account https://developer.apple.com/devcenter/ios/index.action
Requires windows phone developer account https://dev.windowsphone.com/
wp8 is not yet supported

This is open source cordova plugin.

You can see Cordova Plugins in one page: http://cranberrygame.github.io?referrer=github

cf)construct2

android: Phonegap IAP or c2 IAP plugin

blackberry10: c2 IAP plugin (https://www.scirra.com/manual/173/iap)

ios: Phonegap IAP or c2 IAP plugin

windows8: c2 IAP plugin

wp8: Phonegap IAP

# Change log #
```c
2.0.52 Fixed string argument like "testapp_removeads,testapp_coinpack1" lead failure issue.
```
# Install plugin #

## Cordova cli ##
https://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-Line%20Interface - npm install -g cordova@6.0.0
```c
cordova plugin add cordova-plugin-payment-iap
(when build error, use github url: cordova plugin add https://github.com/cranberrygame/cordova-plugin-payment-iap)
```

## Xdk ##
https://software.intel.com/en-us/intel-xdk - Download XDK - XDK PORJECTS - [specific project] - CORDOVA HYBRID MOBILE APP SETTINGS - Plugin Management - Add Plugins to this Project - Third Party Plugins -
```c
Plugin Source: Cordova plugin registry
Plugin ID: cordova-plugin-payment-iap
```

## Cocoon ##
https://cocoon.io - Create project - [specific project] - Setting - Plugins - Custom - Git Url: https://github.com/cranberrygame/cordova-plugin-payment-iap.git - INSTALL - Save

## Phonegap build service (config.xml) ##
https://build.phonegap.com/ - Apps - [specific project] - Update code - Zip file including config.xml
```c
<gap:plugin name="cordova-plugin-payment-iap" source="npm" />
```

## Construct2 ##
Download construct2 plugin

https://dl.dropboxusercontent.com/u/186681453/pluginsforcordova/index.html

How to install c2 native plugins in xdk, cocoon and cordova cli

https://plus.google.com/102658703990850475314/posts/XS5jjEApJYV

# Server setting #
```c
```
## Android ##
```c
//if you see this message when trying to add in app product, you must republish the app with Phonegap IAP plugin once in alpha, beta, normal publish (just republish, no iap event coding).
//if your app is republished with dummy Phonegap IAP plugin, then you can add in app product
//(See 1.png 2.png 3.png)
Your app doesn't have any in-app products yet.
To add in-app products, you need to add the BILLING permission to your APK.

//add in app product (nonconsumable)
google play developer console - [specific app] - in app product - add - managed, product ID: testapp_removeads - Name : Remove Ads, Description: You can purchase remove ads by tapping "Remove Ads" button. - set active

//add in app product (consumable)
google play developer console - [specific app] - in app product - add - unmanaged, product ID: testapp_coinpack1 - Name : Coin Pack1 (250 Coins), Description: Coin pack1 (250 Coins) - set active

//add in app product (consumable)
google play developer console - [specific app] - in app product - add - unmanaged, product ID: testapp_coinpack2 - Name : Coin Pack2 (750 Coins), Description: Coin pack2 (750 Coins) - set active

//add in app product (consumable)
google play developer console - [specific app] - in app product - add - unmanaged, product ID: testapp_coinpack3 - Name : Coin Pack3 (2250 Coins), Description: Coin pack3 (2250 Coins) - set active

//get application license key (per app)
google play developer console - [specific app] - Services & APis - license and in app purchase - get ANDROID_APPLICATION_LICENSE_KEY
```

## iOS ##
```c
//accept paid agreement if you are adding your first app on iOS (contributed by tabrez)

//add in app product (nonconsumable)
itunesconnect - Manage Your Apps - [specific app] - Manage In-App Purchases - Create New - Non Consumable - Select - Reference Name: testapp_removeads, Product ID: testapp_removeads - 언어 추가 - 언어: English, Display Name : Remove Ads, Description: You can purchase remove ads by tapping "Remove Ads" button. And you can also restore previous purchases by tapping "Restore" button. - Screenshot for Review (screen shot where "Remove Ads" button and "Restore" button exist)

//add in app product (consumable)
itunesconnect - Manage Your Apps - [specific app] - Manage In-App Purchases - Create New - Consumable - Select - Reference Name: testapp_coinpack1, Product ID: testapp_coinpack1 - 언어 추가 - 언어: English, Display Name : Coin Pack1 (250 Coins), Description: Coin Pack1 (250 Coins) - Screenshot for Review (screen shot where PurchaseConsumablePack button exists)

//add in app product (consumable)
itunesconnect - Manage Your Apps - [specific app] - Manage In-App Purchases - Create New - Consumable - Select - Reference Name: testapp_coinpack2, Product ID: testapp_coinpack2 - 언어 추가 - 언어: English, Display Name : Coin Pack2 (750 Coins), Description: Coin Pack2 (750 Coins) - Screenshot for Review (screen shot where PurchaseConsumablePack button exists)

//add in app product (consumable)
itunesconnect - Manage Your Apps - [specific app] - Manage In-App Purchases - Create New - Consumable - Select - Reference Name: testapp_coinpack3, Product ID: testapp_coinpack3 - 언어 추가 - 언어: English, Display Name : Coin Pack3 (2250 Coins), Description: Coin Pack3 (2250 Coins) - Screenshot for Review (screen shot where PurchaseConsumablePack button exists)

cf)Screenshot for Review (Screenshots must be 960x640, 960x600, 640x960, 640x920, 1136x640, 1136x600, 640x1136, 640x1096, 2208x1242, 1242x2208, 1334x750, 750x1334, 1024x768, 1024x748, 768x1024, 768x1004, 2048x1536, 2048x1496, 1536x2048 or 1536x2008 pixels.)

iOS Simulator - Hardware - Device - iPhone 6 Plus

Screen capture (1242x2208)

See doc/iOS Simulator Screen Shot_iPhone 6 Plus.png
```

should_agree_with_paid_applications_contracts

In app purchase screenshot for review (iPhone 6 Plus)

## Wp8 ##
```c
//add in app product (nonconsumable)
Windows Phone Dev Center - Dashboard - select Windows Phone Store - Apps - [specific app] - Products - Add in-app product - In-app product properties - In-app product alias: testapp_removeads, Product identifier: testapp_removeads, Product type: Durable, Product lifetime: Forever - Save -
Description - Product title: Remove Ads, Description: Purchase remove ads by tapping "Remove Ads" and restore by tapping "Restore"., Product image: (300x300 px PNG file) - Save - Submit

//add in app product (consumable)
Windows Phone Dev Center - Dashboard - select Windows Phone Store - Apps - [specific app] - Products - Add in-app product - In-app product properties - In-app product alias: testapp_coinpack1, Product identifier: testapp_coinpack1, Product type: Consumable - Save -
Description - Product title: Coin Pack1 (250 Coins), Description: Coin Pack1 (250 Coins), Product image: (300x300 px PNG file) - Save - Submit

//add in app product (consumable)
Windows Phone Dev Center - Dashboard - select Windows Phone Store - Apps - [specific app] - Products - Add in-app product - In-app product properties - In-app product alias: testapp_coinpack2, Product identifier: testapp_coinpack2, Product type: Consumable - Save -
Description - Product title: Coin Pack2 (750 Coins), Description: Coin Pack2 (750 Coins), Product image: (300x300 px PNG file) - Save - Submit

//add in app product (consumable)
Windows Phone Dev Center - Dashboard - select Windows Phone Store - Apps - [specific app] - Products - Add in-app product - In-app product properties - In-app product alias: testapp_coinpack3, Product identifier: testapp_coinpack3, Product type: Consumable - Save -
Description - Product title: Coin Pack3 (2250 Coins), Description: Coin Pack3 (2250 Coins), Product image: (300x300 px PNG file) - Save - Submit

ing
//Get YOUR_APP_ID from Windows Phone Dev Center and put it in "your wp8 project - Properties - WMAppManifest.xml - Packaging - Product ID"
Windows Phone Dev Center - Dashboard - select Windows Phone Store - Apps - [specific app] - Details - App ID: YOUR_APP_ID
```

# API #
```javascript

var androidApplicationLicenseKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtrOQsWiUYfQ65MjUam2zu2DgoBkOsaoelFQHWzRkAT+KHr1xPIOF5JUeQs/XWtNjRI4pavBrRveB3xnoKE+WxvILh4N+3Kl11/i0r9B6/LBae8V8WZpArEIIvh3rgowDGTO0B6sfWO71iP9EStmwziBI4sDOMuPensBSmj8bxj3hhNEzyRJvQbybdNgAD2xoy55+S0kgLHE3PbZwqogJf1pPIGSmhC2SXSrMXoJzxeMxM8/hN7VoVj9VAJxzOE3zR9he9npiDWGLsPnAIXggUN9Ys0h80YjwRl7GHLP0P/itBo28w4+qOqz2E34SFFInAqX7evtrMu3AkfYcX+FPuQIDAQAB";
var productIds = "testapp_removeads,testapp_coinpack1,testapp_coinpack2,testapp_coinpack3";
var existing_purchases = [];
var product_info = {};

document.addEventListener("deviceready", function(){

	window.iap.setUp(androidApplicationLicenseKey);

	//get all products' infos for all productIds
	window.iap.requestStoreListing(productIds, function (result){
	/*
	[
		{
			"productId": "sword001",
			"title": "Sword of Truths",
			"price": "Formatted price of the item, including its currency sign.",
			"description": "Very pointy sword. Sword knows if you are lying, so don't lie."
		},
		{
			"productId": "shield001",
			"title": "Shield of Peanuts",
			"price": "Formatted price of the item, including its currency sign.",
			"description": "A shield made entirely of peanuts."
		}
	]
	*/
	//alert(JSON.stringify(result));

		for (var i = 0 ; i < result.length; ++i){
			var p = result[i];

			product_info[p["productId"]] = { title: p["title"], price: p["price"] };

			alert("productId: "+p["productId"]);
			alert("title: "+p["title"]);
			alert("price: "+p["price"]);
		}
	}, function (error){
		alert("error: "+error);
	});
}, false);

function purchaseProduct(productId) {

	//purchase product id, put purchase product id info into server.
	window.iap.purchaseProduct(productId, function (result){
		alert("purchaseProduct");
	},
	function (error){
		alert("error: "+error);
	});
}

function consumeProduct(productId) {
	//consume product id, throw away purchase product id info from server.
	window.iap.consumeProduct(productId, function (result){
		alert("purchaseProduct");
	},
	function (error){
		alert("error: "+error);
	});
}

function restorePurchases() {
	//get user's purchased product ids which purchased before and not cunsumed.
	window.iap.restorePurchases(function (result){
		for (var i = 0 ; i < result.length; ++i){
			var p = result[i];

			if (self.existing_purchases.indexOf(p['productId']) === -1)
				self.existing_purchases.push(p['productId']);

			alert("productId: "+p['productId']);
		}
	},
	function (error){
		alert("error: "+error);
	});
}

function hasProduct = function (productId){
	return existing_purchases.indexOf(productId) !== -1;
};

```
# Examples #
example/basic/index.html

# Test #

[![](http://img.youtube.com/vi/xXrVb8E8gMM/0.jpg)](https://www.youtube.com/watch?v=xXrVb8E8gMM&feature=youtu.be "Youtube")

You can also run following test apk.
https://dl.dropboxusercontent.com/u/186681453/pluginsforcordova/iap/apk.html

## Android ##
```c
//publish as alpha test (recommend) or beta test instead of production.
google play developer console - [specific app] - APK - Alpha test - Upload as alpha test - Drag and drop apk and publish now as alpha test.

//add test user for iap
google play developer console - configuration - account detail - LICENSE TESTING - Gmail accounts with testing access

//add test community for alpha test or beta test download
google play developer console -
All applications -
[specific app] -
APK -
Alpha testers -
Manage list of testers -
Add Google groups or Google+ community: https://plus.google.com/communities/xxx (if you want make Google+ Community, go to this: https://plus.google.com/communities) -
Add -
Let test user download and install apk from this url: https://play.google.com/apps/testing/YOUR_PACKAGE (invite test user in your Google+ community, wait until this url is available, take hours)

test for iap requires real device.

cf)caution

if you want to test with local apk, use signed and exactly same version apk uploaded in google play store.

cf)error message

the item you requested is not available for purchase
==> In-activated Product Id, so Activate Product Id
http://stackoverflow.com/questions/13117081/the-item-you-requested-is-not-available-for-purchase

This product is not for sale
==> make testing apk version and published (normal or alpha or beta) apk version same.
```

## iOS ##
```c
test doest not requires publishing.
test requires real device.

//if you don't want to spend real money buying your own app, setup your test users and buy with test account.
//if you alreay logged in with other account, first log out (Setting - iTunes & App Store - Apple ID: xxx@xxx.com - Log out)
itunesconnect - Users and Roles - Sandbox Testers - +

//Xdk
XDK PROJECTS - projectname - BUILD SETTINGS - iOS - Provisioning Profile: production, Production Provisioning File: YOUR_PROVISION_FILE (.mobileprovision)
BUILD - CORVOVA 3,X HYBRID MOBILE APP PLATFORMS - iOS - Build - iOS CERTIFICATE - Edit - UPLOAD CERTIFICATE: YOUR_CERTIFICATE_FILE (.cer) - Go to Next Step - Download .ipa file - Drag it to the itunes and run it on the device

//Xcode
Select "Xcode - iPhone" (Ad Hoc)
- Product
- Run
```

## Wp8 ##
```c
```

# Useful links #

Cordova Plugins

http://cranberrygame.github.io?referrer=github

# Credits #

redpajama_set_name: RedPajamaGithub


text:
SET SCHEMA 'ohdsi';

CREATE EXTENSION "uuid-ossp";
CREATE EXTENSION tablefunc;

-- MP Claim and qualifier table: rdf_mp_claim_qualifier -----------------------------
CREATE TABLE ap_oo_mp_claim_qualifier AS
SELECT
mp_claim_id, method, relationship, precipitant, p_concept_code, p_role_concept_code, object, o_concept_code, o_role_concept_code
FROM (
WITH method AS (
SELECT mp_claim_id, mp_data_index, m.entered_value as method, m.inferred_value as inferred_method from method m),
p AS (
SELECT ca.id, q.qvalue, q.concept_code, q.vocabulary_id, q.qualifier_role_concept_code, cb.label
FROM mp_claim_annotation ca
JOIN oa_claim_body cb on cb.is_oa_body_of = ca.id
JOIN qualifier q on q.claim_body_id = cb.id
WHERE q.qualifier_role_concept_code = 'DIDEO_00000013'),
o AS (
SELECT ca.id, q.qvalue, q.concept_code, q.vocabulary_id, q.qualifier_role_concept_code, cb.label
FROM mp_claim_annotation ca
JOIN oa_claim_body cb on cb.is_oa_body_of = ca.id
JOIN qualifier q on q.claim_body_id = cb.id
WHERE q.qualifier_role_concept_code = 'DIDEO_00000012'),
r AS (
SELECT ca.id, q.qvalue
FROM mp_claim_annotation ca
JOIN oa_claim_body cb on cb.is_oa_body_of = ca.id
JOIN qualifier q on q.claim_body_id = cb.id
WHERE q.predicate = True)
SELECT method.mp_claim_id, method.mp_data_index, method.method, r.qvalue as relationship, p.qvalue as precipitant, p.concept_code as p_concept_code, p.qualifier_role_concept_code as p_role_concept_code, o.qvalue as object,
o.concept_code as o_concept_code, o.qualifier_role_concept_code as o_role_concept_code
from method
JOIN p ON p.id = method.mp_claim_id
JOIN o ON o.id = method.mp_claim_id
JOIN r ON r.id = method.mp_claim_id) AS tb

-- MP data table: rdf_mp_data -------------------------------------------------------
-- auc, cmax, clearance, halflife
CREATE TABLE ap_oo_mp_data AS
(SELECT d.mp_claim_id, d.mp_data_index, d.ev_supports, d.type as datatype, df.type as dftype, df.value, df.direction, uuid_generate_v4() as data_item_urn, uuid_generate_v4() as data_type_urn
FROM crosstab('SELECT df.data_body_id, df.data_field_type, df.value_as_string FROM data_field df ORDER BY 1,2')
AS df(data_body_id INTEGER, direction TEXT, type TEXT, value TEXT)
JOIN oa_data_body db ON df.data_body_id = db.id
JOIN mp_data_annotation d ON db.id = d.has_body
WHERE d.type = 'auc' or d.type = 'cmax' or d.type = 'clearance' or d.type = 'halflife');

-- MP material table: rdf_mp_material -----------------------------------------------
-- precipitant dose, object dose
CREATE TABLE ap_oo_mp_material AS
WITH m_field AS (
SELECT material_body_id as body_id, drugname, value, duration, formulation, regimens
FROM crosstab('SELECT mf.material_body_id, mf.material_field_type, mf.value_as_string FROM material_field mf ORDER BY 1,2')
AS mf(material_body_id INTEGER, drugname TEXT, duration TEXT, formulation TEXT, regimens TEXT, value TEXT)
WHERE mf.value != ''),
m_ann AS (
SELECT mann.mp_claim_id, mann.has_body, mann.mp_data_index, mann.ev_supports, mbody.material_type
FROM mp_material_annotation mann
JOIN oa_material_body mbody ON mann.has_body = mbody.id
WHERE material_type = 'precipitant_dose'
OR material_type = 'object_dose')
SELECT m_ann.mp_claim_id, m_ann.mp_data_index, m_ann.ev_supports, m_ann.material_type, m_field.drugname, m_field.value, m_field.duration, m_field.formulation, m_field.regimens
FROM m_ann
JOIN m_field on m_ann.has_body = m_field.body_id;

-- find same pair of drugs involved in annotations with different method
select * from ap_oo_mp_claim_qualifier a
join ap_oo_mp_claim_qualifier b
on a.precipitant = b.precipitant
and a. object = b.object
and a.mp_claim_id != b.mp_claim_id
and a.method != b.method;


text:
.clickableRow {
    cursor:pointer;
    border:1px solid black;
    padding-bottom: 2px;
}
.tableTd {
    padding: 5px;
    border: 1px solid gray;
}

.userGroupRoles {
    padding-left: 5px;
    cursor:pointer;
}


text:
Authentication and Security

    REST calls are anonymous by default.  The Spiffy UI framework offers security based on a scheme we've developed at Novell called tokenized identity.  This token-based security model supports simple authentication, single sign-on, and stateless security models.

Try it out

        Most of this application's REST calls are accessible without authentication, but we've added a little secured data....

Try it out with OAuth 2.0

        This page can also get secured data using OAuth 2.0.

    The Spiffy UI framework provides the client-side portion of this security model.  It connects to any authentication server you provide that implements this REST protocol for tokenized identity.  The Spiffy UI sample application provides a simple example of authentication with tokenized identity using Java servlets.  Java servlet filters are a popular choice for more complex applications.

    You can extend the servlets in this example, create your own, or implement your authentication server in any other technology that supports REST.

Tokenized identity

    The broad strokes of the authentication process are very simple.  You request some data, the server tells you it requires authentication, you get a token, and you give the token back to the server to get your data.  Just as a key allows you to open a door, your token gives you access to the data.

    Managing the token this way has many advantages.

    You don't have to trust the REST server.  No more giving your username and password to random web applications.  You can sign into one trusted server and use your token to sign in everywhere else.

    Single sign-on.  Since the tokens are generic, you can reuse them for multiple servers which accept tokenized identity and only log in once.

    Tokens can time out.  Typical J2EE sessions stay valid as long as they're actively used.  Tokens can add a built-in expiration date.  If a bad guy gets your token, it doesn't last.

    Tokens support stateless application servers.  REST has no session, and your tokens shouldn't either.  Combine your tokens with SAML and you'll get stateless authentication.  This scales to the cloud and keeps you logged in even if your server goes down.

Don't forget the cloud

    There's more to authentication than just a username and password.  Most companies are very careful about where their usernames and passwords can travel.  The IT department wants to keep passwords inside the network and off the Internet.

    Tokenized identity changes all that.  You can place the authentication server in the firewall and put the application outside.  Use SAML and they don't even have to talk to each other.  Make it possible for any company to connect to your system without risking their security.

Security customization

    Tokenized identity works for us, but it doesn't have to work for you.  When you use the Spiffy UI framework you can specify your own authentication handling.  You can customize our login dialog or write your own.  You can also skip security altogether and make your application anonymous.

    That's the overview.  Now let's look at some of the techie details.

    The easiest way to watch the authentication protocol is with Firebug.

    The first request gets a 401 response indicating that authentication is required.  Then the Spiffy UI framework requests a token and includes it in future requests.  This all goes through the authentication proxy.

Authentication proxy

    All REST calls are governed by the same-origin policy and may only call back to the server that served the JavaScript.  This is fine for most REST data calls, but single sign-on requires you to call to another server.

    The Spiffy UI framework supplies a REST authentication proxy service that makes it possible to authenticate against any server.  This proxy is implemented in AuthServlet.java.  The process works like this:

Client makes a request to server URL http://host:port/data-server-war-context/path-require-auth in order to access some resources.

Server looks for specific authentication header.  When it is not found, it returns JSON, indicating no authentication information is available. It will also send back a "WWW-Authenticate" response header, with the authentication server URL information, letting the client know that it needs to authenticate and how.

    WWW-Authenticate  X-OPAQUE uri="http://host:port/auth-path", signOffUri=""

Due to same-origin policy, client cannot directly contact the authentication server, which is on a different server. The client instead contacts a servlet (AuthServlet) that is in the same client WAR, forwarding on user credentials.

The servlet, which acts as a proxy, then contacts the authentication server at http://host2:port2/auth-server-war-context/auth-path to ask for an authentication token to access data server resources. To use the proxy servlet, it must be added to the web.xml of the client WAR.

    <servlet>
      <servlet-name>AuthServlet</servlet-name>
      <servlet-class>org.spiffyui.server.AuthServlet</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>AuthServlet</servlet-name>
      <url-pattern>/auth/*</url-pattern>
    </servlet-mapping>

If user's credentials are sufficient, the authentication server will return an authentication token in JSON format, such as:

    {"Token":"demouser-3f597a4d311a3e00"}

        to the proxy servlet, which then forwards the token back to the client to be saved in a browser cookie.

Client can now make the request to access the resources again on the data server at original URL:  http://host:port/data-server-war-context/path-require-auth, carrying a valid authentication token in the request header "Authorization":

    Authorization	X-OPAQUE demouser-3f597a4d311a3e00

Data server checks and validates the authentication token, then returns requested resources.

Login

    The authentication proxy is just a helper in this process.  The real work happens in the token exchange.  You can skip the proxy if you're calling from Java or any other language that doesn't use the same-origin policy.  Here's what happens when you click the login button above:

        (Optionally) Browser sends "GET" request to http://localhost:8080/authdata (implemented by SampleDataServlet).

        (Optionally) Server returns 401 (Unauthorized) with the NoAuthHeader fault payload, and "WWW-Authenticate" response header X-OPAQUE uri="http://localhost:8080/authserver", signOffUri=""

        The Spiffy UI framework shows the  LoginPanel in the browser, prompting user for username and password, and sends those credentials to the authentication proxy at http://localhost:8080/auth. Any username and password work in this sample.

    Proxy server AuthServlet contacts authentication server (implemented by SampleAuthServer) at http://localhost:8080/authserver to ask for authentication token.

        (Optionally) The authentication server rejects the authentication type.

        (Optionally) The proxy resends the authentication in the proper format.

        The authentication server generates a token and returns it to the client.  In order to make our sample easier, the token is always your username followed by "-" then a random alphanumeric character.

        The proxy server returns the token to the browser.

        The browser uses the token to request the data.

        (Optionally) The REST server can now call back to the authentication server to verify the token.  If the token is SAML, the REST server may be able to verify it without calling to a separate server.

        (Optionally) The authentication server responds that the token is valid.

        The REST server sends back the secured data.

    Now that the token exchange has been established, the browser can request data from the REST server without using the AuthServlet or the authentication server.

Logout

    The logout process goes through authentication proxy as well. You can skip the proxy if you're calling from Java or any other language that doesn't use the same-origin policy.  Here's what happens when you click the logout button in the header:

        The browser sends a request to the AuthServlet at http://localhost:8080/auth to perform the logout, passing on the user token.

        The AuthServlet issues a DELETE request to the authentication server (implemented by SampleAuthServer) at http://localhost:8080/authserver, forwarding on user token.

        (Optionally) The authentication server calls the specified sign-off URI to invalidate any cached tokens on the REST server.

        (Optionally) The REST server replies with a response 200 if the token has been successfully removed from the cache, or a 404 if the token isn't found.

        The authentication server returns a response 200 to the AuthServlet.

        The AuthServlet forwards the logout reponse to the browser; the browser then removes any cookies associated with the token, and refreshes the page to clear out all JavaScript memory.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>UniqueLabelsValidator</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.component

Class UniqueLabelsValidator

java.lang.Object

org.jetel.component.UniqueLabelsValidator

public class UniqueLabelsValidator
extends java.lang.Object

This class adds warnings to the configuration status
 when the labels of the validated metadata are not unique.

 The validation is performed because non-unique labels
 may cause problems with field mapping.

Field Summary

Fields

Modifier and Type
Field and Description

protected GraphElement
graphElement

protected ConfigurationStatus
status

Constructor Summary

Constructors

Constructor and Description

UniqueLabelsValidator()

UniqueLabelsValidator(ConfigurationStatus status,
                     GraphElement graphElement)

Method Summary

Methods

Modifier and Type
Method and Description

GraphElement
getGraphElement()

ConfigurationStatus
getStatus()

void
setGraphElement(GraphElement graphElement)

void
setStatus(ConfigurationStatus status)

protected void
validateLabel(java.lang.String label)

To be overridden by subclasses.

boolean
validateMetadata(ConfigurationStatus status,
                GraphElement graphElement,
                DataRecordMetadata metadata)

boolean
validateMetadata(DataRecordMetadata metadata)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

status

protected ConfigurationStatus status

graphElement

protected GraphElement graphElement

Constructor Detail

UniqueLabelsValidator

public UniqueLabelsValidator()

UniqueLabelsValidator

public UniqueLabelsValidator(ConfigurationStatus status,
                     GraphElement graphElement)

Parameters:

status -

graphElement -

Method Detail

getStatus

public ConfigurationStatus getStatus()

Returns:

the status

setStatus

public void setStatus(ConfigurationStatus status)

Parameters:

status - the status to set

getGraphElement

public GraphElement getGraphElement()

Returns:

the graphElement

setGraphElement

public void setGraphElement(GraphElement graphElement)

Parameters:

graphElement - the graphElement to set

validateLabel

protected void validateLabel(java.lang.String label)

To be overridden by subclasses.

Parameters:

label -

validateMetadata

public boolean validateMetadata(DataRecordMetadata metadata)

validateMetadata

public boolean validateMetadata(ConfigurationStatus status,
                       GraphElement graphElement,
                       DataRecordMetadata metadata)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
package com.github.liudaomanbu.excel.constant;

public enum Necessity {
  MUST, NOT_MUST;
}


text:
@interface CSClassCell : UITableViewCell
{
}
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UILabel *courseLabel;
@property (weak, nonatomic) IBOutlet UILabel *instructorLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *moreInfoButton;
@property (weak, nonatomic) IBOutlet UIImageView *moreInfoSeparator;

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fungi europ. exsicc. , Editio novo. Century 32(42)(nos 4101-4200): no. 4162 (1898)

#### Original name
Physalospora perversa Rehm, 1898

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=3">
    <link rel="stylesheet" type="text/css" href="css/common.css">
    <link rel="stylesheet" type="text/css" href="lib/tympanus/baraja.css">
    <title></title>

Coco Loko

Total bicycle rights in blog four loko raw denim ex, helvetica sapiente odio placeat.

Vermouth Land

Velit chambray fugiat, enim aesthetic esse ullamco typewriter.

Electrodynamics

Before they sold out PBR magna jean shorts non seitan ea. Dolor wolf pop-up.

Retinal Bliss

Locavore vero ad, before they sold out food truck bushwick helvetica.

Disco Fever

Cillum laboris consequat, qui elit retro next level skateboard freegan hella.

Serenity

Truffaut wes anderson hoodie 3 wolf moon labore, fugiat lomo iphone eiusmod vegan.

Dark Honor

Chillwave mustache pinterest, marfa seitan umami id farm-to-table iphone.

Nested Happiness

Minim post-ironic banksy american apparel iphone wayfarers.

Cherry Country

Sint vinyl Austin street art odd future id trust fund, terry richardson cray.

Cherry Country

Sint vinyl Austin street art odd future id trust fund, terry richardson cray.

Coco Loko

Total bicycle rights in blog four loko raw denim ex, helvetica sapiente odio placeat.

Vermouth Land

Velit chambray fugiat, enim aesthetic esse ullamco typewriter.

Electrodynamics

Before they sold out PBR magna jean shorts non seitan ea. Dolor wolf pop-up.

Retinal Bliss

Locavore vero ad, before they sold out food truck bushwick helvetica.

Disco Fever

Cillum laboris consequat, qui elit retro next level skateboard freegan hella.

Serenity

Truffaut wes anderson hoodie 3 wolf moon labore, fugiat lomo iphone eiusmod vegan.

Dark Honor

Chillwave mustache pinterest, marfa seitan umami id farm-to-table iphone.

Nested Happiness

Minim post-ironic banksy american apparel iphone wayfarers.

        <button type="button" id="nav-fanOther2" class="btn">ACTION</button>
        <button type="button" id="nav-prev" class="btn"><</button>
        <button type="button" id="nav-next" class="btn">></button>
        <button type="button" id="close" class="btn">close</button>


text:
import React from 'react'
import Promise from 'bluebird'
import Elm from './react-elm-components'
import _ from 'lodash'
const Rx = require('rxjs/Rx')
const ps = require('ps-node')
const path = require('path')
const exec = require('child_process').exec
const fs = require('fs')
const jsonfile = require('jsonfile')

import { tokenize } from './parser.js'
import { createTokenHash, cleanUpExpression } from './helpers'

Promise.config({
    cancellation: true
})

const writeJsonFile = Promise.promisify(jsonfile.writeFile)

const writeFile = Promise.promisify(fs.writeFile)

const basePath =
    process.env.NODE_ENV === 'development'
        ? 'app/compilers/elm-compiler'
        : 'dist/app/compilers/elm-compiler'

const tempFolderPath = `${basePath}/temp`
const codePath = tempFolderPath
const promisifiedExec = Promise.promisify(exec)

const numLinesAddedToPlaygroundFile = 5
function getFormattedError(error) {
    const errorStringPrefix =
        'Error: Command failed: cd temp && elm-make Main.elm --output=main.js && node main.js'
    const errorString = error.toString()
    const correctedErrorString = errorString
        .split('\n')
        .map(str => {
            if (str.match(/^\d+\|/)) {
                const indexOfPipe = str.indexOf('|')
                const lineNumber = str.split('|')[0]
                const newLineNumber = lineNumber - numLinesAddedToPlaygroundFile
                return newLineNumber + str.slice(indexOfPipe)
            } else {
                return str
            }
        })
        .join('\n')
        .slice(errorStringPrefix.length)

    return (

                {correctedErrorString}

    )
}

let lastOpenFilePath = ''
const packageJsonTemplateFileContents = require('./temp/elm-package-template.js')

function writeSourcesToElmPackageJson(
    templateFileContents,
    basePathForEditorCode
) {
    const packageJsonFilePath = `${tempFolderPath}/elm-package.json`

    let packageJsonFileContents = {
        ...templateFileContents,
        'source-directories': _.uniq(
            templateFileContents['source-directories'].concat([
                path.resolve(tempFolderPath),
                path.resolve(basePathForEditorCode)
            ])
        )
    }

    if (basePathForEditorCode !== path.resolve(tempFolderPath)) {
        let folderToCheck = basePathForEditorCode
        let filesInFolderToCheck
        let depth = 0
        const maxDepth = 25
        while (true && depth < maxDepth) {
            depth += 1
            filesInFolderToCheck = fs.readdirSync(folderToCheck)
            if (_.includes(filesInFolderToCheck, 'elm-package.json')) {
                const tempPackageJsonContent = jsonfile.readFileSync(
                    `${folderToCheck}/elm-package.json`
                )
                const sourceDirectories =
                    tempPackageJsonContent['source-directories']

                packageJsonFileContents = {
                    ...packageJsonFileContents,
                    'source-directories': _.uniq(
                        packageJsonFileContents['source-directories'].concat(
                            _.trimEnd(
                                `${folderToCheck}/${sourceDirectories}`,
                                '/.'
                            )
                        )
                    )
                }
                break
            } else {
                if (folderToCheck === '/') {
                    break
                }

                // something line '/Users' will result in ''. hence the ||
                folderToCheck =
                    _.initial(folderToCheck.split('/')).join('/') || '/'
            }
        }
    }

    return writeJsonFile(packageJsonFilePath, packageJsonFileContents, {
        spaces: 4
    })
}

/*
 * Update elm-package.json src property to include path from where the file is loaded
 * TODO - this function should be called just before the elm-make step and not in the beginning
 */
function updateFileSources(openFilePath = tempFolderPath) {
    if (
        (openFilePath && lastOpenFilePath === openFilePath) ||
        (!openFilePath && lastOpenFilePath === tempFolderPath)
    ) {
        return Promise.resolve(true)
    } else {
        lastOpenFilePath = openFilePath || tempFolderPath
    }

    return writeSourcesToElmPackageJson(
        packageJsonTemplateFileContents,
        openFilePath || tempFolderPath
    )
}

function writeCodeToFile(code) {
    const moduleName = 'UserCode'
    let codeToWrite = code.trim()

    // if module declaration is there in the panel, don't add it again
    if (code.startsWith('module ')) {
        const inlineModuleName = _.words(code)[1]
        codeToWrite = code.replace(
            `module ${inlineModuleName}`,
            'module UserCode'
        )
    } else if (code.trim() === '') {
        // if code panel is empty, insert a random function
        codeToWrite = `module ${moduleName} exposing (..)\n\nrandomIdentityFunction x = x`
    } else {
        codeToWrite = `module ${moduleName} exposing (..)\n\n${code}`
    }

    return writeFile(`${codePath}/${moduleName}.elm`, codeToWrite).then(
        () => moduleName
    ) // return the moduleName for playgroundFileWritercatch((err) => console.log('error writing file', `${codePath}/${moduleName}.elm`, err.toString()))
}

function hasSubscribed(code) {
    return code.indexOf('subscriptions') >= 0
}

function getToStrings(expression) {
    return expression.commands
        .map(command => {
            if (command.value.trim().length === 0) {
                return '"""\n"""'
            } else {
                const newLines = _.times(command.newlines, _.constant('\n'))
                    .map(() => '"""\n"""')
                    .join(',')
                return `Basics.toString (${cleanUpExpression(
                    command.value
                )}),${newLines}`
            }
        })
        .join(',')
}

function getSimpleExpressionChunk(expression) {
    return `(String.concat [${getToStrings(expression)}])`
}

function getGeneratedFrolicFileContent(
    expression,
    importStatements,
    statements,
    userModuleName
) {
    const mainFileTemplateForComponents = `import Html exposing (..)
${importStatements}
import ${userModuleName} exposing (..)`

    let fileContent = ''
    if (expression.value.startsWith('$view')) {
        fileContent = `module F${expression.hash} exposing (..)
${mainFileTemplateForComponents}
${statements}

frolicSpecialUpdate model _ = model
frolicSpecialView _ = ${_.trim(_.drop(expression.value.split(' ')).join(' '))}
main =
    beginnerProgram { model = 1 , view = frolicSpecialView , update = frolicSpecialUpdate }
`
    }

    return fileContent
}

function getGeneratedMainFileContent(
    expression,
    importStatements,
    statements,
    userModuleName
) {
    const mainFileTemplate = `import Html exposing (..)
import ${userModuleName} exposing (..)
${importStatements}
`

    const mainFileTemplateForComponents = `import Html exposing (..)
${importStatements}
import ${userModuleName} exposing (..)`

    let fileContent
    if (expression.type === 'frolicExpression') {
        fileContent = getGeneratedFrolicFileContent(
            expression,
            importStatements,
            statements,
            userModuleName
        )
    } else if (expression.type === 'renderExpression') {
        const appProgram = hasSubscribed(expression.value)
            ? 'program'
            : 'beginnerProgram'

        fileContent = `module F${expression.hash} exposing (..)
${mainFileTemplateForComponents}
${statements}
main =
    ${appProgram} ${_.drop(expression.value.split(' ')).join(' ')}`
    } else {
        fileContent = `module F${expression.hash} exposing (..)
import String
${mainFileTemplate}
${statements}
main =
    pre []
        [ text ${getSimpleExpressionChunk(expression)} ]`
    }

    return fileContent
}

function inCache(token) {
    return Boolean(cachedSources[token.hash])
}

const notInCache = _.negate(inCache)

function writeFilesForExpressions(tokens, userModuleName, codePath) {
    // eslint-disable-line no-shadow
    const importStatements = tokens
        .filter(notInCache)
        .filter(token => token.type === 'importStatement')
        .map(token => token.value)
        .join('\n')
    const statements = tokens
        .filter(notInCache)
        .filter(token => token.type === 'assignment')
        .map(token => token.value)
        .join('\n')
    const allExpressions = tokens.filter(
        token =>
            token.type === 'expression' ||
            token.type === 'renderExpression' ||
            token.type === 'frolicExpression'
    )
    const expressions = allExpressions.filter(notInCache)

    const fileWritePromises = expressions.map((expression, index) =>
        writeFile(
            `${codePath}/F${expression.hash}.elm`,
            getGeneratedMainFileContent(
                expression,
                importStatements,
                statements,
                userModuleName,
                index
            )
        )
    )
    return Promise.all(fileWritePromises).then(() => allExpressions)
}

let cachedSources = {} // eslint-disable-line vars-on-top, prefer-const

function getSource(module, expression) {
    // console.log(3)
    const fileName = `F${expression.hash}`

    if (!cachedSources[expression.hash]) {
        cachedSources[expression.hash] = fs
            .readFileSync(`${codePath}/${fileName}.js`)
            .toString()
    } else {
        // console.log('feed source from cache', expression.value, cachedSources[expression.hash])
    }

    // caching the evaled stuff doesn't work. so instead just caching the source code string. that's enough since it solve not running elm-make all the time
    eval(cachedSources[expression.hash]) // eslint-disable-line no-eval
    return module.exports[_.capitalize(fileName)]
}

let elmMakePromises = Promise.resolve()

/*
   * tokenize
   * create md5 keys for each token (based on expression value + file name)
   * store md5's current request in an array (for ordering the expressions. order of expression -> order of output in preview window)
   * name of the generated elm files would be - `F${md5OfTheToken}`
   * write user code to a file - weird place to put this. does not fit in the flow
   * before writing the elm file and using elm-make, check cache (cachedCompiledCode[md5OfTheToken])
   * if (foundInCache) { doNothing }
   * else {
   *   write elm file,
   *   use elm-make to generate .js file
   *   store the compiled code (.js file content) in the cache
   * }
   * now eval the compiled code for each playgroud expression
   * return elm-react components (key would be same as the generated md5 hashes! profit!)
   */
export function compile(code = '', playgroundCode = '', openFilePath) {
    elmMakePromises.cancel()
    // get folder path from file path
    const openFileFolderPath = openFilePath
        ? _.initial(openFilePath.split('/')).join('/')
        : null

    const tokens = tokenize(playgroundCode.trim())
    const tokensWithHashes = tokens.map(token => ({
        ...token,
        hash: createTokenHash(openFilePath || '', token, code.trim())
    }))

    return updateFileSources(openFileFolderPath)
        .then(() => writeCodeToFile(code))
        .then(userModuleName =>
            writeFilesForExpressions(tokensWithHashes, userModuleName, codePath)
        )
        .then(expressions => {
            // eslint-disable-line arrow-body-style
            return new Promise(() => {
                const allPromises = expressions
                    .filter(notInCache)
                    .map(expression => {
                        const fileName = `F${expression.hash}`
                        return promisifiedExec(
                            `cd ${codePath} && elm-make --yes ${fileName}.elm --output=${fileName}.js`
                        )
                    })

                // console.log(1)
                elmMakePromises = new Promise((resolve, reject, onCancel) => {
                    // on cancellation of promise
                    onCancel(() => {
                        ps.lookup(
                            {
                                command: 'elm-make',
                                psargs: 'ax'
                            },
                            (err, resultList) => {
                                if (err) {
                                    console.log(
                                        'error getting command info',
                                        err.toString()
                                    ) // eslint-disable-line no-console
                                } else {
                                    resultList.forEach(process => {
                                        ps.kill(
                                            process.pid,
                                            errorGettingProcessInfo => {
                                                if (errorGettingProcessInfo) {
                                                    console.error(
                                                        'Error killing process ',
                                                        errorGettingProcessInfo.toString()
                                                    ) // eslint-disable-line no-console
                                                }
                                            }
                                        )
                                    })
                                }
                            }
                        )
                    })
                    return Promise.all(allPromises)
                        .then(resolve)
                        .then(() => {
                            // console.log(2, expressions)
                            let sources = []

                            sources = expressions.map((expression, index) =>
                                getSource(module, expression, index)
                            )

                            const elmComponents = sources.map(
                                (source, index) => {
                                    // only return elm component is source is not corrupted
                                    // style={{display: 'flex', justifyContent: 'center'}}
                                    if (source && source.embed) {
                                        return (

                                                <Elm
                                                    key={
                                                        expressions[index].hash
                                                    }
                                                    src={source}
                                                />

                                        )
                                    } else {
                                        return a
                                    }
                                }
                            )

                            subscriber.next(elmComponents)
                        })
                        .catch(reject)
                }).catch(err => {
                    console.error('elm compilation error', err.toString()) // eslint-disable-line no-console
                    subscriber.next(getFormattedError(err))
                })
            })
        })
}

function onNewFileLoad(openFilePath) {
    const openFileFolderPath = openFilePath
        ? _.initial(openFilePath.split('/')).join('/')
        : null
    updateFileSources(openFileFolderPath)
}

function cleanUp() {
    if (subscriber) {
        subscriber.complete()
    }
    // const files = fs.readdirSync(tempFolderPath)
    // files.filter((file) => file !== 'Main.elm' && (file.split('.')[1] === 'elm' || file.split('.')[1] === 'js'))
    //         .map((file) => fs.unlink(tempFolderPath + '/' + file))
}

// TODO - to be done
function generateTests() {
    return '-- to be implemented'
}

function formatCode(code) {
    const cmd = `${basePath}/elm-format --stdin`

    function execFormat(callback) {
        const child = exec(cmd, callback)
        child.stdin.write(code)
        child.stdin.end()
        return child
    }

    return Promise.promisify(execFormat)()
    // .then((formattedCode) => _.drop(formattedCode.split('\n'), 2).join('\n'))
}

let subscriber = null
function getObservable() {
    return Rx.Observable.create(o => {
        subscriber = o
    })
}

function onCodeChange(code, playgroundCode, openFilePath) {
    return this.compile(code, playgroundCode, openFilePath)
}

function onPlaygroundCodeChange(code, playgroundCode, openFilePath) {
    return this.compile(code, playgroundCode, openFilePath)
}

// do some initialization work here
export function compiler() {
    return {
        compile,
        cleanUp,
        onNewFileLoad,
        generateTests,
        formatCode,
        outputStream: getObservable(),
        onCodeChange,
        onPlaygroundCodeChange,
        editorMode: 'elm',
        extensions: ['elm'],
        sampleCode: 'add x y = x + y',
        samplePlaygroundCode: 'add 1 2'
    }
}


text:
#include "include/utils/SkLuaCanvas.h"

#include "include/private/SkTo.h"
#include "include/utils/SkLua.h"
#include "src/core/SkStringUtils.h"

extern "C" {
    #include "lua.h"
    #include "lauxlib.h"
}

class AutoCallLua : public SkLua {
public:
    AutoCallLua(lua_State* L, const char func[], const char verb[]) : INHERITED(L) {
        lua_getglobal(L, func);
        if (!lua_isfunction(L, -1)) {
            int t = lua_type(L, -1);
            SkDebugf("--- expected function %d\n", t);
        }

        lua_newtable(L);
        this->pushString(verb, "verb");
    }

    ~AutoCallLua() {
        lua_State* L = this->get();
        if (lua_pcall(L, 1, 0, 0) != LUA_OK) {
            SkDebugf("lua err: %s\n", lua_tostring(L, -1));
        }
        lua_settop(L, -1);
    }

    void pushEncodedText(SkTextEncoding, const void*, size_t);

private:
    typedef SkLua INHERITED;
};

#define AUTO_LUA(verb)  AutoCallLua lua(fL, fFunc.c_str(), verb)

///////////////////////////////////////////////////////////////////////////////

void AutoCallLua::pushEncodedText(SkTextEncoding enc, const void* text, size_t length) {
    switch (enc) {
        case SkTextEncoding::kUTF8:
            this->pushString((const char*)text, length, "text");
            break;
        case SkTextEncoding::kUTF16:
            this->pushString(SkStringFromUTF16((const uint16_t*)text, length), "text");
            break;
        case SkTextEncoding::kGlyphID:
            this->pushArrayU16((const uint16_t*)text, SkToInt(length >> 1),
                               "glyphs");
            break;
        case SkTextEncoding::kUTF32:
            break;
    }
}

///////////////////////////////////////////////////////////////////////////////

void SkLuaCanvas::pushThis() {
    SkLua(fL).pushCanvas(this);
}

///////////////////////////////////////////////////////////////////////////////

SkLuaCanvas::SkLuaCanvas(int width, int height, lua_State* L, const char func[])
    : INHERITED(width, height)
    , fL(L)
    , fFunc(func) {
}

SkLuaCanvas::~SkLuaCanvas() {}

void SkLuaCanvas::willSave() {
    AUTO_LUA("save");
    this->INHERITED::willSave();
}

SkCanvas::SaveLayerStrategy SkLuaCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
    AUTO_LUA("saveLayer");
    if (rec.fBounds) {
        lua.pushRect(*rec.fBounds, "bounds");
    }
    if (rec.fPaint) {
        lua.pushPaint(*rec.fPaint, "paint");
    }

    (void)this->INHERITED::getSaveLayerStrategy(rec);
    // No need for a layer.
    return kNoLayer_SaveLayerStrategy;
}

bool SkLuaCanvas::onDoSaveBehind(const SkRect*) {
    // TODO
    return false;
}

void SkLuaCanvas::willRestore() {
    AUTO_LUA("restore");
    this->INHERITED::willRestore();
}

void SkLuaCanvas::didConcat44(const SkScalar m[16]) {
    // TODO
}
void SkLuaCanvas::didScale(SkScalar x, SkScalar y) {
    this->didConcat(SkMatrix::MakeScale(x, y));
}
void SkLuaCanvas::didTranslate(SkScalar x, SkScalar y) {
    this->didConcat(SkMatrix::MakeTrans(x, y));
}
void SkLuaCanvas::didConcat(const SkMatrix& matrix) {
    switch (matrix.getType()) {
        case SkMatrix::kTranslate_Mask: {
            AUTO_LUA("translate");
            lua.pushScalar(matrix.getTranslateX(), "dx");
            lua.pushScalar(matrix.getTranslateY(), "dy");
            break;
        }
        case SkMatrix::kScale_Mask: {
            AUTO_LUA("scale");
            lua.pushScalar(matrix.getScaleX(), "sx");
            lua.pushScalar(matrix.getScaleY(), "sy");
            break;
        }
        default: {
            AUTO_LUA("concat");
            // pushMatrix added in https://codereview.chromium.org/203203004/
            // Doesn't seem to have ever been working correctly since added
            // lua.pushMatrix(matrix);
            break;
        }
    }

    this->INHERITED::didConcat(matrix);
}

void SkLuaCanvas::didSetMatrix(const SkMatrix& matrix) {
    this->INHERITED::didSetMatrix(matrix);
}

void SkLuaCanvas::onClipRect(const SkRect& r, SkClipOp op, ClipEdgeStyle edgeStyle) {
    AUTO_LUA("clipRect");
    lua.pushRect(r, "rect");
    lua.pushBool(kSoft_ClipEdgeStyle == edgeStyle, "aa");
    this->INHERITED::onClipRect(r, op, edgeStyle);
}

void SkLuaCanvas::onClipRRect(const SkRRect& rrect, SkClipOp op, ClipEdgeStyle edgeStyle) {
    AUTO_LUA("clipRRect");
    lua.pushRRect(rrect, "rrect");
    lua.pushBool(kSoft_ClipEdgeStyle == edgeStyle, "aa");
    this->INHERITED::onClipRRect(rrect, op, edgeStyle);
}

void SkLuaCanvas::onClipPath(const SkPath& path, SkClipOp op, ClipEdgeStyle edgeStyle) {
    AUTO_LUA("clipPath");
    lua.pushPath(path, "path");
    lua.pushBool(kSoft_ClipEdgeStyle == edgeStyle, "aa");
    this->INHERITED::onClipPath(path, op, edgeStyle);
}

void SkLuaCanvas::onClipRegion(const SkRegion& deviceRgn, SkClipOp op) {
    AUTO_LUA("clipRegion");
    this->INHERITED::onClipRegion(deviceRgn, op);
}

void SkLuaCanvas::onDrawPaint(const SkPaint& paint) {
    AUTO_LUA("drawPaint");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawPoints(PointMode mode, size_t count,
                               const SkPoint pts[], const SkPaint& paint) {
    AUTO_LUA("drawPoints");
    lua.pushArrayPoint(pts, SkToInt(count), "points");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawOval(const SkRect& rect, const SkPaint& paint) {
    AUTO_LUA("drawOval");
    lua.pushRect(rect, "rect");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawArc(const SkRect& rect, SkScalar startAngle, SkScalar sweepAngle,
                            bool useCenter, const SkPaint& paint) {
    AUTO_LUA("drawArc");
    lua.pushRect(rect, "rect");
    lua.pushScalar(startAngle, "startAngle");
    lua.pushScalar(sweepAngle, "sweepAngle");
    lua.pushBool(useCenter, "useCenter");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawRect(const SkRect& rect, const SkPaint& paint) {
    AUTO_LUA("drawRect");
    lua.pushRect(rect, "rect");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
    AUTO_LUA("drawRRect");
    lua.pushRRect(rrect, "rrect");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
                               const SkPaint& paint) {
    AUTO_LUA("drawDRRect");
    lua.pushRRect(outer, "outer");
    lua.pushRRect(inner, "inner");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
    AUTO_LUA("drawPath");
    lua.pushPath(path, "path");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawBitmap(const SkBitmap& bitmap, SkScalar x, SkScalar y,
                               const SkPaint* paint) {
    AUTO_LUA("drawBitmap");
    if (paint) {
        lua.pushPaint(*paint, "paint");
    }
}

void SkLuaCanvas::onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
                                   const SkPaint* paint, SrcRectConstraint) {
    AUTO_LUA("drawBitmapRect");
    if (paint) {
        lua.pushPaint(*paint, "paint");
    }
}

void SkLuaCanvas::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst,
                                   const SkPaint* paint) {
    AUTO_LUA("drawBitmapNine");
    if (paint) {
        lua.pushPaint(*paint, "paint");
    }
}

void SkLuaCanvas::onDrawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint* paint) {
    AUTO_LUA("drawImage");
    if (paint) {
        lua.pushPaint(*paint, "paint");
    }
}

void SkLuaCanvas::onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
                                  const SkPaint* paint, SrcRectConstraint) {
    AUTO_LUA("drawImageRect");
    if (paint) {
        lua.pushPaint(*paint, "paint");
    }
}

void SkLuaCanvas::onDrawTextBlob(const SkTextBlob *blob, SkScalar x, SkScalar y,
                                 const SkPaint &paint) {
    AUTO_LUA("drawTextBlob");
    lua.pushTextBlob(blob, "blob");
    lua.pushScalar(x, "x");
    lua.pushScalar(y, "y");
    lua.pushPaint(paint, "paint");
}

void SkLuaCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
                                const SkPaint* paint) {
    AUTO_LUA("drawPicture");
    // call through so we can see the nested picture ops
    this->INHERITED::onDrawPicture(picture, matrix, paint);
}

void SkLuaCanvas::onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) {
    AUTO_LUA("drawDrawable");
    // call through so we can see the nested ops
    this->INHERITED::onDrawDrawable(drawable, matrix);
}

void SkLuaCanvas::onDrawVerticesObject(const SkVertices*, const SkVertices::Bone[], int,
                                       SkBlendMode, const SkPaint& paint) {
    AUTO_LUA("drawVertices");
    lua.pushPaint(paint, "paint");
}


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of Qt Designer.  This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//

#ifndef QDESIGNER_QSETTINGS_H
#define QDESIGNER_QSETTINGS_H

#include "shared_global_p.h"

#include <QtDesigner/QDesignerSettingsInterface>

#include <QtCore/QSettings>

QT_BEGIN_NAMESPACE

//  Implements QDesignerSettingsInterface by calls to QSettings
class QDESIGNER_SHARED_EXPORT QDesignerQSettings : public QDesignerSettingsInterface
{
public:
    QDesignerQSettings();

    void beginGroup(const QString &prefix) Q_DECL_OVERRIDE;
    virtual void endGroup();

    bool contains(const QString &key) const Q_DECL_OVERRIDE;
    void setValue(const QString &key, const QVariant &value) Q_DECL_OVERRIDE;
    QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const Q_DECL_OVERRIDE;
    void remove(const QString &key) Q_DECL_OVERRIDE;

    // The application name to be used for settings. Allows for including
    // the Qt version to prevent settings of different Qt versions from
    // interfering.
    static QString settingsApplicationName();

private:
    QSettings m_settings;
};

QT_END_NAMESPACE

#endif // QDESIGNER_QSETTINGS_H


text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.BaseFluent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

/** Generated */
@SuppressWarnings(value = "unchecked")
public class V1NonResourceRuleFluentImpl<A extends V1NonResourceRuleFluent<A>> extends BaseFluent<A>
    implements V1NonResourceRuleFluent<A> {
  public V1NonResourceRuleFluentImpl() {}

  public V1NonResourceRuleFluentImpl(V1NonResourceRule instance) {
    this.withNonResourceURLs(instance.getNonResourceURLs());

    this.withVerbs(instance.getVerbs());
  }

  private List<String> nonResourceURLs;
  private List<String> verbs;

  public A addToNonResourceURLs(Integer index, String item) {
    if (this.nonResourceURLs == null) {
      this.nonResourceURLs = new ArrayList<String>();
    }
    this.nonResourceURLs.add(index, item);
    return (A) this;
  }

  public A setToNonResourceURLs(Integer index, String item) {
    if (this.nonResourceURLs == null) {
      this.nonResourceURLs = new ArrayList<String>();
    }
    this.nonResourceURLs.set(index, item);
    return (A) this;
  }

  public A addToNonResourceURLs(java.lang.String... items) {
    if (this.nonResourceURLs == null) {
      this.nonResourceURLs = new ArrayList<String>();
    }
    for (String item : items) {
      this.nonResourceURLs.add(item);
    }
    return (A) this;
  }

  public A addAllToNonResourceURLs(Collection<String> items) {
    if (this.nonResourceURLs == null) {
      this.nonResourceURLs = new ArrayList<String>();
    }
    for (String item : items) {
      this.nonResourceURLs.add(item);
    }
    return (A) this;
  }

  public A removeFromNonResourceURLs(java.lang.String... items) {
    for (String item : items) {
      if (this.nonResourceURLs != null) {
        this.nonResourceURLs.remove(item);
      }
    }
    return (A) this;
  }

  public A removeAllFromNonResourceURLs(Collection<String> items) {
    for (String item : items) {
      if (this.nonResourceURLs != null) {
        this.nonResourceURLs.remove(item);
      }
    }
    return (A) this;
  }

  public List<String> getNonResourceURLs() {
    return this.nonResourceURLs;
  }

  public String getNonResourceURL(Integer index) {
    return this.nonResourceURLs.get(index);
  }

  public String getFirstNonResourceURL() {
    return this.nonResourceURLs.get(0);
  }

  public String getLastNonResourceURL() {
    return this.nonResourceURLs.get(nonResourceURLs.size() - 1);
  }

  public String getMatchingNonResourceURL(Predicate<String> predicate) {
    for (String item : nonResourceURLs) {
      if (predicate.test(item)) {
        return item;
      }
    }
    return null;
  }

  public Boolean hasMatchingNonResourceURL(Predicate<String> predicate) {
    for (String item : nonResourceURLs) {
      if (predicate.test(item)) {
        return true;
      }
    }
    return false;
  }

  public A withNonResourceURLs(List<String> nonResourceURLs) {
    if (nonResourceURLs != null) {
      this.nonResourceURLs = new ArrayList();
      for (String item : nonResourceURLs) {
        this.addToNonResourceURLs(item);
      }
    } else {
      this.nonResourceURLs = null;
    }
    return (A) this;
  }

  public A withNonResourceURLs(java.lang.String... nonResourceURLs) {
    if (this.nonResourceURLs != null) {
      this.nonResourceURLs.clear();
    }
    if (nonResourceURLs != null) {
      for (String item : nonResourceURLs) {
        this.addToNonResourceURLs(item);
      }
    }
    return (A) this;
  }

  public Boolean hasNonResourceURLs() {
    return nonResourceURLs != null && !nonResourceURLs.isEmpty();
  }

  public A addToVerbs(Integer index, String item) {
    if (this.verbs == null) {
      this.verbs = new ArrayList<String>();
    }
    this.verbs.add(index, item);
    return (A) this;
  }

  public A setToVerbs(Integer index, String item) {
    if (this.verbs == null) {
      this.verbs = new ArrayList<String>();
    }
    this.verbs.set(index, item);
    return (A) this;
  }

  public A addToVerbs(java.lang.String... items) {
    if (this.verbs == null) {
      this.verbs = new ArrayList<String>();
    }
    for (String item : items) {
      this.verbs.add(item);
    }
    return (A) this;
  }

  public A addAllToVerbs(Collection<String> items) {
    if (this.verbs == null) {
      this.verbs = new ArrayList<String>();
    }
    for (String item : items) {
      this.verbs.add(item);
    }
    return (A) this;
  }

  public A removeFromVerbs(java.lang.String... items) {
    for (String item : items) {
      if (this.verbs != null) {
        this.verbs.remove(item);
      }
    }
    return (A) this;
  }

  public A removeAllFromVerbs(Collection<String> items) {
    for (String item : items) {
      if (this.verbs != null) {
        this.verbs.remove(item);
      }
    }
    return (A) this;
  }

  public List<String> getVerbs() {
    return this.verbs;
  }

  public String getVerb(Integer index) {
    return this.verbs.get(index);
  }

  public String getFirstVerb() {
    return this.verbs.get(0);
  }

  public String getLastVerb() {
    return this.verbs.get(verbs.size() - 1);
  }

  public String getMatchingVerb(Predicate<String> predicate) {
    for (String item : verbs) {
      if (predicate.test(item)) {
        return item;
      }
    }
    return null;
  }

  public Boolean hasMatchingVerb(Predicate<String> predicate) {
    for (String item : verbs) {
      if (predicate.test(item)) {
        return true;
      }
    }
    return false;
  }

  public A withVerbs(List<String> verbs) {
    if (verbs != null) {
      this.verbs = new ArrayList();
      for (String item : verbs) {
        this.addToVerbs(item);
      }
    } else {
      this.verbs = null;
    }
    return (A) this;
  }

  public A withVerbs(java.lang.String... verbs) {
    if (this.verbs != null) {
      this.verbs.clear();
    }
    if (verbs != null) {
      for (String item : verbs) {
        this.addToVerbs(item);
      }
    }
    return (A) this;
  }

  public Boolean hasVerbs() {
    return verbs != null && !verbs.isEmpty();
  }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    V1NonResourceRuleFluentImpl that = (V1NonResourceRuleFluentImpl) o;
    if (nonResourceURLs != null
        ? !nonResourceURLs.equals(that.nonResourceURLs)
        : that.nonResourceURLs != null) return false;
    if (verbs != null ? !verbs.equals(that.verbs) : that.verbs != null) return false;
    return true;
  }

  public int hashCode() {
    return java.util.Objects.hash(nonResourceURLs, verbs, super.hashCode());
  }

  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    if (nonResourceURLs != null && !nonResourceURLs.isEmpty()) {
      sb.append("nonResourceURLs:");
      sb.append(nonResourceURLs + ",");
    }
    if (verbs != null && !verbs.isEmpty()) {
      sb.append("verbs:");
      sb.append(verbs);
    }
    sb.append("}");
    return sb.toString();
  }
}


text:
<?php

class InventoryController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
			//$confirmation_code = str_random(30);
		    $data =  Input::except(array('_token')) ;
            $rule  =  array(
                    'prodId'       => 'required',
                    'pname'      => 'required',
                    'descr'      => 'required',
                    'location'   => 'required',
                    'price'      => 'required',
                    'pvat'      => 'required',
                    'sales'      => 'required',
                    'svat'      => 'required',
                    'quantity'      => 'required',
                    'swarn'      => 'required'
                ) ;

			/*$message = array(
			                   'prodId.required' => 'Product Must Have a Serial Number',
			                   'pname.required' => 'Product Name Required',
			                   'descr.required' => 'Brief Short Product Description',
			                   'price.required' => 'Enter Product price',
			                   'pvat.required' => 'VAT for Price',
			                   'sales.required' => 'Sales Price Required',
			                   'svat.required' => 'VAT for sales',
			                   'quantity.required' => 'Must enter quantity of stock',
			                   'swarn.required' => 'Reorder level',
			               );*/

            $validator = Validator::make($data,$rule);

	        if($validator->fails())
	        {
	            return Redirect::back()->withInput()->withErrors($validator);
	        }

	        else
	        {
			    $newproduct = new Products;
			    $newproduct->prodId = Input::get('prodId');
			    $newproduct->pname = Input::get('pname');
			    $newproduct->descr = Input::get('descr');
			    $newproduct->category = Input::get('cat');
			    $newproduct->location = Input::get('location');
			    $newproduct->purl = Input::get('purl');
			    $newproduct->price = Input::get('price');
			    $newproduct->pvat = Input::get('pvat');
			    $newproduct->sales = Input::get('sales');
			    $newproduct->svat = Input::get('svat');
			    $newproduct->quantity = Input::get('quantity');
			    $newproduct->swarn = Input::get('swarn');
			    $newproduct->save();

			    return Redirect::to('/back_end/manageProduct')->with('success', true)
                    		->with('message','Product Added Successfully');
				        }
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/*
	function to query and return information in the product tabel
	*/

	public function displayInformation(){
		//query all information from the table

		$results = DB::table('product')->get();
		//$list = DB::table('categories')->get();

		return View::make('/back_end/manageProduct')
		->with('results', $results);

	}

	public function display(){
		//query all information from the table

		$list = DB::table('categories')->get();
		//$list = DB::table('categories')->get();

		return View::make('/back_end/addProduct')
		->with('list', $list);

	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
		$data = DB::table('product')->get($id);
		$data->delete();

		return View::make('/back_end/manageProduct')->with('message','Row is deleted');
	}

}


text:
<?php

declare(strict_types=1);

namespace Symplify\NetteAdapterForSymfonyBundles\Tests\Transformer;

use Nette\DI\ServiceDefinition;
use PHPUnit\Framework\TestCase;
use stdClass;
use Symplify\NetteAdapterForSymfonyBundles\Transformer\ArgumentsTransformer;
use Symplify\NetteAdapterForSymfonyBundles\Transformer\ServiceDefinitionTransformer;

final class ServiceDefinitionTransformerTest extends TestCase
{
    /**
     * @var ServiceDefinitionTransformer
     */
    private $serviceDefinitionTransformer;

    protected function setUp()
    {
        $this->serviceDefinitionTransformer = new ServiceDefinitionTransformer(new ArgumentsTransformer());
    }

    public function testFactory()
    {
        $netteServiceDefinition = (new ServiceDefinition())->setFactory(stdClass::class, [1, 2, 3]);

        $symfonyServiceDefinition = $this->serviceDefinitionTransformer->transformFromNetteToSymfony(
            $netteServiceDefinition
        );

        $this->assertSame(stdClass::class, $symfonyServiceDefinition->getFactory());
        $this->assertSame([1, 2, 3], $symfonyServiceDefinition->getArguments());
    }
}


text:
package org.apache.pig.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.newplan.Operator;
import org.apache.pig.newplan.logical.expression.ConstantExpression;
import org.apache.pig.newplan.logical.expression.LogicalExpressionPlan;
import org.apache.pig.newplan.logical.relational.LOFilter;
import org.apache.pig.newplan.logical.relational.LogicalPlan;
import org.junit.Test;

public class TestPigScriptParser extends TestCase {

    @Test
    public void testParserWithEscapeCharacters() throws Exception {

        // All the needed variables
        PigContext pigContext = new PigContext(ExecType.LOCAL, new Properties()) ;
        PigServer pigServer = new PigServer( pigContext );
        pigContext.connect();

        String tempFile = this.prepareTempFile() ;

    	String query = String.format("A = LOAD '%s' ;", Util.encodeEscape(tempFile)) ;
        // Start the real parsing job
        {
        	// Initial statement
        	Util.buildLp(pigServer, query);
        }

        {
        	// Normal condition
        	String q = query + "B = filter A by $0 eq 'This is a test string' ;" ;
        	checkParsedConstContent(pigServer, pigContext, q, "This is a test string") ;
        }

        {
        	// single-quote condition
        	String q = query + "B = filter A by $0 eq 'This is a test \\'string' ;" ;
        	checkParsedConstContent(pigServer, pigContext,
        	                        q, "This is a test 'string") ;
        }

        {
            // escaping dot
            // the reason we have 4 backslashes below is we really want to put two backslashes but
            // since this is to be represented in a Java String, we escape each backslash with one more
            // backslash - hence 4. In a pig script in a file, this would be
            // \\.string
            String q = query + "B = filter A by $0 eq 'This is a test \\\\.string' ;" ;
            checkParsedConstContent(pigServer, pigContext,
                                    q, "This is a test \\.string") ;
        }

        {
        	// newline condition
        	String q = query + "B = filter A by $0 eq 'This is a test \\nstring' ;" ;
        	checkParsedConstContent(pigServer, pigContext,
        	                        q, "This is a test \nstring") ;
        }

        {
        	// Unicode
        	String q = query + "B = filter A by $0 eq 'This is a test \\uD30C\\uC774string' ;" ;
        	checkParsedConstContent(pigServer, pigContext,
        	                        q, "This is a test \uD30C\uC774string") ;
        }
    }

    @Test
    public void testDefineUDF() throws Exception {
        String inputData[] = {
                "dshfdskfwww.xyz.com/sportsjoadfjdslpdshfdskfwww.xyz.com/sportsjoadfjdsl" ,
                "kas;dka;sd" ,
                "jsjsjwww.xyz.com/sports" ,
                "jsdLSJDcom/sports" ,
                "wwwJxyzMcom/sports"
        };
        File f = Util.createFile(inputData);
        String[] queryLines = new String[] {
                // the reason we have 4 backslashes below is we really want to put two backslashes but
                // since this is to be represented in a Java String, we escape each backslash with one more
                // backslash - hence 4. In a pig script in a file, this would be
                // www\\.xyz\\.com
                "define minelogs org.apache.pig.test.RegexGroupCount('www\\\\.xyz\\\\.com/sports');" ,
        		"A = load 'file://" + f.getAbsolutePath() + "'  using PigStorage() as (source : chararray);" ,
        		"B = foreach A generate minelogs(source) as sportslogs;" };
        PigServer ps = new PigServer(ExecType.LOCAL);
        for (String line : queryLines) {
            ps.registerQuery(line);
        }
        Iterator<Tuple> it = ps.openIterator("B");
        int[] expectedResults = new int[] {2,0,1,0,0};
        int i = 0;
        while(it.hasNext()) {
            Tuple t = it.next();
            assertEquals(expectedResults[i++], t.get(0));
        }
    }

   @Test
	public void testSplitWithNotEvalCondition() throws Exception {
	    String defineQ = "define minelogs org.apache.pig.test.RegexGroupCount('www\\\\.xyz\\\\.com/sports');";
	    String defineL = "a = load 'nosuchfile' " +
	            " using PigStorage() as (source : chararray);";
	    String defineSplit = "SPLIT a INTO a1 IF (minelogs(source) > 0 ), a2 IF (NOT (minelogs(source)>0));";//    (NOT ( minelogs(source) ) > 0) ;";
	    PigServer ps = new PigServer(ExecType.LOCAL);
	    ps.registerQuery(defineQ);
	    ps.registerQuery(defineL);
	    try{
	        ps.registerQuery(defineSplit);
	    }catch(FrontendException e)
	    {
	        Assert.fail(e.getMessage());
	    }
	}

    @Test
    public void testErrorMessageUndefinedAliasInGroupByStatement() throws Exception {
        String queryA = "A = load 'nosuchfile'  using PigStorage() as (f1:chararray,f2:chararray);";
        String queryB = "B = GROUP B by f1;";
        PigServer ps = new PigServer(ExecType.LOCAL);
        ps.registerQuery(queryA);
        try{
            ps.registerQuery(queryB);
        }catch (FrontendException e)
        {
            Assert.assertTrue(e.getMessage().contains("Undefined alias:"));
            return;
        }
        Assert.fail();
    }

	private void checkParsedConstContent(PigServer pigServer,
                                             PigContext pigContext,
                                             String query,
                                             String expectedContent)
                                        throws Exception {
        pigContext.connect();
        LogicalPlan lp = Util.buildLp(pigServer, query + "store B into 'output';");
        // Digging down the tree
        Operator load = lp.getSources().get(0);
        Operator filter = lp.getSuccessors( load ).get(0);
        LogicalExpressionPlan comparisonPlan = ((LOFilter)filter).getFilterPlan();
        List<Operator> comparisonPlanRoots = comparisonPlan.getSinks();
        Operator compRootOne = comparisonPlanRoots.get(0);
        Operator compRootTwo = comparisonPlanRoots.get(1);

        // Here is the actual check logic
        if (compRootOne instanceof ConstantExpression) {
            assertTrue("Must be equal",
                        ((String)((ConstantExpression)compRootOne).getValue()).equals(expectedContent)) ;
        }
        // If not left, it must be right.
        else {
            assertTrue("Must be equal",
                        ((String)((ConstantExpression)compRootTwo).getValue()).equals(expectedContent)) ;
        }
    }

    private String prepareTempFile() throws IOException {
        File inputFile = File.createTempFile("test", "txt");
        inputFile.deleteOnExit() ;
        PrintStream ps = new PrintStream(new FileOutputStream(inputFile));
        ps.println("hohoho") ;
        ps.close();
        return inputFile.getPath() ;
    }

}


text:
/**
 * auto generate by WallE, do not modify it...
 * @constructor
 */
function Module1() {
    //#region interface

    this.pmsg = function(oMsg){
        CHNBModule.bus.Module1.actor.pmsg(oMsg);
    };

    this.msg = function(oMsg){
        CHNBModule.bus.Module1.actor.msg(oMsg);
    };

    //#endregion

    //#region Fields

    this.Module1 = CHNBMock.getInstance("Module1");

    //#endregion
}


text:
using System.Composition;
using Microsoft.ApiDesignGuidelines.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;

namespace Microsoft.ApiDesignGuidelines.CSharp.Analyzers
{
    /// <summary>
    /// CA1716: Identifiers should not match keywords
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    public sealed class CSharpIdentifiersShouldNotMatchKeywordsFixer : IdentifiersShouldNotMatchKeywordsFixer
    {
    }
}


text:
package com.arialyy.aria.core.upload.target;

import com.arialyy.aria.core.common.AbsBuilderTarget;
import com.arialyy.aria.core.common.AbsNormalTarget;

/**
 * @author aria
 * Date: 2019-09-05
 */
public class UTargetFactory {

  public static volatile UTargetFactory INSTANCE;

  private UTargetFactory() {

  }

  public static UTargetFactory getInstance() {

    if (INSTANCE == null) {
      synchronized (UTargetFactory.class) {
        if (INSTANCE == null) {
          INSTANCE = new UTargetFactory();
        }
      }
    }

    return INSTANCE;
  }

  public <T extends AbsNormalTarget> T generateNormalTarget(Class<T> clazz, long taskId) {
    T target = null;
    if (clazz == HttpNormalTarget.class) {
      target = (T) new HttpNormalTarget(taskId);
    } else if (clazz == FtpNormalTarget.class) {
      target = (T) new FtpNormalTarget(taskId);
    }

    return target;
  }

  public <T extends AbsBuilderTarget> T generateBuilderTarget(Class<T> clazz, String url) {
    T target = null;
    if (clazz == HttpBuilderTarget.class) {
      target = (T) new HttpBuilderTarget(url);
    } else if (clazz == FtpBuilderTarget.class) {
      target = (T) new FtpBuilderTarget(url);
    }

    return target;
  }
}


text:
using System;
using Pdelvo.Minecraft.Network;

namespace Pdelvo.Minecraft.Protocol.Packets
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// </remarks>
    [PacketUsage(PacketUsage.Both)]
    public class Experience : Packet
    {
        /// <summary>
        ///   Initializes a new instance of the <see cref="Experience" /> class.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public Experience()
        {
            Code = 0x2B;
        }

        /// <summary>
        ///   Gets or sets the current experience.
        /// </summary>
        /// <value> The current experience. </value>
        /// <remarks>
        /// </remarks>
        public float CurrentExperience { get; set; }

        // Changed to float in 20
        /// <summary>
        ///   Gets or sets the level.
        /// </summary>
        /// <value> The level. </value>
        /// <remarks>
        /// </remarks>
        public short Level { get; set; }

        //Changed to short in 20
        /// <summary>
        ///   Gets or sets the total experience.
        /// </summary>
        /// <value> The total experience. </value>
        /// <remarks>
        /// </remarks>
        public short TotalExperience { get; set; }

        /// <summary>
        ///   Receives the specified reader.
        /// </summary>
        /// <param name="reader"> The reader. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnReceive(BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");
            CurrentExperience = reader.ReadSingle ();
            Level = reader.ReadInt16 ();
            TotalExperience = reader.ReadInt16 ();
        }

        /// <summary>
        ///   Sends the specified writer.
        /// </summary>
        /// <param name="writer"> The writer. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnSend(BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);
            writer.Write(CurrentExperience);
            writer.Write(Level);
            writer.Write(TotalExperience);
        }
    }
}


text:
<?php
namespace inklabs\kommerce\EntityDTO\Builder;

use inklabs\kommerce\Entity\Pagination;
use inklabs\kommerce\EntityDTO\PaginationDTO;

class PaginationDTOBuilder implements DTOBuilderInterface
{
    /** @var Pagination */
    protected $entity;

    /** @var PaginationDTO */
    protected $entityDTO;

    public function __construct(Pagination $pagination)
    {
        $this->entity = $pagination;

        $this->entityDTO = new PaginationDTO;
        $this->entityDTO->maxResults      = $this->entity->getMaxResults();
        $this->entityDTO->page            = $this->entity->getPage();
        $this->entityDTO->total           = $this->entity->getTotal();
        $this->entityDTO->isTotalIncluded = $this->entity->isTotalIncluded();
    }

    protected function preBuild()
    {
    }

    public function build()
    {
        $this->preBuild();
        unset($this->entity);
        return $this->entityDTO;
    }
}


text:
import { Component, OnInit, AfterViewInit, Input, ViewChild, ElementRef, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-element-wrapper',
  templateUrl: './element-wrapper.component.html',
  styles: [
  ]
})
export class ElementWrapperComponent implements AfterViewInit, OnChanges {

  @Input() element: HTMLElement;
  @Input() windowId = '';
  @Input() activeWindowId = '';

  @ViewChild('elRef', { static: true }) elRef: ElementRef<HTMLDivElement>;

  constructor() { }

  ngAfterViewInit(): void {
    this.handleRender();
  }

  ngOnChanges(changes: SimpleChanges) {
    this.handleRender();
  }

  handleRender() {
    if (this.element) {
      if (this.windowId && this.windowId !== this.activeWindowId) {
        return;
      }
      this.elRef.nativeElement.appendChild(this.element);
    }
  }

}


text:
<?php declare(strict_types=1);

namespace Nirvarnia\Exception;

use Exception;

/**
 * Exception type to represent an unexpected value, which signifies an error,
 * returned from a function.
 */
class UnexpectedError extends Exception
{
    // No body.
}


text:
package defaults

import (
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/openshift/installer/pkg/types/libvirt"
)

func defaultNetwork() *libvirt.Network {
	return &libvirt.Network{
		IfName: defaultIfName,
	}
}

func TestSetNetworkDefaults(t *testing.T) {
	cases := []struct {
		name     string
		network  *libvirt.Network
		expected *libvirt.Network
	}{
		{
			name:     "empty",
			network:  &libvirt.Network{},
			expected: defaultNetwork(),
		},
		{
			name: "IfName present",
			network: &libvirt.Network{
				IfName: "test-if",
			},
			expected: func() *libvirt.Network {
				n := defaultNetwork()
				n.IfName = "test-if"
				return n
			}(),
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			SetNetworkDefaults(tc.network)
			assert.Equal(t, tc.expected, tc.network, "unexpected network")
		})
	}
}


text:
<?php
namespace Specification;

class Exception extends \Exception
{

    public $description;

    const PARSER_ERROR = 'PARSER_ERROR';

    const SPEC_UNAVAILABLE = 'SPEC_UNAVAILABLE';
    const SPEC_REQUIRED = 'SPEC_REQUIRED';
    const SPEC_INVALID = 'SPEC_INVALID';

    const SCHEMA_MISSING = 'SCHEMA_MISSING';
    const SCHEMA_ERROR = 'SCHEMA_ERROR';
    const SCHEMA_VIOLATION = 'SCHEMA_VIOLATION';

    const PROPERTY_SPEC_MISSING = 'PROPERTY_SPEC_MISSING';

    const REQUEST_CASTING_FAILED = 'REQUEST_CASTING_FAILED';
    const REQUEST_VALIDATION_FAILED = 'REQUEST_VALIDATION_FAILED';

    public function __construct($type, $description, \Exception $previous = null)
    {
        parent::__construct($type, 0, $previous);
        $this->description = $description;
    }

    public function getType()
    {
        return $this->message;
    }

    public function getDescription()
    {
        return $this->description;
    }
}