text:
package org.onosproject.segmentrouting.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.MplsLabel;
import org.onlab.packet.VlanId;
import org.onosproject.TestApplicationId;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.config.Config;
import org.onosproject.net.config.ConfigApplyDelegate;
import org.onosproject.segmentrouting.SegmentRoutingManager;
import org.onosproject.segmentrouting.pwaas.DefaultL2Tunnel;
import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelDescription;
import org.onosproject.segmentrouting.pwaas.DefaultL2TunnelPolicy;
import org.onosproject.segmentrouting.pwaas.L2Mode;

import java.io.InputStream;
import java.util.Set;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

/**
 * Unit tests for class {@link PwaasConfig}.
 */
public class PwaasConfigTest {

    private static final String TUNNEL_ID_1 = "1";
    private static final String TUNNEL_ID_2 = "20";
    private static final String NOT_PRESENT_TUNNEL_ID = "2";
    private static final ConnectPoint INGRESS_1 = ConnectPoint.deviceConnectPoint("of:0000000000000001/1");
    private static final ConnectPoint INGRESS_2 = ConnectPoint.deviceConnectPoint("of:0000000000000002/1");
    private static final ConnectPoint EGRESS_1 = ConnectPoint.deviceConnectPoint("of:0000000000000011/1");
    private static final ConnectPoint EGRESS_2 = ConnectPoint.deviceConnectPoint("of:0000000000000012/1");
    private static final VlanId INGRESS_INNER_TAG_1 = VlanId.vlanId("10");
    private static final VlanId INGRESS_INNER_TAG_2 = VlanId.vlanId("100");
    private static final VlanId INGRESS_OUTER_TAG_1 = VlanId.vlanId("20");
    private static final VlanId INGRESS_OUTER_TAG_2 = VlanId.vlanId("200");
    private static final VlanId EGRESS_INNER_TAG_1 = VlanId.vlanId("11");
    private static final VlanId EGRESS_INNER_TAG_2 = VlanId.vlanId("110");
    private static final VlanId EGRESS_OUTER_TAG_1 = VlanId.vlanId("21");
    private static final VlanId EGRESS_OUTER_TAG_2 = VlanId.vlanId("210");
    private static final String MODE_1 = "RAW";
    private static final String MODE_2 = "TAGGED";
    private static final boolean ALL_VLAN_1 = true;
    private static final boolean ALL_VLAN_2 = false;
    private static final VlanId SD_TAG_1 = VlanId.vlanId("40");
    private static final VlanId SD_TAG_2 = VlanId.NONE;
    private static final MplsLabel PW_LABEL_1 = MplsLabel.mplsLabel("255");
    private static final MplsLabel PW_LABEL_2 = MplsLabel.mplsLabel("4095");

    private PwaasConfig config;
    private PwaasConfig invalidConfig;

    @Before
    public void setUp() throws Exception {
        InputStream jsonStream = PwaasConfig.class
                .getResourceAsStream("/pwaas.json");
        InputStream invalidJsonStream = PwaasConfig.class
                .getResourceAsStream("/pwaas-invalid.json");

        String key = SegmentRoutingManager.APP_NAME;
        ApplicationId subject = new TestApplicationId(key);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(jsonStream);
        JsonNode invalidJsonNode = mapper.readTree(invalidJsonStream);
        ConfigApplyDelegate delegate = new MockDelegate();

        config = new PwaasConfig();
        config.init(subject, key, jsonNode, mapper, delegate);
        invalidConfig = new PwaasConfig();
        invalidConfig.init(subject, key, invalidJsonNode, mapper, delegate);
    }

    /**
     * Tests config validity.
     */
    @Test
    public void testIsValid() {
        assertTrue(config.isValid());
        assertFalse(invalidConfig.isValid());
    }

    /**
     * Tests getPwIds.
     */
    @Test
    public void testGetPwIds() {
        Set<Long> pwIds = config.getPwIds();
        assertThat(pwIds.size(), is(2));
        assertTrue(pwIds.contains(Long.parseLong(TUNNEL_ID_1)));
        assertTrue(pwIds.contains(Long.parseLong(TUNNEL_ID_2)));
        assertFalse(pwIds.contains(Long.parseLong(NOT_PRESENT_TUNNEL_ID)));
    }

    /**
     * Tests getPwDescription.
     */
    @Test
    public void testGetPwDescription() {
        DefaultL2TunnelDescription l2TunnelDescription = null;

        DefaultL2Tunnel l2Tunnel = new DefaultL2Tunnel(
            L2Mode.valueOf(MODE_1),
            SD_TAG_1,
            Long.parseLong(TUNNEL_ID_1),
            PW_LABEL_1
        );
        DefaultL2TunnelPolicy l2TunnelPolicy = new DefaultL2TunnelPolicy(
                Long.parseLong(TUNNEL_ID_1),
                INGRESS_1,
                INGRESS_INNER_TAG_1,
                INGRESS_OUTER_TAG_1,
                EGRESS_1,
                EGRESS_INNER_TAG_1,
                EGRESS_OUTER_TAG_1,
                ALL_VLAN_1
        );
        l2TunnelDescription = config.getPwDescription(Long.parseLong(TUNNEL_ID_1));
        assertThat(l2TunnelDescription.l2Tunnel().pwMode(), is(l2Tunnel.pwMode()));
        assertThat(l2TunnelDescription.l2Tunnel().sdTag(), is(l2Tunnel.sdTag()));
        assertThat(l2TunnelDescription.l2Tunnel().tunnelId(), is(l2Tunnel.tunnelId()));
        assertThat(l2TunnelDescription.l2Tunnel().pwLabel(), is(l2Tunnel.pwLabel()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().tunnelId(), is(l2TunnelPolicy.tunnelId()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1InnerTag(), is(l2TunnelPolicy.cP1InnerTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1OuterTag(), is(l2TunnelPolicy.cP1OuterTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2InnerTag(), is(l2TunnelPolicy.cP2InnerTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2OuterTag(), is(l2TunnelPolicy.cP2OuterTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1(), is(l2TunnelPolicy.cP1()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2(), is(l2TunnelPolicy.cP2()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().isAllVlan(), is(l2TunnelPolicy.isAllVlan()));

        l2Tunnel = new DefaultL2Tunnel(
                L2Mode.valueOf(MODE_2),
                SD_TAG_2,
                Long.parseLong(TUNNEL_ID_2),
                PW_LABEL_2
        );
        l2TunnelPolicy = new DefaultL2TunnelPolicy(
                Long.parseLong(TUNNEL_ID_2),
                INGRESS_2,
                INGRESS_INNER_TAG_2,
                INGRESS_OUTER_TAG_2,
                EGRESS_2,
                EGRESS_INNER_TAG_2,
                EGRESS_OUTER_TAG_2,
                ALL_VLAN_2
        );
        l2TunnelDescription = config.getPwDescription(Long.parseLong(TUNNEL_ID_2));
        assertThat(l2TunnelDescription.l2Tunnel().pwMode(), is(l2Tunnel.pwMode()));
        assertThat(l2TunnelDescription.l2Tunnel().sdTag(), is(l2Tunnel.sdTag()));
        assertThat(l2TunnelDescription.l2Tunnel().tunnelId(), is(l2Tunnel.tunnelId()));
        assertThat(l2TunnelDescription.l2Tunnel().pwLabel(), is(l2Tunnel.pwLabel()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().tunnelId(), is(l2TunnelPolicy.tunnelId()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1InnerTag(), is(l2TunnelPolicy.cP1InnerTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1OuterTag(), is(l2TunnelPolicy.cP1OuterTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2OuterTag(), is(l2TunnelPolicy.cP2OuterTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2OuterTag(), is(l2TunnelPolicy.cP2OuterTag()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP1(), is(l2TunnelPolicy.cP1()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().cP2(), is(l2TunnelPolicy.cP2()));
        assertThat(l2TunnelDescription.l2TunnelPolicy().isAllVlan(), is(l2TunnelPolicy.isAllVlan()));

    }

    private class MockDelegate implements ConfigApplyDelegate {
        @Override
        public void onApply(Config config) {
        }
    }

}


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

<TITLE>
RLSI
</TITLE>

<META NAME="date" CONTENT="2013-03-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

jml.topics

Class RLSI

java.lang.Object
  jml.topics.TopicModel
      jml.topics.RLSI

public class RLSI
extends TopicModel

Field Summary

Fields inherited from class jml.topics.TopicModel

dataMatrix, indicatorMatrix, nTopic, topicMatrix

Constructor Summary

RLSI()

Method Summary

static void
main(java.lang.String[] args)

 void
train()

          Train this topic model to fit the given corpus.

Methods inherited from class jml.topics.TopicModel

getIndicatorMatrix, getTopicMatrix, readCorpus

Methods inherited from class java.lang.Object

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

Constructor Detail

RLSI

public RLSI()

Method Detail

train

public void train()

Description copied from class: TopicModel

Train this topic model to fit the given corpus.

Specified by:
train in class TopicModel

main

public static void main(java.lang.String[] args)

Parameters:
args -

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

redpajama_set_name: RedPajamaGithub


text:
module.exports = function isArray(value) {
  return Object.prototype.toString.apply(value) === '[object Array]';
};


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;

use yii\web\JsExpression;
use kartik\widgets\DatePicker;
use kartik\widgets\Typeahead;
use kartik\widgets\Select2;

//suppress reload of existing asstes in main window
$this->assetBundles['yii\web\YiiAsset'] = new yii\web\AssetBundle;
$this->assetBundles['yii\validators\ValidationAsset'] = new yii\web\AssetBundle;
$this->assetBundles['yii\widgets\ActiveFormAsset'] = new yii\web\AssetBundle;
$this->assetBundles['yii\web\JqueryAsset'] = new yii\web\AssetBundle;
$this->assetBundles['yii\bootstrap\BootstrapAsset'] = new yii\web\AssetBundle;
$this->assetBundles['kartik\widgets\DatePickerAsset'] = new yii\web\AssetBundle;
$this->assetBundles['kartik\widgets\Typeahead1Asset'] = new yii\web\AssetBundle;
$this->assetBundles['kartik\widgets\Typeahead2Asset'] = new yii\web\AssetBundle;
$this->assetBundles['yii\bootstrap\Select2Asset'] = new yii\web\AssetBundle;

/**
 * @var yii\web\View $this
 * @var app\modules\purchase\models\PurchaseOrderLine $model
 * @var yii\widgets\ActiveForm $form
 */

$script = <<<SKRIPT

$('.addprlineupdate').on('click',function(event){
  $('#PurchaseRequestUpdateForm').ajaxSubmit(
  {
    type : "POST",
    success: function(){
      $('#applicationModal').modal('hide');
      window.doOnFilterStart(1,'');
    }
  });
  event.preventDefault();
});

SKRIPT;

$this->registerJs($script);

?>

	<?php $form = ActiveForm::begin([
		'id' => 'PurchaseRequestUpdateForm',
		'action' => Html::Url(['/purchase/purchase-order-line/update','id'=>$model->id]),
    'ajaxVar' => new JsExpression("function ($form) { return false; }")
	]); ?>

      <?php

$dataExp = <<< SCRIPT
  function (term, page) {
    return {
      search: term, // search term
    };
  }
SCRIPT;

$dataResults = <<< SCRIPT
  function (data, page) {
    return {
      results: data.results
    };
  }
SCRIPT;

$url = Html::url(['/parties/contact/jsonlist']);

$usercontactid = $model->purchaseordergroup_id;

$fInitSelection = <<< SCRIPT
  function (element, callback) {
    $.ajax("$url&id=$usercontactid", {
        dataType: "json"
    }).done(function(data) { callback(data.results); });
  }
SCRIPT;

?>

    <?= $form->field($model, 'purchaseordergroup_id')->widget(Select2::classname(),[
          'size' => 'lg',
          'pluginOptions'=>[
            'minimumInputLength' => 3,
            'ajax' => [
              'url' => Html::url(['/parties/contact/jsonlist']),
              'dataType' => 'json',
              'data' => new JsExpression($dataExp),
              'results' => new JsExpression($dataResults),
            ],
            'initSelection' => new JsExpression($fInitSelection)
          ]
    ]); ?>

    <?= Html::activeHiddenInput($model,'purchaseorder_id',['value'=>$purchaseorder_id]); ?>

      <?= Html::activeHiddenInput($model,'article_id'); ?>
      <?= $form->field($model, 'article')->widget(Typeahead::classname(),[
            'options' => ['placeholder' => \Yii::t('app','Product')],
            'dataset' => [
              [
                //'prefetch' => $baseUrl . '/samples/countries.json',
                'remote' => \Yii::$app->controller->createUrl('/purchase/purchase-order-line/jsonlist') . '&search=%QUERY',
                'limit' => 10
              ]
            ]
      ]); ?>

      <?= $form->field($model, 'date_delivery')->widget(DatePicker::classname(), [
        'model' => $model,
        'attribute' => 'date_delivery',
        'value' => date('d-M-Y', strtotime('+7 days')),
        'options' => ['placeholder' => \Yii::t('app','Delivery Date')],
        'pluginOptions' => [
          'format' => 'yyyy-mm-dd',
          'todayHighlight' => true,
          'numberOfMonths' => 2
        ]
      ]);?>

    <?php

$dataExp = <<< SCRIPT
  function (term, page) {
    return {
      search: term, // search term
    };
  }
SCRIPT;

$dataResults = <<< SCRIPT
  function (data, page) {
    return {
      results: data.results
    };
  }
SCRIPT;

$url = Html::url(['/parties/party/jsonlist']);

$fInitSelection = <<< SCRIPT
  function (element, callback) {
    var id=$(element).val();
    if (id!=="") {
      $.ajax("$url&id="+id, {
        dataType: "json"
      }).done(function(data) { callback(data.results); });
    }
  }
SCRIPT;

?>

    <?= $form->field($model, 'party_id')->widget(Select2::classname(),[
          'options' => ['placeholder' => \Yii::t('app','Select supplier ...')],
          'pluginOptions'=>[
            'minimumInputLength' => 3,
            'ajax' => [
              'url' => Html::url(['/parties/party/jsonlist']),
              'dataType' => 'json',
              'data' => new JsExpression($dataExp),
              'results' => new JsExpression($dataResults),
            ],
            'initSelection' => new JsExpression($fInitSelection)
          ]
    ]); ?>

      <?= $form->field($model, 'order_amount',['template'=>' {input}{hint}{error}'])->textInput(['placeholder'=>\Yii::t('app','Quantity')]) ?>

      <?= $form->field($model, 'order_uom',['template'=>' {input}{hint}{error}'])->dropDownList($model->UomPropertiesOptions,['placeholder'=>\Yii::t('app','UoM')]) ?>

    <?= $form->field($model, 'order_price',['template'=>' {input}{hint}{error}'])->textInput(['placeholder'=>\Yii::t('app','Price')]) ?>

    <?= $form->field($model, 'order_currency',[
          'template'=>' {input}{hint}{error}',
          'addon' => [
            'append' => [
              'content' => Html::submitButton(\Yii::t('app','Update'), ['class' => 'btn btn-info addprlineupdate']),
              'asButton' => true
            ]
        ]])->dropDownList($model->CurPropertiesOptions,['placeholder'=>\Yii::t('app','CUR')]) ?>

	<?php ActiveForm::end(); ?>


text:
package mewtocol

import (
	"fmt"
	"log"
	"strings"
)

// 指定した1点の接点状態を読み出す電文を生成して返す
// contactCode:
//    X: 外部入力
//    Y: 外部出力
//    R: 内部リレー
//    L: リンクリレー
//    T: タイマ
//    C: カウンタ
func formatReadIOSingle(dstAddress uint, contactCode string, contactNo uint) string {
	if !isValidCode(contactCode, []string{"X", "Y", "R", "L", "T", "C"}) {
		panic(fmt.Sprintln("invalid code:", contactCode))
	}

	command := "RCS" + contactCode + fmt.Sprintf("%04d", contactNo)
	return format(dstAddress, command)
}

// 指定したワード単位での接点状態を読み出す電文を生成して返す
// contactCode:
//    X: 外部入力
//    Y: 外部出力
//    R: 内部リレー
//    L: リンクリレー
//    T: タイマ
//    C: カウンタ
func formatReadIOWord(dstAddress uint, contactCode string, startWordNo uint, endWordNo uint) string {
	if !isValidCode(contactCode, []string{"X", "Y", "R", "L", "T", "C"}) {
		panic(fmt.Sprintln("invalid code:", contactCode))
	}

	command := "RCC" + contactCode + fmt.Sprintf("%04d", startWordNo) + fmt.Sprintf("%04d", endWordNo)
	return format(dstAddress, command)
}

// 指定した1点の接点出力を書き込む電文を生成して返す。
// stateがtrueの時はON、falseの時はOFFを出力します。
// contactCode:
//    Y: 外部出力
//    R: 内部リレー
//    L: リンクリレー
func formatWriteIOSingle(dstAddress uint, contactCode string, contactNo uint, state bool) string {
	if !isValidCode(contactCode, []string{"Y", "R", "L"}) {
		panic(fmt.Sprintln("invalid code:", contactCode))
	}
	contactData := ""

	if state {
		contactData = "1"
	} else {
		contactData = "0"
	}

	command := "WCS" + contactCode + fmt.Sprintf("%04d", contactNo) + contactData
	return format(dstAddress, command)
}

// 指定したワード単位での接点状態を読み出す電文を生成して返す
// dataCode:
//    D: データレジスタ
//    L: リンクレジスタ
//    F: ファイルレジスタ
func formatReadDataArea(dstAddress uint, dataCode string, startWordNo uint, endWordNo uint) string {
	if !isValidCode(dataCode, []string{"D", "L", "F"}) {
		panic(fmt.Sprintln("invalid code:", dataCode))
	}

	command := "RD" + dataCode + fmt.Sprintf("%05d", startWordNo) + fmt.Sprintf("%05d", endWordNo)
	return format(dstAddress, command)
}

// データエリアへ、配列の引数として渡された値を書き込む
// dataCode:
//    D: データレジスタ
//    L: リンクレジスタ
//    F: ファイルレジスタ
func formatWriteDataArea(dstAddress uint, dataCode string, startWordNo uint, values []uint32) string {
	if !isValidCode(dataCode, []string{"D", "L", "F"}) {
		panic(fmt.Sprintln("invalid code:", dataCode))
	}

	valuesBin := make([]byte, 0, len(values))
	index := 0
	for i, val := range values {
		hex := []byte(fmt.Sprintf("%04x", val))
		upper := hex[:2]
		lower := hex[2:]
		valBin := append(lower, upper...)
		valuesBin = append(valuesBin, valBin...)
		index = i
	}

	endWordNo := startWordNo + uint(index)
	command := "WD" + dataCode + fmt.Sprintf("%05d", startWordNo) + fmt.Sprintf("%05d", endWordNo)
	command += strings.ToUpper(string(valuesBin))
	return format(dstAddress, command)
}

// 渡されたコマンド本体にヘッダとBCCを追加する。
// ここでは末尾のCRは付加しません。送信時に付加してください
func format(dstAddress uint, body string) string {
	command := header() + address(dstAddress) + command() + body
	sendData := command + getBcc(command)
	return sendData
}

func header() string {
	return "%"
}

// dstAddress 1 - 32, FF(255) is Global send.
func address(ad uint) string {
	if (ad < 1 || 32 < ad) && ad != 255 {
		panic(fmt.Sprintf("Invalid mewtocol address: %d", ad))
	}

	return fmt.Sprintf("%02d", ad)
}

// 指定可能なコードかどうかチェックし、OKならtrueを返す。
func isValidCode(code string, list []string) bool {
	for _, s := range list {
		if code == s {
			return true
		}
	}

	log.Fatal(fmt.Sprintf("invalid code:", code))
	return false
}

func command() string {
	return "#"
}


text:
/*
Title: Gateway Center
Description: L.N. Consulting is a mechanical, electrical, and energy services engineering design firm, with geothermal and renewable energy systems integration experience
*/

# Laboratory

Gateway Center

   L.N. Consulting completed the design for the Mascoma laboratory building located in Lebanon, N.H.  The project encompasses 33,000 sq. ft. and is 3 levels of a 5 story building.  The laboratory needed to support microbiology and an R&D fermentation production suite.  The project has been designed with high efficiency systems using sustainable materials.  The waste destruct system was also designed around an energy efficient technique which utilizes chemical destruction in lieu of thermal destruction to reduce energy usage and operating costs.  The ventilation system is based around a high efficiency heat recovery ventilator with demand control ventilation for non-lab spaces.  The estimated cost of mechanical and electrical construction is $3,000,000.00.

Hanover, NH

Investors Corporation of Vermont, Paul Sprayregen (802) 863-2311

Greg Rabideau, Architect (802) 863-0222

ICV Construction

$ 5.0 million

Completed 2009


text:
<?php
/*
Plugin Name: Autoptimize
Plugin URI: http://blog.futtta.be/autoptimize
Description: Optimizes your website, concatenating the CSS and JavaScript code, and compressing it.
Version: 2.1.0
Author: Frank Goossens (futtta)
Author URI: http://blog.futtta.be/
Domain Path: localization/
Text Domain: autoptimize
Released under the GNU General Public License (GPL)
http://www.gnu.org/licenses/gpl.txt
*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

define('AUTOPTIMIZE_PLUGIN_DIR',plugin_dir_path(__FILE__));

// Load config class
include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeConfig.php');

// Load toolbar class
include( AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeToolbar.php' );

// Load partners tab if admin
if (is_admin()) {
    include AUTOPTIMIZE_PLUGIN_DIR.'classlesses/autoptimizePartners.php';
}

// Do we gzip when caching (needed early to load autoptimizeCache.php)
define('AUTOPTIMIZE_CACHE_NOGZIP',(bool) get_option('autoptimize_cache_nogzip'));

// Load cache class
include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeCache.php');

// wp-content dir name (automagically set, should not be needed), dirname of AO cache dir and AO-prefix can be overridden in wp-config.php
if (!defined('AUTOPTIMIZE_WP_CONTENT_NAME')) { define('AUTOPTIMIZE_WP_CONTENT_NAME','/'.wp_basename( WP_CONTENT_DIR )); }
if (!defined('AUTOPTIMIZE_CACHE_CHILD_DIR')) { define('AUTOPTIMIZE_CACHE_CHILD_DIR','/cache/autoptimize/'); }
if (!defined('AUTOPTIMIZE_CACHEFILE_PREFIX')) { define('AUTOPTIMIZE_CACHEFILE_PREFIX', 'autoptimize_'); }

// Plugin dir constants (plugin url's defined later to accomodate domain mapped sites)
if (is_multisite() && apply_filters( 'autoptimize_separate_blog_caches' , true )) {
    $blog_id = get_current_blog_id();
    define('AUTOPTIMIZE_CACHE_DIR', WP_CONTENT_DIR.AUTOPTIMIZE_CACHE_CHILD_DIR.$blog_id.'/' );
} else {
    define('AUTOPTIMIZE_CACHE_DIR', WP_CONTENT_DIR.AUTOPTIMIZE_CACHE_CHILD_DIR);
}
define('AUTOPTIMIZE_CACHE_DELAY',true);
define('WP_ROOT_DIR',str_replace(AUTOPTIMIZE_WP_CONTENT_NAME,'',WP_CONTENT_DIR));

// Initialize the cache at least once
$conf = autoptimizeConfig::instance();

/* Check if we're updating, in which case we might need to do stuff and flush the cache
to avoid old versions of aggregated files lingering around */

$autoptimize_version="2.1.0";
$autoptimize_db_version=get_option('autoptimize_version','none');

if ($autoptimize_db_version !== $autoptimize_version) {
    if ($autoptimize_db_version==="none") {
        add_action('admin_notices', 'autoptimize_install_config_notice');
    } else {
        // updating, include the update-code
        include(AUTOPTIMIZE_PLUGIN_DIR.'classlesses/autoptimizeUpdateCode.php');
    }

    update_option('autoptimize_version',$autoptimize_version);
    $autoptimize_db_version=$autoptimize_version;
}

// Load translations
function autoptimize_load_plugin_textdomain() {
    load_plugin_textdomain('autoptimize',false,plugin_basename(dirname( __FILE__ )).'/localization');
}
add_action( 'init', 'autoptimize_load_plugin_textdomain' );

function autoptimize_uninstall(){
    autoptimizeCache::clearall();

    $delete_options=array("autoptimize_cache_clean", "autoptimize_cache_nogzip", "autoptimize_css", "autoptimize_css_datauris", "autoptimize_css_justhead", "autoptimize_css_defer", "autoptimize_css_defer_inline", "autoptimize_css_inline", "autoptimize_css_exclude", "autoptimize_html", "autoptimize_html_keepcomments", "autoptimize_js", "autoptimize_js_exclude", "autoptimize_js_forcehead", "autoptimize_js_justhead", "autoptimize_js_trycatch", "autoptimize_version", "autoptimize_show_adv", "autoptimize_cdn_url", "autoptimize_cachesize_notice","autoptimize_css_include_inline","autoptimize_js_include_inline","autoptimize_css_nogooglefont");

    if ( !is_multisite() ) {
        foreach ($delete_options as $del_opt) {    delete_option( $del_opt ); }
    } else {
        global $wpdb;
        $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
        $original_blog_id = get_current_blog_id();
        foreach ( $blog_ids as $blog_id ) {
            switch_to_blog( $blog_id );
            foreach ($delete_options as $del_opt) {    delete_option( $del_opt ); }
        }
        switch_to_blog( $original_blog_id );
    }

    if ( wp_get_schedule( 'ao_cachechecker' ) ) {
        wp_clear_scheduled_hook( 'ao_cachechecker' );
    }
}

function autoptimize_install_config_notice() {
    echo '

';
    _e('Thank you for installing and activating Autoptimize. Please configure it under "Settings" -> "Autoptimize" to start improving your site\'s performance.', 'autoptimize' );
    echo '

';
}

function autoptimize_update_config_notice() {
    echo '

';
    _e('Autoptimize has just been updated. Please test your site now and adapt Autoptimize config if needed.', 'autoptimize' );
    echo '

';
}

function autoptimize_cache_unavailable_notice() {
    echo '

';
    _e('Autoptimize cannot write to the cache directory (default: /wp-content/cache/autoptimize), please fix to enable CSS/ JS optimization!', 'autoptimize' );
    echo '

';
}

// Set up the buffering
function autoptimize_start_buffering() {
    $ao_noptimize = false;

    // noptimize in qs to get non-optimized page for debugging
    if (array_key_exists("ao_noptimize",$_GET)) {
        if ( ($_GET["ao_noptimize"]==="1") && (apply_filters('autoptimize_filter_honor_qs_noptimize',true)) ) {
            $ao_noptimize = true;
        }
    }

    // check for DONOTMINIFY constant as used by e.g. WooCommerce POS
    if (defined('DONOTMINIFY') && (constant('DONOTMINIFY')===true || constant('DONOTMINIFY')==="true")) {
        $ao_noptimize = true;
    }

    // filter you can use to block autoptimization on your own terms
    $ao_noptimize = (bool) apply_filters( 'autoptimize_filter_noptimize', $ao_noptimize );

    if (!is_feed() && !$ao_noptimize && !is_admin() && ( !function_exists('is_customize_preview') || !is_customize_preview() ) ) {
        // Config element
        $conf = autoptimizeConfig::instance();

        // Load our base class
        include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeBase.php');

        // Load extra classes and set some vars
        if($conf->get('autoptimize_html')) {
            include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeHTML.php');
            // BUG: new minify-html does not support keeping HTML comments, skipping for now
            // if (defined('AUTOPTIMIZE_LEGACY_MINIFIERS')) {
                @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/minify-html.php');
            // } else {
            //    @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/minify-2.1.7-html.php');
            // }
        }

        if($conf->get('autoptimize_js')) {
            include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeScripts.php');
            if (!class_exists('JSMin')) {
                if (defined('AUTOPTIMIZE_LEGACY_MINIFIERS')) {
                    @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/jsmin-1.1.1.php');
                } else {
                    @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/minify-2.3.1-jsmin.php');
                }
            }
            if ( ! defined( 'CONCATENATE_SCRIPTS' )) {
                define('CONCATENATE_SCRIPTS',false);
            }
            if ( ! defined( 'COMPRESS_SCRIPTS' )) {
                define('COMPRESS_SCRIPTS',false);
            }
        }

        if($conf->get('autoptimize_css')) {
            include(AUTOPTIMIZE_PLUGIN_DIR.'classes/autoptimizeStyles.php');
            if (defined('AUTOPTIMIZE_LEGACY_MINIFIERS')) {
                if (!class_exists('Minify_CSS_Compressor')) {
                    @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/minify-css-compressor.php');
                }
            } else {
                if (!class_exists('CSSmin')) {
                    @include(AUTOPTIMIZE_PLUGIN_DIR.'classes/external/php/yui-php-cssmin-2.4.8-4_fgo.php');
                }
            }
            if ( ! defined( 'COMPRESS_CSS' )) {
                define('COMPRESS_CSS',false);
            }
        }

        // filter to be used with care, kills all output buffers when true. use with extreme caution. you have been warned!
        if (apply_filters('autoptimize_filter_obkiller',false)) {
            while (ob_get_level() > 0) {
                ob_end_clean();
            }
        }

        // Now, start the real thing!
        ob_start('autoptimize_end_buffering');
    }
}

// Action on end, this is where the magic happens
function autoptimize_end_buffering($content) {
    if ( ((stripos($content,"<html") === false) && (stripos($content,"<!DOCTYPE html") === false)) || preg_match('/]*(?:amp|⚡)/',$content) === 1 || stripos($content,"<xsl:stylesheet") !== false ) { return $content; }

    // load URL constants as late as possible to allow domain mapper to kick in
    if (function_exists("domain_mapping_siteurl")) {
        define('AUTOPTIMIZE_WP_SITE_URL',domain_mapping_siteurl(get_current_blog_id()));
        define('AUTOPTIMIZE_WP_CONTENT_URL',str_replace(get_original_url(AUTOPTIMIZE_WP_SITE_URL),AUTOPTIMIZE_WP_SITE_URL,content_url()));
    } else {
        define('AUTOPTIMIZE_WP_SITE_URL',site_url());
        define('AUTOPTIMIZE_WP_CONTENT_URL',content_url());
    }

    if ( is_multisite() && apply_filters( 'autoptimize_separate_blog_caches' , true ) ) {
        $blog_id = get_current_blog_id();
        define('AUTOPTIMIZE_CACHE_URL',AUTOPTIMIZE_WP_CONTENT_URL.AUTOPTIMIZE_CACHE_CHILD_DIR.$blog_id.'/' );
    } else {
        define('AUTOPTIMIZE_CACHE_URL',AUTOPTIMIZE_WP_CONTENT_URL.AUTOPTIMIZE_CACHE_CHILD_DIR);
    }
    define('AUTOPTIMIZE_WP_ROOT_URL',str_replace(AUTOPTIMIZE_WP_CONTENT_NAME,'',AUTOPTIMIZE_WP_CONTENT_URL));

    // Config element
    $conf = autoptimizeConfig::instance();

    // Choose the classes
    $classes = array();
    if($conf->get('autoptimize_js'))
        $classes[] = 'autoptimizeScripts';
    if($conf->get('autoptimize_css'))
        $classes[] = 'autoptimizeStyles';
    if($conf->get('autoptimize_html'))
        $classes[] = 'autoptimizeHTML';

    // Set some options
    $classoptions = array(
        'autoptimizeScripts' => array(
            'justhead' => $conf->get('autoptimize_js_justhead'),
            'forcehead' => $conf->get('autoptimize_js_forcehead'),
            'trycatch' => $conf->get('autoptimize_js_trycatch'),
            'js_exclude' => $conf->get('autoptimize_js_exclude'),
            'cdn_url' => $conf->get('autoptimize_cdn_url'),
            'include_inline' => $conf->get('autoptimize_js_include_inline')
        ),
        'autoptimizeStyles' => array(
            'justhead' => $conf->get('autoptimize_css_justhead'),
            'datauris' => $conf->get('autoptimize_css_datauris'),
            'defer' => $conf->get('autoptimize_css_defer'),
            'defer_inline' => $conf->get('autoptimize_css_defer_inline'),
            'inline' => $conf->get('autoptimize_css_inline'),
            'css_exclude' => $conf->get('autoptimize_css_exclude'),
            'cdn_url' => $conf->get('autoptimize_cdn_url'),
            'include_inline' => $conf->get('autoptimize_css_include_inline'),
            'nogooglefont' => $conf->get('autoptimize_css_nogooglefont')
        ),
        'autoptimizeHTML' => array(
            'keepcomments' => $conf->get('autoptimize_html_keepcomments')
        )
    );

    $content = apply_filters( 'autoptimize_filter_html_before_minify', $content );

    // Run the classes
    foreach($classes as $name) {
        $instance = new $name($content);
        if($instance->read($classoptions[$name])) {
            $instance->minify();
            $instance->cache();
            $content = $instance->getcontent();
        }
        unset($instance);
    }

    $content = apply_filters( 'autoptimize_html_after_minify', $content );
    return $content;
}

if ( autoptimizeCache::cacheavail() ) {
    $conf = autoptimizeConfig::instance();
    if( $conf->get('autoptimize_html') || $conf->get('autoptimize_js') || $conf->get('autoptimize_css') ) {
        // Hook to wordpress
        if (defined('AUTOPTIMIZE_INIT_EARLIER')) {
            add_action('init','autoptimize_start_buffering',-1);
        } else {
            add_action('template_redirect','autoptimize_start_buffering',2);
        }
    }
} else {
    add_action('admin_notices', 'autoptimize_cache_unavailable_notice');
}

register_uninstall_hook(__FILE__, "autoptimize_uninstall");
include_once('classlesses/autoptimizeCacheChecker.php');

// Do not pollute other plugins
unset($conf);


text:
<?php

namespace Elastica\Test\Aggregation;

use Elastica\Aggregation\ValueCount;
use Elastica\Document;
use Elastica\Query;

class ValueCountTest extends BaseAggregationTest
{
    protected function setUp()
    {
        parent::setUp();
        $this->_index = $this->_createIndex();
        $docs = array(
            new Document('1', array('price' => 5)),
            new Document('2', array('price' => 8)),
            new Document('3', array('price' => 1)),
            new Document('4', array('price' => 3)),
            new Document('5', array('price' => 3)),
        );
        $this->_index->getType('test')->addDocuments($docs);
        $this->_index->refresh();
    }

    public function testValueCountAggregation()
    {
        $agg = new ValueCount("count", "price");

        $query = new Query();
        $query->addAggregation($agg);
        $results = $this->_index->search($query)->getAggregation("count");

        $this->assertEquals(5, $results['value']);
    }
}


text:
package io.hops.metadata.yarn.entity.fair;

public class AppSchedulable {

  private final String schedulerAppId;
  private final long starttime;
  private final String queuename;

  public AppSchedulable(String schedulerAppId, long starttime,
          String queuename) {
    this.schedulerAppId = schedulerAppId;
    this.starttime = starttime;
    this.queuename = queuename;
  }

  public String getSchedulerAppId() {
    return schedulerAppId;
  }

  public long getStarttime() {
    return starttime;
  }

  public String getQueuename() {
    return queuename;
  }
}


text:
Kranion is an open source, interactive transcranial focused ultrasound visualization system. Kranion can import DICOM MR and CT studies and perform several visualization and procedure preplanning functions. GPU support provides interactive performance on supported graphics hardware.

Features:

- Geometric modeling and visualization of treatment plan
- Patient selection (Skull density ratio calculation)
- Skull metrics
- Phase aberration estimation
- Transducer efficiency estimatation

System requirements:

- Windows 8, Windows 10, or Linux
- Java 1.8 or later, 64 bit version installed
- Latest NVidia driver installed (version 388.59 or later)
- NVidia GPU with 2 GB or more of dedicated memory, with support for OpenGL 4.5

You can watch a tutorial here: https://www.youtube.com/watch?v=tbfp_qUErT4


text:
The phrasebook is a series of simple JSON-formatted files that represent possible responses to different commands. Using this system, instead of having a single hard-coded set of responses, it has a series of possible phrasings for anything it says, and it chooses between them randomly.

Entries are divided into **contexts**, **modules**, and **phrases**.

## Contexts
A context is a group of phrases which have similar meanings. Instead of saying a single phrase, Cabbage will look up all phrases with a certain context and module and choose randomly among them.

## Modules
Modules mean the same thing here as they mean in the rest of the bot. However, it is very important to note that contexts are normally module-specific; that is, even if two modules have contexts with the same name, they are treated as two separate contexts unless specifically requested to pull from both.

## Phrases
A phrase is a mix of text and escape-sequences.

## Phrasefile Format
### File naming
Phrasefiles should be placed in phrasebook/phrases. They are to be named according to the format `X.phrases`, where X is a descriptive name for the set of phrases. Usually, this will just be the module name, but it is possible to define phrasefiles that provide phrases for multiple modules.

### JSON format
```
[
	{
		"module" : "MODULE NAME GOES HERE",
		"phrases" : {
			"CONTEXT NAME GOES HERE" : [
				"PHRASE GOES HERE",
				"OTHER PHRASE GOES HERE",
				...
			],
			"OTHER CONTEXT NAME GOES HERE" : [
				"OTHER PHRASE GOES HERE",
				...
			],
			...
		}
	},
	{
		"module" : "OTHER MODULE NAME GOES HERE",
		...
	},
	...
]
```

### Escape Sequences
All escape sequences begin with % (to insert a literal % character, use %%)
The following escape sequences are recognized by the Phrasebook, and will be translated as follows:
* %% -- A literal % character
* %u -- The username for that issued the command to which Cabbage is responding
* %U -- As %u, but tag the user instead of just printing the name
* %m -- CabbageBot's username
* %E -- Mention @everyone
* %t -- The current time
* %T -- The current time and date
* %i -- The command string ('!cabbage ' by default, but customizable in cabbagerc)
* %1-%0 -- Custom substitutions (see documentation for Phrasebook.get())


text:
package liquibase.ext;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import liquibase.Liquibase;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.resource.ClassLoaderResourceAccessor;

public class BaseTestCase {

    private static String url;
    private static Driver driver;
    private static Properties info;
    protected static Connection connection;
    protected static JdbcConnection jdbcConnection;
    protected static Liquibase liquiBase;
    protected static String changeLogFile;

    public static void connectToDB() throws Exception {
        if (connection == null) {
            info = new Properties();
            info.load(new FileInputStream("src/test/resources/liquibase.properties"));

            url = info.getProperty("url");
            driver = (Driver) Class.forName(DatabaseFactory.getInstance().findDefaultDriver(url), true,
                    Thread.currentThread().getContextClassLoader()).newInstance();

            connection = driver.connect(url, info);

            if (connection == null) {
                throw new DatabaseException("Connection could not be created to " + url + " with driver "
                        + driver.getClass().getName() + ".  Possibly the wrong driver for the given database URL");
            }

            jdbcConnection = new JdbcConnection(connection);
        }
    }

    public static void cleanDB() throws Exception {
        liquiBase = new Liquibase(changeLogFile, new ClassLoaderResourceAccessor(), jdbcConnection);
        liquiBase.dropAll();
    }
}


text:
CREATE OR REPLACE PROCEDURE findAuthor(X IN CHAR) AS
n CHAR(30);
BEGIN
SELECT R.name INTO n
FROM Publications P, Writes W, Authors A, Persons R
WHERE P.Title = X AND P.pid = W.pid AND W.perid = A.perid AND A.perid = R.perid;
DBMS_OUTPUT.PUT_LINE('The Author of the Book of this book is '||n);
END;

EXEC findAuthor('Posuere libero.');

--3.Print out the names of each user who have viewed a Book of type Y. where Y is a input parameter.
--FIXED and
CREATE OR REPLACE PROCEDURE findUsers(Y IN CHAR) AS
s CHAR(30);
cursor find is SELECT DISTINCT S.name
FROM Publications P, PaysFor F, Customer C, Persons S
WHERE P.type = Y AND P.pid = F.pid AND F.perid = C.perid AND C.perid = S.perid;
BEGIN
open find;
loop fetch find INTO s;
if(find%NOTFOUND) then exit;
end if;
DBMS_OUTPUT.PUT_LINE('The names of users who viewed a Book of type are '||s);
end loop;
close find;
END;

Test;
	The names of users who viewed a Book of type are Aman

 CREATE OR REPLACE PROCEDURE findUsers(Y IN CHAR) AS
s CHAR(30);
cursor find is SELECT DISTINCT S.name
FROM Publications P, PaysFor F, Customer C, Persons S
WHERE P.type = Y AND P.pid = F.pid AND F.perid = C.perid AND C.perid = S.perid;
BEGIN
open find;
loop fetch find INTO s;
if(find%NOTFOUND) then exit;
end if;
DBMS_OUTPUT.PUT_LINE('The names of users who viewed a Book of type are '||s);
end loop;
close find;
END;

Test;
4. CREATE OR REPLACE PROCEDURE rating(X IN CHAR) AS
n integer;
BEGIN
SELECT R.rating INTO n
FROM Publications P, Rates R
WHERE P.Title = X AND P.pid = R.pid;
DBMS_OUTPUT.PUT_LINE('The rating of the Book is '||n);
END;

EXEC rating('Duis dictum.');

Test:
	The rating of the Book is 5

--5.What is the Average cost that each Author charges for there books. Please print
--out the Authors Name as well as the Average cost of thier books for each of them.

SELECT DISTINCT S.name, AVG(P.price)
FROM Persons S, Authors A, Writes W, Publications P
WHERE S.perid = A.perid AND  A.perid = W.perid AND W.pid = P.pid
GROUP BY S.name;

--6.Whats the name of each book that the user X payed to view. Where X is a input parameter.

CREATE OR REPLACE PROCEDURE bookName(X IN CHAR) AS
n CHAR(30);
cursor books is SELECT DISTINCT P.Title
FROM Persons S, Customer C, paysFor F, Publications P
WHERE S.name = X AND S.perid = C.perid AND C.perid = F.perid AND F.pid = P.pid;
BEGIN
open books;
loop
fetch books INTO n;
if(books%NOTFOUND) then exit;
end if;
DBMS_OUTPUT.PUT_LINE('The user saw were named '||n);
end loop;
close books;
END;

Test;  the Books the user saw were named Penatibus tempor!

7. For each Author find the Average rating give for each of their books. Print the Authors Name and the Average rating
SELECT DISTINCT S.name, AVG(R.rating)
FROM Persons S, Authors A, Writes W, Publications P, Rates R
WHERE S.perid = A.perid AND A.perid = W.perid AND W.pid = P.pid AND P.pid = R.pid
GROUP BY S.name;

Test;
	Name			AVG(R.RATING)
-------------------------------------------------
	Yulduz              	5

8. For Book X find each date for which the book was viewed. where X is a input parameter
CREATE OR REPLACE PROCEDURE datesviewed(X IN CHAR) AS
d CHAR(30);
cursor viewed is SELECT DISTINCT L.dateViewed
FROM Publications P, RetrieveLog L
WHERE P.Title = X AND P.pid = L.pid;
BEGIN
open viewed;
loop fetch viewed into d;
if(viewed%NOTFOUND) then exit;
end if;
DBMS_OUTPUT.PUT_LINE('The dates the Book was viewed are: ' ||d);
end loop;
close viewed;
END;

Test;
	The dates the Book was viewed are: 27-OCT-16

9. For Book X find the Names of each user who has viewed it. Print out the name of the user as well as the Name of the Book. Where X is an input
parameter.
CREATE OR REPLACE PROCEDURE usersView(X in CHAR) AS
v CHAR(30);
cursor us is SELECT DISTINCT S.name INTO v
FROM Customer C, Publications P, RetrieveLog L, Persons S, paysFor F
WHERE P.Title = X AND P.pid = L.pid AND L.perid = S.perid AND S.perid = C.perid AND C.perid = S.perid
GROUP BY S.name;
BEGIN
open us;
loop fetch us into v;
if(us%NOTFOUND) then exit;
end if;
DBMS_OUTPUT.PUT_LINE('Names of user who have viewed the Book are: '||v);
end loop;
close us;
END;

Test;
	Names of user who have viewed the Book are: Erik

2 things in Progress:

10. Difficult Query
For Each User, Count the number of Book's they have viewed, and separately. Also count the Number of books each each Author has published.
A User and Author must be listed even if the Count is zero for either of them.


text:
package marathon

import (
	"io"
	"io/ioutil"
	"os"
	"reflect"
	"text/template"

	"github.com/ContainX/depcon/pkg/encoding"
	"github.com/spf13/viper"
	"path/filepath"
	"strings"
)

const (
	DefaultEnv = "-"
)

// Templated based Functions
var Funcs = template.FuncMap{
	"default": func(args ...interface{}) interface{} {
		arg := args[0]
		if len(args) < 2 {
			return arg
		}
		value := args[1]

		defer recovery()

		v := reflect.ValueOf(value)
		switch v.Kind() {
		case reflect.String, reflect.Slice, reflect.Array, reflect.Map:
			if v.Len() == 0 {
				return arg
			}
		case reflect.Bool:
			if !v.Bool() {
				return arg
			}
		default:
			return value
		}

		return value
	},
	"isEnv": func(value string) bool {
		if len(value) > 0 {
			current := strings.ToLower(viper.GetString(ENV_NAME))
			return current == strings.ToLower(value)
		}
		return false
	},
}

type TemplateContext struct {
	Environments map[string]*TemplateEnvironment `json:"environments,omitempty"`
}

type TemplateEnvironment struct {
	Apps map[string]map[string]interface{} `json:"apps,omitempty"`
}

func (ctx *TemplateContext) Transform(writer io.Writer, descriptor string) error {
	var t *template.Template

	if b, err := ioutil.ReadFile(descriptor); err != nil {
		return err
	} else {
		var e error
		t = template.New(descriptor).Funcs(Funcs)
		t, e = t.Parse(string(b))
		if e != nil {
			return e
		}
		if matches, err := filepath.Glob("./**/*.tmpl"); err == nil && len(matches) > 0 {
			if t, e = t.ParseFiles(matches...); err != nil {
				return err
			}
		}
	}
	environment := viper.GetString(ENV_NAME)
	m := ctx.mergeAppWithDefault(strings.ToLower(environment))

	if err := t.Execute(writer, m); err != nil {
		return err
	}
	return nil
}

// Validates the specified app is declared within the current envirnoment. If it is any values missing from
// specific environment are propagated from the default environment
func (ctx *TemplateContext) mergeAppWithDefault(env string) map[string]map[string]interface{} {
	if _, exists := ctx.Environments[DefaultEnv]; !exists {
		if _, cok := ctx.Environments[env]; !cok {
			return make(map[string]map[string]interface{})
		}
		return ctx.Environments[env].Apps
	}

	defm := ctx.Environments[DefaultEnv].Apps

	if ctx.Environments[env] == nil {
		return defm
	}

	envm := ctx.Environments[env].Apps

	merged := make(map[string]map[string]interface{})

	for app, props := range envm {
		merged[app] = props
	}

	for app, props := range defm {
		if _, exists := merged[app]; !exists {
			merged[app] = props
		} else {
			for k, v := range props {
				if _, ok := merged[app][k]; !ok {
					merged[app][k] = v
				}
			}

		}
	}
	return merged
}

func recovery() {
	recover()
}

func TemplateExists(filename string) bool {

	if len(filename) > 0 {
		if _, err := os.Stat(filename); err == nil {
			return true
		}
	}
	return false
}

func LoadTemplateContext(filename string) (*TemplateContext, error) {
	ctx, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	encoder, err := encoding.NewEncoder(encoding.JSON)
	if err != nil {
		return nil, err
	}

	result := &TemplateContext{Environments: make(map[string]*TemplateEnvironment)}

	if err := encoder.UnMarshal(ctx, result); err != nil {
		return nil, err
	}
	return result, nil
}


text:
package net.sf.jabref.gui.mergeentries;

import java.awt.Font;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

import net.sf.jabref.Globals;
import net.sf.jabref.gui.PreviewPanel;
import net.sf.jabref.gui.util.component.DiffHighlightingTextPane;
import net.sf.jabref.logic.bibtex.BibEntryWriter;
import net.sf.jabref.logic.bibtex.LatexFieldFormatter;
import net.sf.jabref.logic.bibtex.LatexFieldFormatterPreferences;
import net.sf.jabref.logic.formatter.casechanger.SentenceCaseFormatter;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.strings.DiffHighlighting;
import net.sf.jabref.model.database.BibDatabaseMode;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.InternalBibtexFields;
import net.sf.jabref.preferences.JabRefPreferences;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Oscar Gustafsson
 *
 *         Class for dealing with merging entries
 */

public class MergeEntries {

    private static final Log LOGGER = LogFactory.getLog(MergeEntries.class);

    // Headings
    private final List<String> columnHeadings = Arrays.asList(Localization.lang("Field"),
            Localization.lang("Left entry"),
            Localization.lang("Left"),
            Localization.lang("None"),
            Localization.lang("Right"),
            Localization.lang("Right entry"));
    private static final String[] DIFF_MODES = {Localization.lang("Plain text"),
            Localization.lang("Show diff") + " - " + Localization.lang("word"),
            Localization.lang("Show diff") + " - " + Localization.lang("character"),
            Localization.lang("Show symmetric diff") + " - " + Localization.lang("word"),
            Localization.lang("Show symmetric diff") + " - " + Localization.lang("character")};

    private final Set<String> identicalFields = new HashSet<>();
    private final Set<String> differentFields = new HashSet<>();
    private final BibEntry mergedEntry = new BibEntry();
    private final BibEntry leftEntry;
    private final BibEntry rightEntry;
    private final BibDatabaseMode databaseType;
    private JScrollPane scrollPane;
    private JTextArea sourceView;
    private PreviewPanel entryPreview;
    private Boolean doneBuilding;
    private Boolean identicalTypes;
    private List<JRadioButton> typeRadioButtons;
    private final Set<String> allFields = new TreeSet<>();
    private final JComboBox<String> diffMode = new JComboBox<>();
    private final Map<String, JTextPane> leftTextPanes = new HashMap<>();
    private final Map<String, JTextPane> rightTextPanes = new HashMap<>();
    private final Map<String, List<JRadioButton>> radioButtons = new HashMap<>();

    private final JPanel mainPanel = new JPanel();

    private static final String MARGIN = "10px";

    private static final List<JLabel> HEADING_LABELS = new ArrayList<>(6);

    private static final CellConstraints CELL_CONSTRAINTS = new CellConstraints();

    /**
     * Constructor taking two entries
     *
     * @param entryLeft Left entry
     * @param entryRight Right entry
     * @param type Bib database mode
     */
    public MergeEntries(BibEntry entryLeft, BibEntry entryRight, BibDatabaseMode type) {
        leftEntry = entryLeft;
        rightEntry = entryRight;
        this.databaseType = type;
        initialize();
    }

    /**
     * Constructor with optional column captions for the two entries
     *
     * @param entryLeft Left entry
     * @param entryRight Right entry
     * @param headingLeft Heading for left entry
     * @param headingRight Heading for right entry
     * @param type Bib database mode
     */
    public MergeEntries(BibEntry entryLeft, BibEntry entryRight, String headingLeft, String headingRight, BibDatabaseMode type) {
        columnHeadings.set(1, headingLeft);
        columnHeadings.set(5, headingRight);
        this.leftEntry = entryLeft;
        this.rightEntry = entryRight;

        this.databaseType = type;

        initialize();
    }

    /**
     * Main function for building the merge entry JPanel
     */
    private void initialize() {
        doneBuilding = false;
        setupFields();

        fillDiffModes();

        // Create main layout
        String colSpecMain = "left:pref, 5px, center:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, center:3cm:grow";
        String colSpecMerge = "left:pref, 5px, fill:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, fill:3cm:grow";
        String rowSpec = "pref, pref, 10px, fill:5cm:grow, 10px, pref, 10px, fill:3cm:grow";
        StringBuilder rowBuilder = new StringBuilder("");
        for (int i = 0; i < allFields.size(); i++) {
            rowBuilder.append("pref, 2dlu, ");
        }
        rowBuilder.append("pref");

        JPanel mergePanel = new JPanel();
        FormLayout mainLayout = new FormLayout(colSpecMain, rowSpec);
        FormLayout mergeLayout = new FormLayout(colSpecMerge, rowBuilder.toString());
        mainPanel.setLayout(mainLayout);
        mergePanel.setLayout(mergeLayout);

        setupHeadingRows();

        mainPanel.add(new JSeparator(), CELL_CONSTRAINTS.xyw(1, 3, 11));

        setupEntryTypeRow(mergePanel);

        int maxLabelWidth = setupFieldRows(mergePanel);

        // Create and add scrollpane
        scrollPane = new JScrollPane(mergePanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        updateTextPanes(allFields);
        mainPanel.add(scrollPane, CELL_CONSTRAINTS.xyw(1, 4, 11));
        mainPanel.add(new JSeparator(), CELL_CONSTRAINTS.xyw(1, 5, 11));

        synchronizeColumnWidths(mainLayout, mergeLayout, maxLabelWidth);

        // Setup a PreviewPanel and a Bibtex source box for the merged entry
        mainPanel.add(boldFontLabel(Localization.lang("Merged entry")), CELL_CONSTRAINTS.xyw(1, 6, 6));

        entryPreview = new PreviewPanel(null, mergedEntry, null, Globals.prefs.get(JabRefPreferences.PREVIEW_0));
        mainPanel.add(entryPreview, CELL_CONSTRAINTS.xyw(1, 8, 6));

        mainPanel.add(boldFontLabel(Localization.lang("Merged BibTeX source code")), CELL_CONSTRAINTS.xyw(8, 6, 4));

        sourceView = new JTextArea();
        sourceView.setLineWrap(true);
        sourceView.setFont(new Font("Monospaced", Font.PLAIN, Globals.prefs.getInt(JabRefPreferences.FONT_SIZE)));
        mainPanel.add(new JScrollPane(sourceView), CELL_CONSTRAINTS.xyw(8, 8, 4));
        sourceView.setEditable(false);

        // Add some margin around the layout
        mainLayout.appendRow(RowSpec.decode(MARGIN));
        mainLayout.appendColumn(ColumnSpec.decode(MARGIN));
        mainLayout.insertRow(1, RowSpec.decode(MARGIN));
        mainLayout.insertColumn(1, ColumnSpec.decode(MARGIN));

        // Everything done, allow any action to actually update the merged entry
        doneBuilding = true;

        updateAll();

        // Show what we've got
        mainPanel.setVisible(true);
        SwingUtilities.invokeLater(() -> scrollPane.getVerticalScrollBar().setValue(0));
    }

    private int setupFieldRows(JPanel mergePanel) {
        // For all fields in joint add a row and possibly radio buttons
        int row = 2;
        int maxLabelWidth = -1;
        for (String field : allFields) {
            JLabel label = boldFontLabel(new SentenceCaseFormatter().format(field));
            mergePanel.add(label, CELL_CONSTRAINTS.xy(1, (2 * row) - 1, "left, top"));
            Optional<String> leftString = leftEntry.getFieldOptional(field);
            Optional<String> rightString = rightEntry.getFieldOptional(field);
            if (leftString.equals(rightString)) {
                identicalFields.add(field);
            } else {
                differentFields.add(field);
            }

            maxLabelWidth = Math.max(maxLabelWidth, label.getPreferredSize().width);

            // Left text pane
            if (leftString.isPresent()) {
                JTextPane tf = new DiffHighlightingTextPane();
                mergePanel.add(tf, CELL_CONSTRAINTS.xy(3, (2 * row) - 1, "f, f"));
                leftTextPanes.put(field, tf);
            }

            // Add radio buttons if the two entries do not have identical fields
            if (identicalFields.contains(field)) {
                mergedEntry.setField(field, leftString.get()); // Will only happen if both entries have the field and the content is identical
            } else {
                ButtonGroup group = new ButtonGroup();
                List<JRadioButton> list = new ArrayList<>(3);
                for (int k = 0; k < 3; k++) {
                    JRadioButton button = new JRadioButton();
                    group.add(button);
                    mergePanel.add(button, CELL_CONSTRAINTS.xy(5 + (k * 2), (2 * row) - 1));
                    button.addChangeListener(e -> updateAll());
                    list.add(button);
                }
                radioButtons.put(field, list);
                if (leftString.isPresent()) {
                    list.get(0).setSelected(true);
                    if (!rightString.isPresent()) {
                        list.get(2).setEnabled(false);
                    }
                } else {
                    list.get(0).setEnabled(false);
                    list.get(2).setSelected(true);
                }
            }

            // Right text pane
            if (rightString.isPresent()) {
                JTextPane tf = new DiffHighlightingTextPane();
                mergePanel.add(tf, CELL_CONSTRAINTS.xy(11, (2 * row) - 1, "f, f"));
                rightTextPanes.put(field, tf);
            }
            row++;
        }
        return maxLabelWidth;
    }

    private void setupEntryTypeRow(JPanel mergePanel) {
        // Start with entry type
        mergePanel.add(boldFontLabel(Localization.lang("Entry type")), CELL_CONSTRAINTS.xy(1, 1));

        JTextPane leftTypeDisplay = new DiffHighlightingTextPane();
        leftTypeDisplay.setText(DiffHighlighting.HTML_START + leftEntry.getType() + DiffHighlighting.HTML_END);
        mergePanel.add(leftTypeDisplay, CELL_CONSTRAINTS.xy(3, 1));
        if (leftEntry.getType().equals(rightEntry.getType())) {
            identicalTypes = true;
        } else {
            identicalTypes = false;
            ButtonGroup group = new ButtonGroup();
            typeRadioButtons = new ArrayList<>(2);
            for (int k = 0; k < 3; k += 2) {
                JRadioButton button = new JRadioButton();
                typeRadioButtons.add(button);
                group.add(button);
                mergePanel.add(button, CELL_CONSTRAINTS.xy(5 + (k * 2), 1));
                button.addChangeListener(e -> updateAll());
            }
            typeRadioButtons.get(0).setSelected(true);
        }
        JTextPane rightTypeDisplay = new DiffHighlightingTextPane();
        rightTypeDisplay.setText(DiffHighlighting.HTML_START + rightEntry.getType() + DiffHighlighting.HTML_END);
        mergePanel.add(rightTypeDisplay, CELL_CONSTRAINTS.xy(11, 1));
    }

    private void setupHeadingRows() {
        mainPanel.add(boldFontLabel(Localization.lang("Use")), CELL_CONSTRAINTS.xyw(4, 1, 7, "center, bottom"));
        mainPanel.add(diffMode, CELL_CONSTRAINTS.xy(11, 1, "right, bottom"));

        // Set headings
        for (int i = 0; i < 6; i++) {
            HEADING_LABELS.add(boldFontLabel(columnHeadings.get(i)));
            mainPanel.add(HEADING_LABELS.get(i), CELL_CONSTRAINTS.xy(1 + (i * 2), 2));
        }
    }

    private void fillDiffModes() {
        // Fill diff mode combo box
        for (String diffText : DIFF_MODES) {
            diffMode.addItem(diffText);
        }
        diffMode.setSelectedIndex(
                Math.min(Globals.prefs.getInt(JabRefPreferences.MERGE_ENTRIES_DIFF_MODE), diffMode.getItemCount() - 1));
        diffMode.addActionListener(e -> {
            updateTextPanes(differentFields);
            storePreference();
        });
    }

    private void synchronizeColumnWidths(FormLayout mainLayout, FormLayout mergeLayout,
            int maxLabelWidth) {
        // Synchronize column widths
        String[] rbAlign = {"right", "center", "left"};
        mainLayout.setColumnSpec(1, ColumnSpec.decode(Integer.toString(maxLabelWidth) + "px"));
        Integer maxRBWidth = -1;
        for (int k = 2; k < 5; k++) {
            maxRBWidth = Math.max(maxRBWidth, HEADING_LABELS.get(k).getPreferredSize().width);
        }
        for (int k = 0; k < 3; k++) {
            mergeLayout.setColumnSpec(5 + (k * 2), ColumnSpec.decode(rbAlign[k] + ":" + maxRBWidth + "px"));
        }
    }

    private JLabel boldFontLabel(String text) {
        JLabel label = new JLabel(text);
        Font font = label.getFont();
        label.setFont(font.deriveFont(font.getStyle() | Font.BOLD));
        return label;
    }

    private void storePreference() {
        Globals.prefs.putInt(JabRefPreferences.MERGE_ENTRIES_DIFF_MODE, diffMode.getSelectedIndex());
    }

    private void setupFields() {
        allFields.addAll(leftEntry.getFieldNames());
        allFields.addAll(rightEntry.getFieldNames());

        // Remove internal fields
        Set<String> toberemoved = new TreeSet<>();
        for (String field : allFields) {
            if (InternalBibtexFields.isInternalField(field)) {
                toberemoved.add(field);
            }
        }
        allFields.removeAll(toberemoved);
    }

    private void updateTextPanes(Collection<String> fields) {
        int oldScrollPaneValue = scrollPane.getVerticalScrollBar().getValue();
        for (String field : fields) {
            String leftString = leftEntry.getFieldOptional(field).orElse("");
            String rightString = rightEntry.getFieldOptional(field).orElse("");
            switch (diffMode.getSelectedIndex()) {
            case 0: // Plain text
                break;
            case 1: // Latexdiff style - word
                rightString = DiffHighlighting.generateDiffHighlighting(leftString, rightString, " ");
                break;
            case 2: // Latexdiff style - character
                rightString = DiffHighlighting.generateDiffHighlighting(leftString, rightString, "");
                break;
            case 3: // Symmetric style - word
                String tmpLeftString = DiffHighlighting.generateSymmetricHighlighting(leftString, rightString, " ");
                rightString = DiffHighlighting.generateSymmetricHighlighting(rightString, leftString, " ");
                leftString = tmpLeftString;
                break;
            case 4: // Symmetric style - character
                tmpLeftString = DiffHighlighting.generateSymmetricHighlighting(leftString, rightString, "");
                rightString = DiffHighlighting.generateSymmetricHighlighting(rightString, leftString, "");
                leftString = tmpLeftString;
                break;
            default: // Shouldn't happen
                break;
            }
            if ((leftString != null) && leftTextPanes.containsKey(field)) {
                leftTextPanes.get(field).setText(DiffHighlighting.HTML_START + leftString + DiffHighlighting.HTML_END);
            }
            if ((rightString != null) && rightTextPanes.containsKey(field)) {
                rightTextPanes.get(field).setText(DiffHighlighting.HTML_START + rightString + DiffHighlighting.HTML_END);
            }
        }
        SwingUtilities.invokeLater(() -> scrollPane.getVerticalScrollBar()
                .setValue(Math.min(scrollPane.getVerticalScrollBar().getMaximum(), oldScrollPaneValue)));
    }

    /**
     * @return Merged BibEntry
     */
    public BibEntry getMergeEntry() {
        return mergedEntry;
    }

    /**
     * @return The merge entry JPanel
     */
    public JPanel getMergeEntryPanel() {
        return mainPanel;
    }

    /**
     * Update the merged BibEntry with source and preview panel every time something is changed
     */
    private void updateAll() {
        if (!doneBuilding) {
            // If we are not done adding everything, do not do anything...
            return;
        }
        // Check if the type has changed
        if (!identicalTypes && typeRadioButtons.get(0).isSelected()) {
            mergedEntry.setType(leftEntry.getType());
        } else {
            mergedEntry.setType(rightEntry.getType());
        }

        // Check the potentially different fields
        for (String field : differentFields) {
            if (radioButtons.get(field).get(0).isSelected()) {
                mergedEntry.setField(field, leftEntry.getFieldOptional(field).get()); // Will only happen if field exists
            } else if (radioButtons.get(field).get(2).isSelected()) {
                mergedEntry.setField(field, rightEntry.getFieldOptional(field).get()); // Will only happen if field exists
            } else {
                mergedEntry.clearField(field);
            }
        }

        // Update the PreviewPanel
        entryPreview.setEntry(mergedEntry);

        // Update the BibTeX source view
        StringWriter writer = new StringWriter();
        try {
            new BibEntryWriter(new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)),
                    false).write(mergedEntry, writer, databaseType);
        } catch (IOException ex) {
            LOGGER.error("Error in entry", ex);
        }
        sourceView.setText(writer.getBuffer().toString());
        sourceView.setCaretPosition(0);
    }
}


text:
package com.squareup.spoon;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;

import static android.content.Context.MODE_WORLD_READABLE;
import static android.graphics.Bitmap.CompressFormat.PNG;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.os.Environment.getExternalStorageDirectory;
import static com.squareup.spoon.Chmod.chmodPlusR;
import static com.squareup.spoon.Chmod.chmodPlusRWX;

/** Utility class for capturing screenshots for Spoon. */
public final class Spoon {
  static final String SPOON_SCREENSHOTS = "spoon-screenshots";
  static final String SPOON_FILES = "spoon-files";
  static final String NAME_SEPARATOR = "_";
  static final String TEST_CASE_CLASS_JUNIT_3 = "android.test.InstrumentationTestCase";
  static final String TEST_CASE_METHOD_JUNIT_3 = "runMethod";
  static final String TEST_CASE_CLASS_JUNIT_4 = "org.junit.runners.model.FrameworkMethod$1";
  static final String TEST_CASE_METHOD_JUNIT_4 = "runReflectiveCall";
  static final String TEST_CASE_CLASS_CUCUMBER_JVM = "cucumber.runtime.model.CucumberFeature";
  static final String TEST_CASE_METHOD_CUCUMBER_JVM = "run";
  private static final String EXTENSION = ".png";
  private static final String TAG = "Spoon";
  private static final Object LOCK = new Object();
  private static final Pattern TAG_VALIDATION = Pattern.compile("[a-zA-Z0-9_-]+");
  private static final int LOLLIPOP_API_LEVEL = 21;
  private static final int MARSHMALLOW_API_LEVEL = 23;

  /** Holds a set of directories that have been cleared for this test */
  private static Set<String> clearedOutputDirectories = new HashSet<String>();

  /**
   * Take a screenshot with the specified tag.
   *
   * @param activity Activity with which to capture a screenshot.
   * @param tag Unique tag to further identify the screenshot. Must match [a-zA-Z0-9_-]+.
   * @return the image file that was created
   */
  public static File screenshot(Activity activity, String tag) {
    StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace());
    String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_");
    String methodName = testClass.getMethodName();
    return screenshot(activity, tag, className, methodName);
  }

  /**
   * Take a screenshot with the specified tag.  This version allows the caller to manually specify
   * the test class name and method name.  This is necessary when the screenshot is not called in
   * the traditional manner.
   *
   * @param activity Activity with which to capture a screenshot.
   * @param tag Unique tag to further identify the screenshot. Must match [a-zA-Z0-9_-]+.
   * @return the image file that was created
   */
  public static File screenshot(Activity activity, String tag, String testClassName,
      String testMethodName) {
    if (!TAG_VALIDATION.matcher(tag).matches()) {
      throw new IllegalArgumentException("Tag must match " + TAG_VALIDATION.pattern() + ".");
    }
    try {
      File screenshotDirectory =
          obtainScreenshotDirectory(activity.getApplicationContext(), testClassName,
              testMethodName);
      String screenshotName = System.currentTimeMillis() + NAME_SEPARATOR + tag + EXTENSION;
      File screenshotFile = new File(screenshotDirectory, screenshotName);
      takeScreenshot(screenshotFile, activity);
      Log.d(TAG, "Captured screenshot '" + tag + "'.");
      return screenshotFile;
    } catch (Exception e) {
      throw new RuntimeException("Unable to capture screenshot.", e);
    }
  }

  private static void takeScreenshot(File file, final Activity activity) throws IOException {
    View view = activity.getWindow().getDecorView();
    final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), ARGB_8888);

    if (Looper.myLooper() == Looper.getMainLooper()) {
      // On main thread already, Just Do It™.
      drawDecorViewToBitmap(activity, bitmap);
    } else {
      // On a background thread, post to main.
      final CountDownLatch latch = new CountDownLatch(1);
      activity.runOnUiThread(new Runnable() {
        @Override public void run() {
          try {
            drawDecorViewToBitmap(activity, bitmap);
          } finally {
            latch.countDown();
          }
        }
      });
      try {
        latch.await();
      } catch (InterruptedException e) {
        String msg = "Unable to get screenshot " + file.getAbsolutePath();
        Log.e(TAG, msg, e);
        throw new RuntimeException(msg, e);
      }
    }

    OutputStream fos = null;
    try {
      fos = new BufferedOutputStream(new FileOutputStream(file));
      bitmap.compress(PNG, 100 /* quality */, fos);

      chmodPlusR(file);
    } finally {
      bitmap.recycle();
      if (fos != null) {
        fos.close();
      }
    }
  }

  private static void drawDecorViewToBitmap(Activity activity, Bitmap bitmap) {
    Canvas canvas = new Canvas(bitmap);
    activity.getWindow().getDecorView().draw(canvas);
  }

  private static File obtainScreenshotDirectory(Context context, String testClassName,
      String testMethodName) throws IllegalAccessException {
    return filesDirectory(context, SPOON_SCREENSHOTS, testClassName, testMethodName);
  }

  /**
   * Alternative to {@link #save(Context, File)}
   * @param context Context used to access files.
   * @param path Path to the file you want to save.
   * @return the copy that was created.
   */
  public static File save(final Context context, final String path) {
    return save(context, new File(path));
  }

  /**
   * Save a file from this test run. The file will be saved under the current class & method.
   * The file will be copied to, so make sure all the data you want have been
   * written to the file before calling save.
   *
   * @param context Context used to access files.
   * @param file The file to save.
   * @return the copy that was created.
   */
  public static File save(final Context context, final File file) {
    StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace());
    String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_");
    String methodName = testClass.getMethodName();
    return save(context, className, methodName, file);
  }

  private static File save(Context context, String className, String methodName, File file) {
    File filesDirectory = null;
    try {
      filesDirectory = filesDirectory(context, SPOON_FILES, className, methodName);
      if (!file.exists()) {
        throw new RuntimeException("Can't find any file at: " + file);
      }

      File target = new File(filesDirectory, file.getName());
      copy(file, target);
      Log.d(TAG, "Saved " + file);
      return target;
    } catch (IllegalAccessException e) {
      throw new RuntimeException(("Unable to save file: " + file));
    } catch (IOException e) {
      throw new RuntimeException("Couldn't copy file " + file + " to " + filesDirectory);
    }
  }

  private static void copy(File source, File target) throws IOException {
    Log.d(TAG, "Will copy " + source + " to " + target);

    target.createNewFile();
    chmodPlusR(target);

    final BufferedInputStream is = new BufferedInputStream(new FileInputStream(source));
    final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(target));
    byte [] buffer = new byte[4096];
    while (is.read(buffer) > 0) {
      os.write(buffer);
    }
    is.close();
    os.close();
  }

  private static File filesDirectory(Context context, String directoryType, String testClassName,
      String testMethodName) throws IllegalAccessException {
    File directory;
    if (Build.VERSION.SDK_INT >= LOLLIPOP_API_LEVEL) {
      // Use external storage.
      directory = new File(getExternalStorageDirectory(), "app_" + directoryType);
    } else {
      // Use internal storage.
      directory = context.getDir(directoryType, MODE_WORLD_READABLE);
    }

    synchronized (LOCK) {
      if (!clearedOutputDirectories.contains(directoryType)) {
        deletePath(directory, false);
        clearedOutputDirectories.add(directoryType);
      }
    }

    File dirClass = new File(directory, testClassName);
    File dirMethod = new File(dirClass, testMethodName);
    createDir(dirMethod);
    return dirMethod;
  }

  /** Returns the test class element by looking at the method InstrumentationTestCase invokes. */
  static StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) {
    for (int i = trace.length - 1; i >= 0; i--) {
      StackTraceElement element = trace[i];
      if (TEST_CASE_CLASS_JUNIT_3.equals(element.getClassName()) //
          && TEST_CASE_METHOD_JUNIT_3.equals(element.getMethodName())) {
        return extractStackElement(trace, i);
      }

      if (TEST_CASE_CLASS_JUNIT_4.equals(element.getClassName()) //
          && TEST_CASE_METHOD_JUNIT_4.equals(element.getMethodName())) {
        return extractStackElement(trace, i);
      }
      if (TEST_CASE_CLASS_CUCUMBER_JVM.equals(element.getClassName()) //
              && TEST_CASE_METHOD_CUCUMBER_JVM.equals(element.getMethodName())) {
        return extractStackElement(trace, i);
      }
    }

    throw new IllegalArgumentException("Could not find test class!");
  }

  private static StackTraceElement extractStackElement(StackTraceElement[] trace, int i) {
    //Stacktrace length changed in M
    int testClassTraceIndex = Build.VERSION.SDK_INT >= MARSHMALLOW_API_LEVEL ? (i - 2) : (i - 3);
    return trace[testClassTraceIndex];
  }

  private static void createDir(File dir) throws IllegalAccessException {
    File parent = dir.getParentFile();
    if (!parent.exists()) {
      createDir(parent);
    }
    if (!dir.exists() && !dir.mkdirs()) {
      throw new IllegalAccessException("Unable to create output dir: " + dir.getAbsolutePath());
    }
    chmodPlusRWX(dir);
  }

  private static void deletePath(File path, boolean inclusive) {
    if (path.isDirectory()) {
      File[] children = path.listFiles();
      if (children != null) {
        for (File child : children) {
          deletePath(child, true);
        }
      }
    }
    if (inclusive) {
      path.delete();
    }
  }

  private Spoon() {
    // No instances.
  }
}


text:
package net.fortuna.ical4j.model.property;

import net.fortuna.ical4j.model.Escapable;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyFactoryImpl;
import net.fortuna.ical4j.model.ValidationException;

/**
 * $Id$
 *
 * Created: [Apr 6, 2004]
 *
 * Defines a EXTENDED_ADDRESS iCalendar component property.
 * @author benf
 * @author Mike Douglass
 */
public class ExtendedAddress extends Property implements Escapable {

	private static final long serialVersionUID = 6506776332370144983L;

	private String value;

    /**
     * Default constructor.
     */
    public ExtendedAddress() {
        super(EXTENDED_ADDRESS, PropertyFactoryImpl.getInstance());
    }

    /**
     * @param aValue a value string for this component
     */
    public ExtendedAddress(final String aValue) {
        super(EXTENDED_ADDRESS, PropertyFactoryImpl.getInstance());
        setValue(aValue);
    }

    /**
     * @param aList a list of parameters for this component
     * @param aValue a value string for this component
     */
    public ExtendedAddress(final ParameterList aList, final String aValue) {
        super(EXTENDED_ADDRESS, aList, PropertyFactoryImpl.getInstance());
        setValue(aValue);
    }

    /**
     * {@inheritDoc}
     */
    public final void validate() throws ValidationException {

        /*
         * ; the following is optional, ; and MAY occur more than once (";" xparam)
         */
    }

    /**
     * {@inheritDoc}
     */
    public final void setValue(final String aValue) {
        this.value = aValue;
    }

    /**
     * {@inheritDoc}
     */
    public final String getValue() {
        return value;
    }
}


text:
import type { ReactElement, ReactNode } from "react";
import { createContext, useContext, useMemo } from "react";
import type { HoverModeHookReturnValue } from "@react-md/utils";

/** @remarks \@since 5.0.0 */
export type MenuVisibilityContext = Pick<
  HoverModeHookReturnValue,
  "visible" | "setVisible"
>;

/**
 * @internal
 * @remarks \@since 5.0.0
 */
const context = createContext<MenuVisibilityContext>({
  visible: false,
  setVisible() {
    throw new Error('"MenuVisibilityProvider" must be a parent component');
  },
});
context.displayName = "MenuVisibility";

/**
 * @internal
 * @remarks \@since 5.0.0
 */
const { Provider } = context;

/**
 * This hook allows you control the visibility of a parent menu. The main
 * use-case for this hook is adding a custom sheet header/footer.
 *
 * @example
 * Simple Example
 * ```tsx
 * function SheetFooter(): ReactElement {
 *   const { setVisible } = useMenuVisibility();
 *
 *   return (
 *     <DialogFooter>
 *       <Button onClick={() => setVisible(false)}>Cancel</Button>
 *     </DialogFooter>
 *   );
 * }
 * ```
 *
 * @returns the {@link MenuVisibilityContext}
 * @remarks \@since 5.0.0
 */
export function useMenuVisibility(): Readonly<MenuVisibilityContext> {
  return useContext(context);
}

/**
 * @internal
 * @remarks \@since 5.0.0
 */
export interface MenuVisibilityProviderProps extends MenuVisibilityContext {
  children: ReactNode;
}

/**
 * @internal
 * @remarks \@since 5.0.0
 */
export function MenuVisibilityProvider({
  visible,
  setVisible,
  children,
}: MenuVisibilityProviderProps): ReactElement {
  const value = useMemo<MenuVisibilityContext>(
    () => ({
      visible,
      setVisible,
    }),
    [visible, setVisible]
  );

  return <Provider value={value}>{children}</Provider>;
}


text:
<?xml version="1.0" ?>
<project name="crap4j" default="run-crap4j" basedir="..">

	<!-- #1 redefine crap4j_home to point to the absolute directory where you unzipped crap4j -->
	<property name="CRAP4J_HOME" value="/Users/bobevans/Documents/projects/crap4j/org.crap4j/dist/crap4j"/>

	<!-- Define the Crap4j ant task -->
	<taskdef name="crap4j" classname="org.crap4j.anttask.Crap4jAntTask" >
		<classpath>
			<fileset dir="${CRAP4J_HOME}/lib">
				<include name="**/*.jar" />
			</fileset>
		</classpath>
	</taskdef>

	<!-- #2 Setup your project base directory. In most cases, it can just be basedir.
	       The following is a fancy version -->
	<!-- Use of ${project.dir.crap4j} allows for the resolution of relative paths
	        even when this file is imported in another build file -->
	<dirname file="${ant.file.crap4j}" property="import.dir.crap4j" />
	<condition property="my.project.root.dir" value="${import.dir.crap4j}/.." else="${basedir}">
		<isset property="import.dir.crap4j" />
	</condition>

	<!-- #3 Use crap4j on the project -->
	<target name="run-crap4j">
		<crap4j projectdir="${my.project.root.dir}"
			    outputDir="agitar/reports/crap4j"
			    dontTest="false" debug="false">

			<classes>
				<!-- put the project's class directories here. These are the classes you want crap numbers for -->
				<pathElement location="${my.project.root.dir}/bin" />
			</classes>

			<srces>
				<!-- The project's src folders -->
				<pathElement location="${my.project.root.dir}/src" />
			</srces>

			<testClasses>
				<!-- The project's test classes.
				         Note, separating it from the project classes makes life so much easier
				         but if you didn't, then you probably just want to repeat the classDir entry here -->
				<pathElement location="${my.project.root.dir}/test_bin" />
				<pathElement location="${my.project.root.dir}/integration_tests_bin" />
				<pathElement location="${my.project.root.dir}/agitar/test_bin" />
			</testClasses>

			<libClasspath>
				<!-- Put the dependent paths and libraries here.
				         This is for stuff necessary to your project, but not stuff you want analyzed -->
				<fileset dir="${my.project.root.dir}/lib">
					<include name="**/*.jar" />
				</fileset>
				<!-- if you get errors loading any agitar classes, like the mock classes, add this entry -->
				<!--
				<fileset dir="${CRAP4J_HOME}/lib/com.agitar.eclipse.api_4.2.0.401405/lib/ext">
				                    <include name="**/*.jar" />
				                </fileset>
				 -->
			</libClasspath>

		</crap4j>
	</target>
</project>


text:
namespace WinApiNet.Shell.Console
{
    using System;

    /// <summary>
    /// Defines valid values for the flags of a <see cref="ConsoleHistoryInfo"/> object.
    /// </summary>
    [Flags]
    public enum ConsoleHistoryInfoFlags : uint
    {
        /// <summary>
        /// No flags.
        /// </summary>
        NONE = 0x0,

        /// <summary>
        /// Duplicate entries will not be stored in the history buffer.
        /// </summary>
        HISTORY_NO_DUP_FLAG = 0x1
    }
}


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

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum StackInstanceStatus {

    CURRENT("CURRENT"),
    OUTDATED("OUTDATED"),
    INOPERABLE("INOPERABLE");

    private String value;

    private StackInstanceStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return StackInstanceStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static StackInstanceStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (StackInstanceStatus enumEntry : StackInstanceStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
Generated on $datetime for $projectname by
     $doxygenversion

       ©$year RoadNarrows LLC www.roadnarrows.com


text:
""" Yelp Dataset Challenge Module

.. moduleauthor:: Timothy Helton <timothy.j.helton@gmail.com>
"""

from collections import Counter
import datetime as dt
import logging
import os.path as osp
from typing import Tuple

from dateutil import parser
import pandas as pd
import simplejson

log_format = ('%(asctime)s  %(levelname)8s  -> %(name)s <- '
              '(line: %(lineno)d) %(message)s\n')
date_format = '%m/%d/%Y %I:%M:%S'
logging.basicConfig(format=log_format, datefmt=date_format,
                    level=logging.INFO)

current_dir = osp.dirname(osp.realpath(__file__))
data_dir = osp.realpath(osp.join(current_dir, '..', 'data', 'yelp'))
data_files = (
    'business',
    # 'checkin',
    'review',
    # 'tip',
    # 'user',
)

def convert_boolean(series: pd.Series) -> pd.Series:
    """Convert Pandas Series boolean values True to 1 and False to 0.

    :param pandas.Series series: Pandas Series to be converted
    """

    def conversion(conversion_dict):
        """Recursively convert boolean objects to integers.

        :param dict conversion_dict: dictionary to be converted
        :returns: original dictionary with boolean object replaced with \
            integers
        :rtype: dict
        """
        for k, v in conversion_dict.items():
            if isinstance(v, dict):
                conversion(v)
            elif isinstance(v, bool):
                conversion_dict[k] = v * 1
            else:
                conversion_dict.pop(k)
                conversion_dict[f'{k}_{v}'] = 1
        return conversion_dict

    return series.map(conversion)

class YDC:
    """Yelp Dataset Challenge Class

    :Attributes:

    **data_dir**: *str* path to directory containing data files
    **file_data**: *Dict[str, pandas.DataFrame]* data frames of the loaded \
        data files
    **file_paths**: *Dict[str, str]* paths to the data files
    **file_types**: *Tuple(str)* names of the files data files to be loaded

    """
    def __init__(self,
                 data_path: str=data_dir,
                 file_types: Tuple[str]=data_files):
        self.data_dir = data_path
        self.file_types = file_types
        self.file_paths = {}
        self.file_data = {}

    def __repr__(self) -> str:
        return (
            f'YDC('
            f'data_path={self.data_dir}, '
            f'file_types={self.file_types}'
        )

    def load_data(self):
        """Load original data from json files."""
        for file_type in self.file_types:
            path, data = self.data_files(file_type)
            self.file_paths[file_type] = path
            self.file_data[file_type] = data
            logging.info(f'File Loaded: {osp.basename(path)}')

    def calc_open_hours(self):
        """Populate the week day columns with open hours."""
        def daily_hours(row, day):
            """Calculate the number of hours a business in open each day.

            :param row: data frame index row
            :param str day: day of the week
            :return: number of hours business was open for a given day
            :rtype: int
            """
            midnight = parser.parse('00:00')
            tomorrow = midnight + dt.timedelta(days=1)

            try:
                hours = row['hours'][day]
                times = {k: parser.parse(v) for k, v in hours.items()}
                tot_hours = (times['close'] - times['open']).seconds / 3600

                if times['close'].time() < times['open'].time():
                    tot_hours = ((times['close'] - midnight
                                  + tomorrow - times['open']).seconds / 3600)

            except KeyError:
                tot_hours = 0

            return tot_hours

        days = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
                'Friday', 'Saturday')
        bus = self.file_data['business']
        for day in days:
            bus[day] = bus.apply(lambda x: daily_hours(x, day), axis=1)

    def data_files(self, descriptor: str):
        """Return path to data file for a specific descriptor.

        :param str descriptor: key word in data file (ex. business)
        :returns: full path to data file
        :rtype: str
        """
        prefix = 'yelp_academic_dataset_'
        extension = '.json'
        real_path = osp.realpath(osp.join(self.data_dir,
                                          f'{prefix}{descriptor}{extension}'))

        if descriptor == 'review':
            data_lines = []
            with open(real_path, 'r') as f:
                for line in f:
                    data_lines.append(simplejson.loads(line))
            data = pd.DataFrame(data_lines)
        else:
            data = pd.read_json(real_path, lines=True)
        return real_path, data

    def get_avg_stars(self):
        """Add the average customer review to the business data frame."""
        review = self.file_data['review']
        avg_stars = review.groupby('business_id')['stars'].mean().reset_index()
        avg_stars.columns = ['business_id', 'stars_avg']
        self.file_data['business'] = self.file_data['business'].merge(
            avg_stars, how='left', on='business_id')

    def get_restaurant_type(self):
        """Count the categories and save under a new column restaurant type."""
        def restaurant_type(categories):
            if 'Restaurants' in categories:
                types = Counter(categories)
                types.pop('Restaurants', None)
                all_types.extend([x for x in types.keys()
                                  if x not in all_types])
                return types
            else:
                return 'remove'

        all_types = []
        find_types = self.file_data['business'].categories.map(restaurant_type)
        all_restaurants = {x: 0 for x in all_types}
        find_types = find_types.map(
            lambda x: {**all_restaurants, **x} if isinstance(x, dict) else x)
        self.file_data['business']['restaurant_type'] = find_types

    def get_zip_codes_canada(self):
        """Look for zip codes from Canada."""
        bus = self.file_data['business']
        mask = bus.zip_code.isnull()
        codes = bus[mask].full_address.str.extract(r"(\w\d\w(\s\d\w\d)?$)",
                                                   expand=True)
        bus.loc[mask, 'zip_code'] = codes[0]

    def get_zip_codes_scotland(self):
        """Look for zip codes from Scotland."""
        bus = self.file_data['business']
        mask = bus.zip_code.isnull()
        codes = bus[mask].full_address.str.extract(r"(\w\w\d+\s?\d?(\w\w)?$)",
                                                   expand=True)
        bus.loc[mask, 'zip_code'] = codes[0]

    def get_zip_codes_usa(self):
        """Look for zip codes from the United States."""
        bus = self.file_data['business']
        bus['zip_code'] = bus.full_address.str.extract(r"(\d{5})", expand=True)

    def get_zip_codes(self):
        """Population the zip code column."""
        self.get_zip_codes_usa()
        self.get_zip_codes_canada()
        self.get_zip_codes_scotland()


text:
import { HomeComponent } from './Home';

export let components = {
    HomeComponent: HomeComponent,
}

export let componentsList = Object.keys(components).map((key) => {
    return components[key];
})


text:
namespace IECoreArnold
{

namespace ShaderNetworkAlgo
{

/// Returns a network of `AtNodes` generated by converting `shaderNetwork`
/// to Arnold. The output shader is the last node in the returned vector,
/// and is given the specified `name`. All other nodes will be named
/// uniquely using `name` as a prefix.
IECOREARNOLD_API std::vector<AtNode *> convert( const IECoreScene::ShaderNetwork *shaderNetwork, AtUniverse *universe, const std::string &name, const AtNode *parentNode = nullptr );
/// Updates a previously converted set of nodes to reflect changes in `shaderNetwork`,
/// reusing AtNodes where possible. The `nodes` vector is updated in place, newly created
/// nodes use the same parent as the original nodes, and unused nodes are destroyed with
/// `AiNodeDestroy`. Returns true if the output shader node is reused.
IECOREARNOLD_API bool update( std::vector<AtNode *> &nodes, const IECoreScene::ShaderNetwork *shaderNetwork );

} // namespace ShaderNetworkAlgo

} // namespace IECoreArnold

#endif // IECOREARNOLD_SHADERNETWORKALGO_H


text:
import os
import sys

STRING = "Hello, World!"
NUMBER = 123.4


text:
from . import universities
from . import likes
from . import profile
from . import students
from . import recommendations


text:
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/crowi/go-crowi"
	"github.com/k0kubun/pp"
	"golang.org/x/net/context"
)

func main() {
	config := crowi.Config{
		URL:   "http://localhost:3000",
		Token: os.Getenv("CROWI_ACCESS_TOKEN"),
	}
	client, err := crowi.NewClient(config)
	if err != nil {
		panic(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	var (
		path = fmt.Sprintf("/user/%s/go-crowi-test-%d", os.Getenv("USER"), time.Now().UnixNano())
		body = "# this is a sample\n\ntest"
	)

	res, err := client.Pages.Create(ctx, path, body)
	if err != nil {
		panic(err)
	}

	_, err = client.Attachments.Add(ctx, res.Page.ID, "_example/attachments/sample.png")
	if err != nil {
		panic(err)
	}

	res2, err := client.Attachments.List(ctx, res.Page.ID)
	if err != nil {
		panic(err)
	}

	pp.Println(res2)
}


text:
"""Test the smarttub config flow."""
from unittest.mock import patch

from smarttub import LoginFailed

from homeassistant import config_entries, data_entry_flow
from homeassistant.components.smarttub.const import DOMAIN
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD

from tests.common import MockConfigEntry

async def test_form(hass):
    """Test we get the form."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )
    assert result["type"] == "form"
    assert result["errors"] == {}

    with patch(
        "homeassistant.components.smarttub.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"},
        )

        assert result["type"] == "create_entry"
        assert result["title"] == "test-email"
        assert result["data"] == {
            CONF_EMAIL: "test-email",
            CONF_PASSWORD: "test-password",
        }
        await hass.async_block_till_done()
        mock_setup_entry.assert_called_once()

async def test_form_invalid_auth(hass, smarttub_api):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER}
    )

    smarttub_api.login.side_effect = LoginFailed

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"},
    )

    assert result["type"] == "form"
    assert result["errors"] == {"base": "invalid_auth"}

async def test_reauth_success(hass, smarttub_api, account):
    """Test reauthentication flow."""
    mock_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"},
        unique_id=account.id,
    )
    mock_entry.add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={
            "source": config_entries.SOURCE_REAUTH,
            "unique_id": mock_entry.unique_id,
            "entry_id": mock_entry.entry_id,
        },
        data=mock_entry.data,
    )

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "reauth_confirm"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {CONF_EMAIL: "test-email3", CONF_PASSWORD: "test-password3"}
    )

    assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
    assert result["reason"] == "reauth_successful"
    assert mock_entry.data[CONF_EMAIL] == "test-email3"
    assert mock_entry.data[CONF_PASSWORD] == "test-password3"

async def test_reauth_wrong_account(hass, smarttub_api, account):
    """Test reauthentication flow if the user enters credentials for a different already-configured account."""
    mock_entry1 = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_EMAIL: "test-email1", CONF_PASSWORD: "test-password1"},
        unique_id=account.id,
    )
    mock_entry1.add_to_hass(hass)

    mock_entry2 = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_EMAIL: "test-email2", CONF_PASSWORD: "test-password2"},
        unique_id="mockaccount2",
    )
    mock_entry2.add_to_hass(hass)

    # we try to reauth account #2, and the user successfully authenticates to account #1
    account.id = mock_entry1.unique_id
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={
            "source": config_entries.SOURCE_REAUTH,
            "unique_id": mock_entry2.unique_id,
            "entry_id": mock_entry2.entry_id,
        },
        data=mock_entry2.data,
    )

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "reauth_confirm"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"], {CONF_EMAIL: "test-email1", CONF_PASSWORD: "test-password1"}
    )

    assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
    assert result["reason"] == "already_configured"


text:
title: ECG BOOK CHAPTER 9 - Clifford Lab
permalink: "/ecgbookchapter9.html"
layout: default
---

ST Analysis - Chapter 9

F. Jager

This page provides supplementary information and relevant links for Chapter 9 in Advanced Methods for ECG Analysis, which is co-edited by Francisco Azuaje and Patrick McSharry, and is published
                by
                Artech House
                . The main URL for this book can be found here, together with ordering information. Much of the software associated with this book can be found here.

Links:

Download sample of chapter

Morphology Representation Using Principal Components - Tutuorlal and software

QRS Morphology Representation and Noise Estimation using the Karhunen-Loève Transform - George B. Moody and Roger G. Mark, Computers in Cardiology 1989, pp. 269-272

ECGtools - A selection of ECG analysis tools in Matlab including a self-explaining QRS detector, filtering tools and HRV analysis algorithms.

Long-Term ST Database

European ST Database

SEMIA  - View time series of diagnostic and morphologic parameters of the Long-Term ST Database, together with the corresponding ECG waveforms and their annotations

Contents:

9.1 Introduction

9.2 Phenomenology of T-Wave Alternans

9.3 Pathophysiology of T-Wave Alternans

9.3.1 Derivation of Orthonormal Function Model Transform-Based Morphology Feature Vectors

9.3.2 Derivation of Time-Domain Diagnostic and Morphologic Feature Vectors

9.4 Shape Representation in Terms of Feature-Vector Time Series

9.5 Appendix 9A

 2017 Clifford Lab