text:
package org.thingml.compilers.c.teensy;

import org.thingml.compilers.Context;
import org.thingml.compilers.configuration.CfgBuildCompiler;
import org.thingml.xtext.helpers.AnnotatedElementHelper;
import org.thingml.xtext.helpers.ConfigurationHelper;
import org.thingml.xtext.thingML.Configuration;
import org.thingml.xtext.thingML.Thing;

public class TeensyCCfgBuildCompiler extends CfgBuildCompiler{

	@Override
	public void generateBuildScript(Configuration cfg, Context ctx) {
		generateLinuxMakefile(cfg, (CCompilerContextTeensy) ctx);
	}

	  protected String getSourceFileName(Thing thing) {
	        return "src/" + thing.getName() + ".cpp ";
	    }

	private void generateLinuxMakefile(Configuration cfg, CCompilerContextTeensy ctx) {

        //GENERATE THE MAKEFILE
        String mtemplate = ctx.getTemplateByID("ctemplates/Teensy_Makefile");

        if(AnnotatedElementHelper.hasAnnotation(cfg, "teensy_platform")){
        	String platform = AnnotatedElementHelper.annotation(cfg, "teensy_platform").get(0);
        	mtemplate = mtemplate.replace("/*PLATFORM*/", platform);
        } else {
        	mtemplate = mtemplate.replace("/*PLATFORM*/", "32");
        }

        if(AnnotatedElementHelper.hasAnnotation(cfg, "teensy_overclock")){
        	mtemplate = mtemplate.replace("/*OVERCLOCK*/", "overclock");
        } else {
        	mtemplate = mtemplate.replace("/*OVERCLOCK*/", "default");
        }
        if(AnnotatedElementHelper.hasAnnotation(cfg, "teensy_corepath")){
        	String corepath = AnnotatedElementHelper.annotation(cfg, "teensy_corepath").get(0);
        	mtemplate = mtemplate.replace("/*COREPATH*/", corepath);
        } else {
        	mtemplate = mtemplate.replace("/*COREPATH*/", "${TEENSY_COREPATH}");
        }

        if(AnnotatedElementHelper.hasAnnotation(cfg, "teensy_externpath")){
        	String externpath = AnnotatedElementHelper.annotation(cfg,"teensy_externpath").get(0);
        	mtemplate = mtemplate.replace("/*EXTERNPATH*/", "# path location for your code\nEXTERNPATH = /*EXTERNPATH*/\nTMPEXTERNFOLDER := $(subst /, ,$(EXTERNPATH))\nEXTERNFOLDER := $(word $(shell echo $(words $(TMPEXTERNFOLDER))),$(TMPEXTERNFOLDER))");
        	mtemplate = mtemplate.replace("/*EXTERNPATH*/", externpath);
        	mtemplate = mtemplate.replace("/*EXTERNINCLUDE*/"," -I$(EXTERNPATH)");
        	mtemplate = mtemplate.replace("/*SOURCES_EXTERN*/", " $(SOURCES_EXTERN)");
        	mtemplate = mtemplate.replace("/*EXTERNSOURCES*/", "C_EXTERN := $(wildcard $(EXTERNPATH)/*.c)\nCPP_EXTERN := $(wildcard $(EXTERNPATH)/*.cpp)\nSOURCES_EXTERN := $(C_EXTERN:.c=.o) $(CPP_EXTERN:.cpp=.o)");
        	mtemplate = mtemplate.replace("/*EXTERNOBJS*/", " $(subst $(EXTERNPATH),$(BUILDDIR)/$(EXTERNFOLDER),$(SOURCES_EXTERN))");
        	mtemplate = mtemplate.replace("/*EXTERNBUILDER*/","$(BUILDDIR)/$(EXTERNFOLDER)/%.o: $(EXTERNPATH)/%.c\n\t@echo -e \"[CC]\t$<\"\n\t@mkdir -p \"$(dir $@)\"\n\t@$(CC) $(CPPFLAGS) $(CFLAGS) -o \"$@\" -c \"$<\"\n\n$(BUILDDIR)/$(EXTERNFOLDER)/%.o: $(EXTERNPATH)/%.cpp\n\t@echo -e \"[CXX]\t$<\"\n\t@mkdir -p \"$(dir $@)\"\n\t@$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o \"$@\" -c \"$<\"");
        }else {
        	mtemplate = mtemplate.replace("/*EXTERNPATH*/", "");
        	mtemplate = mtemplate.replace("/*EXTERNINCLUDE*/", "");
        	mtemplate = mtemplate.replace("/*EXTERNSOURCES*/", "");
        	mtemplate = mtemplate.replace("/*SOURCES_EXTERN*/", "");
        	mtemplate = mtemplate.replace("/*EXTERNOBJS*/", "");
        	mtemplate = mtemplate.replace("/*EXTERNBUILDER*/","");
        }

        if(AnnotatedElementHelper.hasAnnotation(cfg, "teensy_libpath")){
        	int i = 0;
        	for(String libpath : AnnotatedElementHelper.annotation(cfg,"teensy_libpath")){
        		mtemplate = mtemplate.replace("/*LIBPATH*/", "# path location for your LIB"+i+"\nLIB"+i+"PATH = /*LIB_PATH*/\nTMPLIB"+i+"FOLDER := $(subst /, ,$(LIB"+i+"PATH))\nLIB"+i+"FOLDER := $(word $(shell echo $(words $(TMPLIB"+i+"FOLDER))),$(TMPLIB"+i+"FOLDER))\n\n/*LIBPATH*/");
            	mtemplate = mtemplate.replace("/*LIB_PATH*/", libpath);
            	mtemplate = mtemplate.replace("/*LIBINCLUDE*/"," -I$(LIB"+i+"PATH)/*LIBINCLUDE*/");
            	mtemplate = mtemplate.replace("/*SOURCES_LIB*/", " $(SOURCES_LIB"+i+")/*SOURCES_LIB*/");
            	mtemplate = mtemplate.replace("/*LIBSOURCES*/", "C_LIB"+i+" := $(wildcard $(LIB"+i+"PATH)/*.c)\nCPP_LIB"+i+" := $(wildcard $(LIB"+i+"PATH)/*.cpp)\nSOURCES_LIB"+i+" := $(C_LIB"+i+":.c=.o) $(CPP_LIB"+i+":.cpp=.o)\n/*LIBSOURCES*/");
            	mtemplate = mtemplate.replace("/*LIBOBJS*/", " $(subst $(LIB"+i+"PATH),$(BUILDDIR)/$(LIB"+i+"FOLDER),$(SOURCES_LIB"+i+"))\n/*LIBOBJS*/");
            	mtemplate = mtemplate.replace("/*LIBBUILDER*/","$(BUILDDIR)/$(LIB"+i+"FOLDER)/%.o: $(LIB"+i+"PATH)/%.c\n\t@echo -e \"[CC]\t$<\"\n\t@mkdir -p \"$(dir $@)\"\n\t@$(CC) $(CPPFLAGS) $(CFLAGS) -o \"$@\" -c \"$<\"\n\n$(BUILDDIR)/$(LIB"+i+"FOLDER)/%.o: $(LIB"+i+"PATH)/%.cpp\n\t@echo -e \"[CXX]\t$<\"\n\t@mkdir -p \"$(dir $@)\"\n\t@$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o \"$@\" -c \"$<\"\n\n/*LIBBUILDER*/");
            	i++;
        	}

        }
        mtemplate = mtemplate.replace("/*LIBPATH*/", "");
    	mtemplate = mtemplate.replace("/*LIBINCLUDE*/", "");
    	mtemplate = mtemplate.replace("/*LIBSOURCES*/", "");
    	mtemplate = mtemplate.replace("/*SOURCES_LIB*/", "");
    	mtemplate = mtemplate.replace("/*LIBOBJS*/", "");
    	mtemplate = mtemplate.replace("/*LIBBUILDER*/","");

    	// Add all generated files
        //mtemplate = mtemplate.replace("/*SOURCES*/", srcs.toString().trim());
    	mtemplate = mtemplate.replace("/*SOURCES*/", String.join(" ",ctx.getGeneratedSources()).replace("\\", "/"));
        mtemplate = mtemplate.replace("/*LIBS*/", /*libs*/"");

        ctx.getBuilder("Makefile").append(mtemplate);
	}
}


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>DragonBones Demo</title>

    <script src="./libs/phaser/phaser.js"></script>
    <script src="./libs/dragonBones/dragonBones.js"></script>

    <script src="./out/DragHelper.js"></script>
    <script src="./out/BaseDemo.js"></script>
    <script src="./out/HelloDragonBones.js"></script>
    <script src="./out/AnimationBase.js"></script>
    <script src="./out/DragonBonesEvent.js"></script>
    <script src="./out/AnimationLayer.js"></script>
    <script src="./out/BoneOffset.js"></script>
    <script src="./out/InverseKinematics.js"></script>
    <script src="./out/BoundingBox.js"></script>
    <script src="./out/ReplaceSlotDisplay.js"></script>
    <script src="./out/ReplaceAnimation.js"></script>
    <script src="./out/CoreElement.js"></script>
    <script src="./out/PerformanceTest.js"></script>
</head>

<body>
    <script>
    const config = {
        version: "1.0",

        // canvas: document.createElement("CANVAS"),
        width: 1000,
        height: 640,
        backgroundColor: 0x0,

        render: {
            pixelArt: false,
            clearBeforeRender: false
        },

        disableContextMenu: true,

        plugins: {
            scene: [
                { key: "DragonBones", plugin: dragonBones.phaser.plugin.DragonBonesScenePlugin, mapping: "dragonbone" }    // setup DB scene plugin
            ]
        },

        scene: HelloDragonBones    // scene to display
        // scene: AnimationBase
        // scene: DragonBonesEvent
        // scene: AnimationLayer
        // scene: BoneOffset
        // scene: InverseKinematics
        // scene: BoundingBox // TODO maby this has issue to run
        // scene: ReplaceSlotDisplay
        // scene: ReplaceAnimation
        // scene: coreElement.Game
        // scene: PerformanceTest
    };

    new Phaser.Game(config);
    </script>
</body>

</html>

redpajama_set_name: RedPajamaGithub


text:
rtstool
=======

rtslib command-line interface

Licensed under Apache License, Version 2.0.


text:
/**
 * @since 2016-11-15 20:41
 * @author vivaxy
 */

import path from 'path';
import fse from 'fs-extra';

export default ({ project }) => {
    return async(filename, data) => {
        const distFolder = project.folder;
        const distFilename = path.join(distFolder, filename);

        await fse.outputFile(distFilename, data);
    };
};


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

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:fillColor="#FF000000"
      android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8zM16.59,7.58L10,14.17l-2.59,-2.58L6,13l4,4 8,-8z"/>
</vector>


text:
<?xml version="1.0"?>

<layout version="0.1.0">
    <default>
        <reference name="head">
            <block type="core/template" name="qubit_uv" template="qubit/uv.phtml"/>
        </reference>
    </default>
</layout>


text:
layout: page
title: Terry Williams's 35th Birthday
date: 2016-05-24
author: Brandon Mejia
tags: weekly links, java
status: published
summary: Aenean egestas, urna convallis pellentesque condimentum, mauris.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 08/09/2019
  endDate: 08/13/2019
  ctyhocn: TIFOHHX
  groupCode: TW3B
published: true
---
Donec egestas, libero sit amet hendrerit aliquam, risus lorem mattis metus, id interdum felis felis vehicula enim. Ut in massa ac risus interdum malesuada. Ut malesuada ex eget urna sagittis, commodo feugiat ante egestas. Nam faucibus sagittis cursus. Phasellus porta, velit non congue venenatis, ipsum turpis ultrices dolor, eu consectetur ex sem ut mauris. Sed ornare malesuada lacus vel ullamcorper. Praesent urna augue, gravida et massa id, iaculis luctus turpis.

1 Integer id eros quis lectus volutpat ultrices consectetur id quam
1 Nullam at eros ut augue dictum condimentum
1 Duis viverra odio quis condimentum venenatis
1 Fusce semper erat quis dictum ultricies
1 Donec pulvinar nibh a mi ullamcorper gravida.

Sed molestie pulvinar lectus nec bibendum. Vestibulum nibh arcu, cursus vitae risus ut, iaculis pretium mi. Suspendisse potenti. Nullam in mattis velit. Morbi a orci efficitur, ultrices dolor vitae, auctor dolor. In elementum efficitur eros, non sodales ipsum pharetra eget. Praesent ultrices tempus lacinia. Pellentesque ac risus non risus pretium sagittis sit amet ut velit. Suspendisse neque massa, convallis a cursus sed, ultrices non mi. Nunc lobortis quam vitae maximus consectetur. Vivamus mattis lorem sit amet lectus molestie rutrum. Nulla aliquam elit ligula, sit amet imperdiet nibh hendrerit eget. Cras malesuada magna lacus, quis congue enim tempus sed. Suspendisse congue venenatis dui, eget sodales massa vulputate sed.
Nullam quis pellentesque lectus. Donec at eros tortor. Ut vitae nibh in quam pretium venenatis vitae ullamcorper velit. Nullam vitae efficitur magna, non elementum sem. Fusce mattis, erat ut accumsan pellentesque, lectus magna tempor diam, sit amet pretium purus dui a tellus. Sed suscipit nisi vel luctus rutrum. Sed nec dolor augue. Vestibulum eu aliquam augue. Nullam consectetur a lacus eu sagittis. Cras a maximus purus. Donec elit ex, hendrerit nec lectus in, euismod sagittis leo. Sed quis tortor tortor. Nullam et dapibus lorem.


text: Rails.application.config.session_store :cookie_store, key: '_u2i-jenkins-rails_project_session'


text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
/*
	$Id: Categorie.class.php,v 1.1 2013-09-30 09:30:48 raphael Exp $
	$Author: raphael $

	$Log: Categorie.class.php,v $
	Revision 1.1  2013-09-30 09:30:48  raphael
	*** empty log message ***

	Revision 1.2  2013-03-01 10:33:59  pierre
	*** empty log message ***

	Revision 1.1  2009-02-16 15:01:39  pierre
	*** empty log message ***

	Revision 1.2  2009-02-16 14:59:58  pierre
	*** empty log message ***

	Revision 1.3  2008/03/04 14:55:54  pierre
	*** empty log message ***

	Revision 1.2  2007/06/06 14:54:39  pierre
	*** empty log message ***

	Revision 1.1  2006/04/12 07:26:22  sylvie
	*** empty log message ***

	Revision 1.2  2004/06/04 12:35:30  ddinside
	fin petites annonces

	Revision 1.1  2004/06/01 14:25:19  ddinside
	ajout petites annonce dont gardes finies
	newslettrer

	Revision 1.1  2004/05/18 15:20:31  ddinside
	classe gestino des inscrits

	Revision 1.1  2004/05/18 13:47:12  ddinside
	creation module petites annonces

*/

class Categorie {

	// Propriétés
	var $dbConn = null;

	var $id = null;
	var $libelle = '';
	var $isGarde = 0;
	var $ordre = 0;
	var $id_site = 0;

	var $listAnnonces = array();

// constructeur
function Categorie($id=null)
{
	global $db;
	$this->dbConn = &$db;

	if($id!=null) {
		//$this = dbGetObjectFromPK("Categorie", $id);
		$temp = dbGetObjectFromPK("Categorie", $id);
		foreach ($temp as $key => $val){
			$this->$key = $val;
		}
	} else {

		$this->id = '';
		$this->libelle = '';
		$this->isGarde = '';
		$this->ordre = 99;
		$this->id_site = $_SESSION['idSite_travail'];
	}
}

// liste des champs de l'objet
function getListeChamps()
{
	// ATTENTION, respecter l'ordre des champs de la table dans la base de données pour construire laListeChamp

	$laListeChamps[]=new dbChamp("categorie_id", "entier", "getId", "setId");
	$laListeChamps[]=new dbChamp("categorie_libelle", "text", "getLibelle", "setLibelle");
	$laListeChamps[]=new dbChamp("categorie_is_garde", "entier", "getIs_garde", "setIs_garde");
	$laListeChamps[]=new dbChamp("categorie_ordre", "entier", "getOrdre", "setOrdre");

	$laListeChamps[]=new dbChamp("id_site", "entier", "getId_site", "setId_site");

	return($laListeChamps);
}

function getId() { return($this->id); }
function getLibelle() { return($this->libelle); }
function getIs_garde() { return($this->isGarde); }
function getOrdre() { return($this->ordre); }
function getId_site() { return($this->id_site); }

function setId($c_id) { return($this->id=$c_id); }
function setLibelle($c_libelle) { return($this->libelle=$c_libelle); }
function setIs_garde($c_isGarde) { return($this->isGarde=$c_isGarde); }
function setOrdre($c_ordre) { return($this->ordre=$c_ordre); }
function setId_site($c_id_site) { return($this->id_site=$c_id_site); }

// autres getters
function getGetterPK() { return("getId"); }
function getSetterPK() { return("setId"); }
function getFieldPK() { return("categorie_id"); }
function getTable() { return("pa_categories"); }
function getClasse() { return("Categorie"); }

	function initValues($id) {
		$sql = "select categorie_id, categorie_libelle, categorie_is_garde, categorie_ordre from pa_categories where categorie_id = $id";
		$rs = $this->dbConn->Execute($sql);
		if($rs && !$rs->EOF) {
			$this->id = $rs->fields[0];
			$this->libelle = $rs->fields[1];
			$this->isGarde = $rs->fields[2];
			$this->ordre = $rs->fields[3];
		} else {
			error_log($_SERVER['PHP_SELF']);
			error_log('erreur ou résultat vide lors de l\'execution de la requete');
			error_log($sql);
			error_log($this->dbConn->ErrorMsg());
			error_log($_SERVER['PHP_SELF']);
		}
	}

	function listToutesCategories() {
		$result = array();

		$sql = " SELECT categorie_id";
		$sql.= " FROM pa_categories";
		$sql.= " ORDER BY categorie_is_garde, categorie_ordre, categorie_id";
		if (DEF_BDD != "ORACLE") $sql.= ";";

		$rs = $this->dbConn->Execute($sql);
		if($rs) {
			while(!$rs->EOF) {
				$uneCategorie = new Categorie($rs->fields[0]);
				array_push($result,$uneCategorie);
				$rs->MoveNext();
			}
		} else {
			error_log($_SERVER['PHP_SELF']);
			error_log('erreur lors de l\'execution de la requete');
			error_log($sql);
			error_log($this->dbConn->ErrorMsg());
			error_log($_SERVER['PHP_SELF']);
		}
		return $result;
	}

	function listCategories($isGarde=0) {

		$result = array();

		$sql = " SELECT categorie_id from pa_categories";
		$sql.= " WHERE categorie_is_garde=$isGarde AND id_site=".$_SESSION['idSite_pa'];
		$sql.= " ORDER BY categorie_ordre, categorie_id";
		if (DEF_BDD != "ORACLE") $sql.= ";";

		$rs = $this->dbConn->Execute($sql);

		if($rs) {
			while(!$rs->EOF) {
				$uneCategorie = new Categorie($rs->fields[0]);
				array_push($result,$uneCategorie);
				$rs->MoveNext();
			}
		} else {
			error_log($_SERVER['PHP_SELF']);
			error_log('erreur lors de l\'execution de la requete');
			error_log($sql);
			error_log($this->dbConn->ErrorMsg());
			error_log($_SERVER['PHP_SELF']);
		}
		return $result;
	}

	function listAnnonces($type='garde') {
		$result = array();
		$sql = '';
		if($type=='garde') {
			$sql = "select annonce_id from pa_annonces where annonce_categorie_id = ".$this->id." and annonce_valid=1 order by annonce_dt_debut desc, annonce_dt_perim";
		} elseif($type=='offre') {
			$sql = "select annonce_id from pa_annonces where annonce_categorie_id = ".$this->id." and annonce_valid=1 and annonce_is_offre = 1 order by annonce_dt_debut desc, annonce_dt_perim";
		} elseif($type=='demande') {
			$sql = "select annonce_id from pa_annonces where annonce_categorie_id = ".$this->id." and annonce_valid=1 and annonce_is_offre = 0 order by annonce_dt_debut desc, annonce_dt_perim";
		}
		$rs = $this->dbConn->Execute($sql);
		if($rs) {
			while(!$rs->EOF) {
				$uneAnnonce = new Annonce($rs->fields[0]);
				array_push($result,$uneAnnonce);
				$rs->MoveNext();
			}
		} else {
			error_log($_SERVER['PHP_SELF']);
			error_log('erreur lors de l\'execution de la requete');
			error_log($sql);
			error_log($this->dbConn->ErrorMsg());
			error_log($_SERVER['PHP_SELF']);
		}
		return $result;
	}

	function setListAnnonces($type='garde') {

		if(sizeof($this->listAnnonces)==0) {
			$sql = '';

			if($type == 'garde') {
				$sql = " SELECT annonce_id FROM pa_annonces ";
				$sql.= " WHERE annonce_valid=1 AND annonce_categorie_id=".$this->id;
				$sql.= " AND id_site=".$_SESSION['idSite_pa'];
				$sql.= " ORDER BY annonce_dt_debut desc, annonce_dt_perim";
			} elseif ($type == 'offre') {
				$sql = " SELECT annonce_id FROM pa_annonces ";
				$sql.= " WHERE annonce_valid=1 AND annonce_categorie_id=".$this->id." AND annonce_is_offre=1 ";
				$sql.= " AND id_site=".$_SESSION['idSite_pa'];
				$sql.= " ORDER BY annonce_dt_debut desc, annonce_dt_perim";
			} elseif ($type == 'demande') {
				$sql = " SELECT annonce_id FROM pa_annonces WHERE annonce_valid=1 ";
				$sql.= " AND annonce_categorie_id=".$this->id." AND annonce_is_offre=0 ";
				$sql.= " AND id_site=".$_SESSION['idSite_pa'];
				$sql.= " ORDER BY annonce_dt_debut desc, annonce_dt_perim";
			}

			$rs = $this->dbConn->Execute($sql);

			if($rs) {
				while(!$rs->EOF){
					$uneAnnonce = new Annonce($rs->fields[0]);
					array_push($this->listAnnonces, $uneAnnonce);
					$rs->MoveNext();
				}
				return true;
			} else {
				error_log($_SERVER['PHP_SELF']);
				error_log('erreur lors de l\'execution de la requete');
				error_log($sql);
				error_log($this->dbConn->ErrorMsg());
				error_log($_SERVER['PHP_SELF']);

			}
		}
		return true;
	}
}
?>


text:
void kafka_metadata_topic_minit(INIT_FUNC_ARGS);
void kafka_metadata_topic_ctor(zval *return_value, zval *zmetadata, const void *metadata_topic);


text:
namespace content {
class BrowserContext;
class RenderProcessHost;
}

namespace extensions {
class Extension;

// Informs renderers about extensions-related data (loaded extensions, available
// functions, etc.) when they start. Sends this information to both extension
// and non-extension renderers, as the non-extension renderers may have content
// scripts. Lives on the UI thread. Shared between incognito and non-incognito
// browser contexts. Also handles sending the loaded, unloaded, and activated
// extension messages, since these can *only* be sent once the process is
// initialized.
// TODO(devlin): "StartupHelper" is no longer sufficient to describe the entire
// behavior of this class.
class RendererStartupHelper : public KeyedService,
                              public content::RenderProcessHostCreationObserver,
                              public content::RenderProcessHostObserver {
 public:
  // This class sends messages to all renderers started for |browser_context|.
  explicit RendererStartupHelper(content::BrowserContext* browser_context);
  ~RendererStartupHelper() override;

  // content::RenderProcessHostCreationObserver:
  void OnRenderProcessHostCreated(
      content::RenderProcessHost* process_host) override;

  // content::RenderProcessHostObserver:
  void RenderProcessExited(
      content::RenderProcessHost* host,
      const content::ChildProcessTerminationInfo& info) override;
  void RenderProcessHostDestroyed(content::RenderProcessHost* host) override;

  // Sends a message to the specified |process| activating the given extension
  // once the process is initialized. OnExtensionLoaded should have already been
  // called for the extension.
  void ActivateExtensionInProcess(const Extension& extension,
                                  content::RenderProcessHost* process);

  // Sends a message to all initialized processes to [un]load the given
  // extension. We have explicit calls for these (rather than using an
  // ExtensionRegistryObserver) because this needs to happen before other
  // initialization which might rely on the renderers being notified.
  void OnExtensionUnloaded(const Extension& extension);
  void OnExtensionLoaded(const Extension& extension);

 private:
  friend class RendererStartupHelperTest;

  // Initializes the specified process, informing it of system state and loaded
  // extensions.
  void InitializeProcess(content::RenderProcessHost* process);

  // Untracks the given process.
  void UntrackProcess(content::RenderProcessHost* process);

  content::BrowserContext* browser_context_;  // Not owned.

  // Tracks the set of loaded extensions and the processes they are loaded in.
  std::map<ExtensionId, std::set<content::RenderProcessHost*>>
      extension_process_map_;

  // The set of render processes that have had the initial batch of IPC messages
  // sent, including the set of loaded extensions. Further messages that
  // activate, load, or unload extensions should not be sent until after this
  // happens.
  std::set<content::RenderProcessHost*> initialized_processes_;

  // The set of ids for extensions that are active in a process that has not
  // been initialized. The activation message will be sent the process is
  // initialized.
  std::map<content::RenderProcessHost*, std::set<ExtensionId>>
      pending_active_extensions_;

  DISALLOW_COPY_AND_ASSIGN(RendererStartupHelper);
};

// Factory for RendererStartupHelpers. Declared here because this header is
// rarely included and it's probably cheaper to put it here than to make the
// compiler generate another object file.
class RendererStartupHelperFactory : public BrowserContextKeyedServiceFactory {
 public:
  static RendererStartupHelper* GetForBrowserContext(
      content::BrowserContext* context);
  static RendererStartupHelperFactory* GetInstance();

 private:
  friend struct base::DefaultSingletonTraits<RendererStartupHelperFactory>;

  RendererStartupHelperFactory();
  ~RendererStartupHelperFactory() override;

  // BrowserContextKeyedServiceFactory implementation:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* profile) const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
  bool ServiceIsCreatedWithBrowserContext() const override;

  DISALLOW_COPY_AND_ASSIGN(RendererStartupHelperFactory);
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_RENDERER_STARTUP_HELPER_H_


text:
package com.thoughtworks.go.config;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import com.thoughtworks.go.domain.ConfigErrors;
import com.thoughtworks.go.domain.PersistentObject;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.StringUtil;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.bouncycastle.crypto.InvalidCipherTextException;

/**
 * @understands an environment variable value that will be passed to a job when it is run
 */
@ConfigTag("variable")
public class EnvironmentVariableConfig extends PersistentObject implements Serializable, Validatable, ParamsAttributeAware, PasswordEncrypter {
    @ConfigAttribute(value = "name", optional = false)
    private String name;

    @ConfigAttribute(value = "secure", optional = true)
    private boolean isSecure = false;

    @ConfigSubtag
    private VariableValueConfig value;

    @ConfigSubtag
    private EncryptedVariableValueConfig encryptedValue;

    private long entityId;
    private String entityType;

    private final ConfigErrors configErrors = new ConfigErrors();

    public static final String NAME = "name";
    public static final String VALUE = "valueForDisplay";
    public static final String SECURE = "secure";
    private GoCipher goCipher = null;
    public static final String ISCHANGED = "isChanged";

    public EnvironmentVariableConfig() {
        this.goCipher = new GoCipher();
    }

    public EnvironmentVariableConfig(String name, String value) {
        this(new GoCipher(), name, value, false);
    }

    public EnvironmentVariableConfig(GoCipher goCipher, String name, String value, boolean isSecure) {
        this(goCipher);
        this.name = name;
        this.isSecure = isSecure;
        setValue(value);
    }

    public EnvironmentVariableConfig(EnvironmentVariableConfig variable) {
        this(variable.goCipher, variable.name, variable.getValue(), variable.isSecure);
    }

    private String encrypt(String value) {
        try {
            return goCipher.encrypt(value);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }

    public EnvironmentVariableConfig(GoCipher goCipher) {
        this.goCipher = goCipher;
    }

    @Override public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        EnvironmentVariableConfig that = (EnvironmentVariableConfig) o;

        if (isSecure != that.isSecure) {
            return false;
        }
        if (configErrors != null ? !configErrors.equals(that.configErrors) : that.configErrors != null) {
            return false;
        }
        if (encryptedValue != null ? !encryptedValue.equals(that.encryptedValue) : that.encryptedValue != null) {
            return false;
        }
        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }
        if (value != null ? !value.equals(that.value) : that.value != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (isSecure ? 1 : 0);
        result = 31 * result + (value != null ? value.hashCode() : 0);
        result = 31 * result + (encryptedValue != null ? encryptedValue.hashCode() : 0);
        result = 31 * result + (configErrors != null ? configErrors.hashCode() : 0);
        return result;
    }

    public String getName() {
        return name;
    }

    void addTo(EnvironmentVariableContext context) {
        context.setProperty(name, getValue(), isSecure());
    }

    public void addToIfExists(EnvironmentVariableContext context) {
        if (context.hasProperty(name)) {
            addTo(context);
        }
    }

    public void validateName(Map<String, EnvironmentVariableConfig> variableConfigMap, ValidationContext validationContext) {
        String currentVariableName = name.toLowerCase();
        String parentDisplayName = validationContext.getParentDisplayName();
        CaseInsensitiveString parentName = getParentNameFrom(validationContext);
        if (StringUtil.isBlank(currentVariableName)) {
            configErrors.add(NAME, String.format("Environment Variable cannot have an empty name for %s '%s'.", parentDisplayName, parentName));
            return;
        }
        EnvironmentVariableConfig configWithSameName = variableConfigMap.get(currentVariableName);
        if (configWithSameName == null) {
            variableConfigMap.put(currentVariableName, this);
        } else {
            configWithSameName.addNameConflictError(parentDisplayName, parentName);
            this.addNameConflictError(parentDisplayName, parentName);
        }
    }

    private void addNameConflictError(String parentDisplayName, Object parentName) {
        configErrors.add(NAME, String.format("Environment Variable name '%s' is not unique for %s '%s'.", this.name, parentDisplayName, parentName));
    }

    private CaseInsensitiveString getParentNameFrom(ValidationContext validationContext) {
        EnvironmentVariableScope parent = (EnvironmentVariableScope) validationContext.getParent();
        return parent.name();
    }

    /**
     * We do this to avoid breaking encapsulation.
     * We should remove this method when we move to Hibernate.
     */
    public Map<String, Object> getSqlCriteria() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("variableName", name);
        map.put("variableValue", getValue());
        map.put("isSecure", isSecure);
        return map;
    }

    public boolean hasName(String variableName) {
        return name.equals(variableName);
    }

    public void validate(ValidationContext validationContext) {
        try {
            getValue();
        } catch (Exception e) {
            errors().add(VALUE, String.format("Encrypted value for variable named '%s' is invalid. This usually happens when the cipher text is modified to have an invalid value.", getName()));
        }
    }

    public ConfigErrors errors() {
        return configErrors;
    }

    public void addError(String fieldName, String message) {
        configErrors.add(fieldName, message);
    }

    public boolean isSecure() {
        return isSecure;
    }

    public boolean isPlain() {
        return !isSecure();
    }

    private void setValue(String value){
        if (isSecure) {
            encryptedValue = new EncryptedVariableValueConfig(encrypt(value));
        } else {
            this.value = new VariableValueConfig(value);
        }
    }

    public String getValue() {
        if (isSecure) {
            try {
                return goCipher.decrypt(encryptedValue.getValue());
            } catch (InvalidCipherTextException e) {
                throw new RuntimeException(String.format("Could not decrypt secure environment variable value for name %s", getName()), e);
            }
        } else {
            return value.getValue();
        }
    }

    public String getDisplayValue(){
        if(isSecure()) return "****";
        return getValue();
    }

    public String getEncryptedValue() {
        return encryptedValue.getValue();
    }

    public void setConfigAttributes(Object attributes) {
        Map attributeMap = (Map) attributes;
        this.name = (String) attributeMap.get(EnvironmentVariableConfig.NAME);
        String value = (String) attributeMap.get(EnvironmentVariableConfig.VALUE);
        if(StringUtil.isBlank(name) && StringUtil.isBlank(value)){
            throw new IllegalArgumentException(String.format("Need not null/empty name & value %s:%s",this.name, value));
        }
        this.isSecure = BooleanUtils.toBoolean((String) attributeMap.get(EnvironmentVariableConfig.SECURE));
        Boolean isChanged = BooleanUtils.toBoolean((String) attributeMap.get(EnvironmentVariableConfig.ISCHANGED));
        if(isSecure){
                this.encryptedValue = isChanged? new EncryptedVariableValueConfig(encrypt(value)) : new EncryptedVariableValueConfig(value);
        }else{
            this.value = new VariableValueConfig(value);
        }
    }

    @PostConstruct
    public void ensureEncrypted() {
        if(isSecure && value != null) {
            encryptedValue = new EncryptedVariableValueConfig(encrypt(value.getValue()));
            value = null;
        }
    }

    public String getValueForDisplay(){
        if(isSecure){
            return getEncryptedValue();
        }
        return value.getValue();
    }

    public void setEntityId(Long entityId) {
        this.entityId = entityId;
    }

    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }
}


text:
<?php

namespace Quotazio\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;

class RegistrationUserPrivate extends BaseController
{
    public function registerAction()
    {
        return $this->container
            ->get('pugx_multi_user.registration_manager')
            ->register('Quotazio\UserBundle\Entity\UserPrivate');
    }
}


text:
package gov.va.med.pharmacy.peps.common.transaction;

import java.util.ArrayList;
import java.util.List;

/**
 * Utility class used to register {@link TransactionSynchronizationListener} instances and to make calls on those listeners.
 *

 * A class which desires to add a {@link TransactionSynchronizationListener} must invoke the
 * {@link #addListener(TransactionSynchronizationListener)} method to register the given listener for the current
 * transaction.
 *

 * A class which has access to the transaction uses the {@link #triggerAfterCommit()}, {@link #triggerAfterRollback()}, and
 * {@link #triggerBeforeCommit()} methods at the appropriate synchronization points. Once all synchronization is complete,
 * the {@link #clear()} method must be invoked.
 */
public class TransactionSynchronizationUtility {
    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger
        .getLogger(TransactionSynchronizationUtility.class);
    private static final ThreadLocal<List<TransactionSynchronizationListener>> SYNCHRONIZATIONS = new ThreadLocal<List<TransactionSynchronizationListener>>();

    /**
     * Set the current thread's List of {@link TransactionSynchronizationListener} to a new ArrayList.
     *

     * Must be called prior to all transaction synchronization to initialize the List of
     * {@link TransactionSynchronizationListener}.
     */
    public static void init() {
        if (!isSynchronizationActive()) {
            SYNCHRONIZATIONS.set(new ArrayList<TransactionSynchronizationListener>());
        }
        else {
            LOG.warn("Transaction synchronization is already active. List of listeners has not been not re-initialized.");
        }
    }

    /**
     * Set the current thread's List of {@link TransactionSynchronizationListener} to null.
     *

     * Must be called after all transaction synchronization is complete on the transaction to clean up ThreadLocal memory
     * references.
     */
    public static void clear() {
        SYNCHRONIZATIONS.set(null);
    }

    /**
     * Synchronization is active if the List of {@link TransactionSynchronizationListener} within the ThreadLocal variable is
     * not null.
     *

     * Should always be true for all transactions as long as {@link #init()} has been called.
     *
     * @return boolean Ture if synchronization is active
     */
    public static boolean isSynchronizationActive() {
        return SYNCHRONIZATIONS.get() != null;
    }

    /**
     * Add a listener for the current thread's transaction. The listener is added to the end of the current list.
     *

     * After calling this method, the {@link TransactionSynchronizationListener} instance provided will be called at the
     * appropriate synchronization points.
     *
     * @param listener {@link TransactionSynchronizationListener} to add
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#add(Object)
     */
    public static boolean addListener(TransactionSynchronizationListener listener) {
        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active. Calling init() now prior to adding the given listener.");
            init();
        }

        return SYNCHRONIZATIONS.get().add(listener);
    }

    /**
     * Insert a listener for the current thread's transaction at the specified index in the list of
     * {@link TransactionSynchronizationListener}.
     *

     * After calling this method, the {@link TransactionSynchronizationListener} instance provided will be called at the
     * appropriate synchronization points.
     *

     * If the given index is less than zero, insert the given {@link TransactionSynchronizationListener} at the beginning of
     * the list. If the given index is greater than the size of the current list add the given
     * {@link TransactionSynchronizationListener} to the end of the list.
     *
     * @param index position within the list of {@link TransactionSynchronizationListener} to insert given listener
     * @param listener {@link TransactionSynchronizationListener} to add
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#add(int, Object)
     * @see List#add(Object)
     */
    public static boolean addListener(int index, TransactionSynchronizationListener listener) {
        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active. Calling init() now prior to adding the given listener.");
            init();
        }

        if (index < 0) {
            SYNCHRONIZATIONS.get().add(0, listener);
        }
        else if (index > SYNCHRONIZATIONS.get().size()) {
            SYNCHRONIZATIONS.get().add(listener);
        }
        else {
            SYNCHRONIZATIONS.get().add(index, listener);
        }

        return true;
    }

    /**
     * Add all of the given listeners for the current thread's transaction. The listeners are added to the end of the current
     * list.
     *

     * After calling this method, the {@link TransactionSynchronizationListener} instance provided will be called at the
     * appropriate synchronization points.
     *
     * @param listeners List of {@link TransactionSynchronizationListener} to add
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#addAll(java.util.Collection)
     */
    public static boolean addListeners(List<TransactionSynchronizationListener> listeners) {
        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active. Calling init() now prior to adding the given listeners.");
            init();
        }

        return SYNCHRONIZATIONS.get().addAll(listeners);
    }

    /**
     * Insert all of the given listeners for the current thread's transaction at the given index within the current list.
     *

     * After calling this method, the {@link TransactionSynchronizationListener} instance provided will be called at the
     * appropriate synchronization points.
     *

     * If the given index is less than zero, insert the given List of {@link TransactionSynchronizationListener} at the
     * beginning of the list. If the given index is greater than the size of the current list add the given List of
     * {@link TransactionSynchronizationListener} to the end of the list.
     *
     * @param index position within the list of {@link TransactionSynchronizationListener} to insert given listeners
     * @param listeners List of {@link TransactionSynchronizationListener} to add
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#addAll(int, java.util.Collection)
     */
    public static boolean addListeners(int index, List<TransactionSynchronizationListener> listeners) {
        boolean successful = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active. Calling init() now prior to adding the given listeners.");
            init();
        }

        if (index < 0) {
            successful = SYNCHRONIZATIONS.get().addAll(0, listeners);
        }
        else if (index > SYNCHRONIZATIONS.get().size()) {
            successful = SYNCHRONIZATIONS.get().addAll(listeners);
        }
        else {
            successful = SYNCHRONIZATIONS.get().addAll(index, listeners);
        }

        return successful;
    }

    /**
     * Remove a listener for the current thread's transaction.
     *
     * @param listener {@link TransactionSynchronizationListener} to remove
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#remove(Object)
     */
    public static boolean removeListener(TransactionSynchronizationListener listener) {
        boolean successful = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot remove given listener!");
        }
        else {
            successful = SYNCHRONIZATIONS.get().remove(listener);
        }

        return successful;
    }

    /**
     * Remove a listener from the current thread's transaction positioned at the given index within the current list.
     *
     * @param index position within the current list to remove
     * @return {@link TransactionSynchronizationListener} that was at the given index
     *
     * @see List#remove(int)
     */
    public static TransactionSynchronizationListener removeListener(int index) {
        TransactionSynchronizationListener listener = null;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot remove given listener!");
        }
        else {
            listener = SYNCHRONIZATIONS.get().remove(index);
        }

        return listener;
    }

    /**
     * Remove the given List of listeners from the current thread's transaction.
     *
     * @param listeners List of {@link TransactionSynchronizationListener} to remove
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#removeAll(java.util.Collection)
     */
    public static boolean removeListeners(List<TransactionSynchronizationListener> listeners) {
        boolean successful = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot remove given listener!");
        }
        else {
            successful = SYNCHRONIZATIONS.get().removeAll(listeners);
        }

        return successful;
    }

    /**
     * Remove all listeners except those in the given List of {@link TransactionSynchronizationListener}.
     *
     * @param listeners List of {@link TransactionSynchronizationListener} to retain
     * @return boolean true if the List of {@link TransactionSynchronizationListener} for the current transaction was changed
     *
     * @see List#retainAll(java.util.Collection)
     */
    public static boolean retainListeners(List<TransactionSynchronizationListener> listeners) {
        boolean successful = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot remove given listener!");
        }
        else {
            successful = SYNCHRONIZATIONS.get().retainAll(listeners);
        }

        return successful;
    }

    /**
     * Returns true if the current list of {@link TransactionSynchronizationListener} for the current thread's transaction
     * includes the given listener.
     *
     * @param listener {@link TransactionSynchronizationListener} to find
     * @return boolean if the given listener is in the current thread transaction's list of listeners
     *
     * @see List#contains(Object)
     */
    public static boolean containsListener(TransactionSynchronizationListener listener) {
        boolean contains = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot test if listener is in the current list!");
        }
        else {
            contains = SYNCHRONIZATIONS.get().contains(listener);
        }

        return contains;
    }

    /**
     * Returns true if the current list of {@link TransactionSynchronizationListener} for the current thread's transaction
     * includes the given listeners.
     *
     * @param listeners List of {@link TransactionSynchronizationListener} to find
     * @return boolean if the given listeners are in the current thread transaction's list of listeners
     *
     * @see List#containsAll(java.util.Collection)
     */
    public static boolean containsListeners(List<TransactionSynchronizationListener> listeners) {
        boolean contains = false;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot test if listeners are in the current list!");
        }
        else {
            contains = SYNCHRONIZATIONS.get().containsAll(listeners);
        }

        return contains;
    }

    /**
     * Return the first index of the given {@link TransactionSynchronizationListener}. If the listener cannot be found,
     * return -1.
     *
     * @param listener {@link TransactionSynchronizationListener} to find
     * @return first index of given listener, or -1 if it cannot be found
     *
     * @see List#indexOf(Object)
     */
    public static int indexOf(TransactionSynchronizationListener listener) {
        int index = -1;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot find given listener!");
        }
        else {
            index = SYNCHRONIZATIONS.get().indexOf(listener);
        }

        return index;
    }

    /**
     * Return the last index of the given {@link TransactionSynchronizationListener}. If the listener cannot be found,
     * return -1.
     *
     * @param listener {@link TransactionSynchronizationListener} to find
     * @return last index of given listener, or -1 if it cannot be found
     *
     * @see List#lastIndexOf(Object)
     */
    public static int lastIndexOf(TransactionSynchronizationListener listener) {
        int index = -1;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot find given listener!");
        }
        else {
            index = SYNCHRONIZATIONS.get().lastIndexOf(listener);
        }

        return index;
    }

    /**
     * Return the {@link TransactionSynchronizationListener} at the given index. If the given index is less than zero or
     * greater than or equal to the current list's size, return null.
     *
     * @param index int index of listener to return
     * @return {@link TransactionSynchronizationListener} if index is in bounds, else null
     */
    public static TransactionSynchronizationListener getListener(int index) {
        TransactionSynchronizationListener listener = null;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot find given listener!");
        }
        else if (index >= 0 && index < SYNCHRONIZATIONS.get().size()) {
            listener = SYNCHRONIZATIONS.get().get(index);
        }

        return listener;
    }

    /**
     * Set the {@link TransactionSynchronizationListener} at the given index (i.e., overwrite the current listener). Return
     * the previous {@link TransactionSynchronizationListener} at that index.
     *

     * If the given index is less than zero, insert the given listener into the first position and return null.
     *

     * If the given index is greater than or equal to the current list's size, add the to the end of the current list and
     * return null.
     *
     * @param index int position in current list to reset
     * @param listener {@link TransactionSynchronizationListener} to set at given index
     * @return previous {@link TransactionSynchronizationListener} value or null
     *
     * @see List#set(int, Object)
     * @see List#add(int, Object)
     * @see List#add(Object)
     */
    public static TransactionSynchronizationListener setListener(int index, TransactionSynchronizationListener listener) {
        TransactionSynchronizationListener previousListener = null;

        if (!isSynchronizationActive()) {
            LOG.warn("Transaction synchronization is not active, so cannot find given listener!");
        }
        else if (index < 0) {
            SYNCHRONIZATIONS.get().add(0, listener);
        }
        else if (index >= SYNCHRONIZATIONS.get().size()) {
            SYNCHRONIZATIONS.get().add(listener);
        }
        else {
            previousListener = SYNCHRONIZATIONS.get().set(index, listener);
        }

        return previousListener;
    }

    /**
     * Return the number of {@link TransactionSynchronizationListener} listening for events on the current transaction.
     *

     * If transaction synchronization is not active the size is zero, but the size may be zero even if synchronization is
     * active and there are no registered listeners.
     *
     * @return int size of List of {@link TransactionSynchronizationListener}
     *
     * @see #isSynchronizationActive()
     */
    public static int size() {
        int size = 0;

        if (isSynchronizationActive()) {
            size = SYNCHRONIZATIONS.get().size();
        }

        return size;
    }

    /**
     * Call all registered {@link TransactionSynchronizationListener#beforeCommit()}.
     */
    public static void triggerBeforeCommit() {
        if (isSynchronizationActive()) {
            for (TransactionSynchronizationListener listener : SYNCHRONIZATIONS.get()) {
                listener.beforeCommit();
            }
        }
        else {
            LOG.error("Unable to invoke beforeCommit() methods because the synchronizations have not been initialized."
                + " Please be sure the TransactionSynchronizationUtility.init() method has been called");
        }
    }

    /**
     * Call all registered {@link TransactionSynchronizationListener#afterCommit()}.
     */
    public static void triggerAfterCommit() {
        if (isSynchronizationActive()) {
            for (TransactionSynchronizationListener listener : SYNCHRONIZATIONS.get()) {
                listener.afterCommit();
            }
        }
        else {
            LOG.error("Unable to invoke afterCommit() methods because the synchronizations have not been initialized."
                + " Please be sure the TransactionSynchronizationUtility.init() method has been called");
        }
    }

    /**
     * Call all registered {@link TransactionSynchronizationListener#afterRollback()}.
     */
    public static void triggerAfterRollback() {
        if (isSynchronizationActive()) {
            for (TransactionSynchronizationListener listener : SYNCHRONIZATIONS.get()) {
                listener.afterRollback();
            }
        }
        else {
            LOG.error("Unable to invoke afterRollback() methods because the synchronizations have not been initialized."
                + " Please be sure the TransactionSynchronizationUtility.init() method has been called");
        }
    }

    /**
     * Cannot instantiate.
     */
    private TransactionSynchronizationUtility() {
        super();
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
    using StackFrameNodeOrToken = CodeAnalysis.EmbeddedLanguages.Common.EmbeddedSyntaxNodeOrToken<StackFrameKind, StackFrameNode>;
    using StackFrameToken = CodeAnalysis.EmbeddedLanguages.Common.EmbeddedSyntaxToken<StackFrameKind>;
    using StackFrameTrivia = CodeAnalysis.EmbeddedLanguages.Common.EmbeddedSyntaxTrivia<StackFrameKind>;

    internal static class StackFrameUtils
    {
        public static void AssertEqual(StackFrameNodeOrToken expected, StackFrameNodeOrToken actual)
        {
            Assert.Equal(expected.IsNode, actual.IsNode);
            if (expected.IsNode)
            {
                AssertEqual(expected.Node, actual.Node);
            }
            else
            {
                AssertEqual(expected.Token, actual.Token);
            }
        }

        public static void AssertEqual(StackFrameNode? expected, StackFrameNode? actual)
        {
            if (expected is null)
            {
                Assert.Null(actual);
                return;
            }

            AssertEx.NotNull(actual);

            Assert.Equal(expected.Kind, actual.Kind);
            Assert.True(expected.ChildCount == actual.ChildCount, PrintChildDifference(expected, actual));

            for (var i = 0; i < expected.ChildCount; i++)
            {
                AssertEqual(expected.ChildAt(i), actual.ChildAt(i));
            }

            static string PrintChildDifference(StackFrameNode expected, StackFrameNode actual)
            {
                var sb = new StringBuilder();
                sb.Append("Expected: ");
                Print(expected, sb);
                sb.AppendLine();

                sb.Append("Actual: ");
                Print(actual, sb);

                return sb.ToString();
            }
        }

        public static void Print(StackFrameNode node, StringBuilder sb)
        {
            foreach (var child in node)
            {
                if (child.IsNode)
                {
                    Print(child.Node, sb);
                }
                else
                {
                    if (!child.Token.LeadingTrivia.IsDefaultOrEmpty)
                    {
                        Print(child.Token.LeadingTrivia, sb);
                    }

                    sb.Append(child.Token.VirtualChars.CreateString());

                    if (!child.Token.TrailingTrivia.IsDefaultOrEmpty)
                    {
                        Print(child.Token.TrailingTrivia, sb);
                    }
                }
            }
        }

        public static void Print(ImmutableArray<StackFrameTrivia> triviaArray, StringBuilder sb)
        {
            if (triviaArray.IsDefault)
            {
                sb.Append("<default>");
                return;
            }

            if (triviaArray.IsEmpty)
            {
                sb.Append("<empty>");
                return;
            }

            foreach (var trivia in triviaArray)
            {
                sb.Append(trivia.VirtualChars.CreateString());
            }
        }

        public static void AssertEqual(StackFrameToken expected, StackFrameToken actual)
        {
            Assert.Equal(expected.Kind, actual.Kind);
            Assert.Equal(expected.IsMissing, actual.IsMissing);
            Assert.Equal(expected.VirtualChars.CreateString(), actual.VirtualChars.CreateString());

            AssertEqual(expected.LeadingTrivia, actual.LeadingTrivia, expected);
            AssertEqual(expected.TrailingTrivia, actual.TrailingTrivia, expected);
        }

        public static void AssertEqual(ImmutableArray<StackFrameTrivia> expected, ImmutableArray<StackFrameTrivia> actual, StackFrameToken token)
        {
            var diffMessage = PrintDiff();

            if (expected.IsDefault)
            {
                Assert.True(actual.IsDefault, diffMessage);
                return;
            }

            Assert.False(actual.IsDefault, diffMessage);
            Assert.True(expected.Length == actual.Length, diffMessage);

            for (var i = 0; i < expected.Length; i++)
            {
                AssertEqual(expected[i], actual[i]);
            }

            string PrintDiff()
            {
                var sb = new StringBuilder();
                sb.AppendLine($"Trivia is different on {token.Kind}");
                sb.Append("Expected: ");

                if (!expected.IsDefaultOrEmpty)
                {
                    sb.Append('[');
                }

                Print(expected, sb);

                if (expected.IsDefaultOrEmpty)
                {
                    sb.AppendLine();
                }
                else
                {
                    sb.AppendLine("]");
                }

                sb.Append("Actual: ");

                if (!actual.IsDefaultOrEmpty)
                {
                    sb.Append('[');
                }

                Print(actual, sb);

                if (!actual.IsDefaultOrEmpty)
                {
                    sb.Append(']');
                }

                return sb.ToString();
            }
        }

        public static void AssertEqual(StackFrameTrivia expected, StackFrameTrivia actual)
        {
            Assert.Equal(expected.Kind, actual.Kind);
            Assert.Equal(expected.VirtualChars.CreateString(), actual.VirtualChars.CreateString());
        }

        public static IEnumerable<CodeAnalysis.EmbeddedLanguages.VirtualChars.VirtualCharSequence> Enumerate(StackFrameToken token)
        {
            foreach (var trivia in token.LeadingTrivia)
            {
                yield return trivia.VirtualChars;
            }

            yield return token.VirtualChars;

            foreach (var trivia in token.TrailingTrivia)
            {
                yield return trivia.VirtualChars;
            }
        }

        public static IEnumerable<CodeAnalysis.EmbeddedLanguages.VirtualChars.VirtualCharSequence> Enumerate(StackFrameNode node)
        {
            foreach (var nodeOrToken in node)
            {
                if (nodeOrToken.IsNode)
                {
                    foreach (var charSequence in Enumerate(nodeOrToken.Node))
                    {
                        yield return charSequence;
                    }
                }
                else if (nodeOrToken.Token.Kind != StackFrameKind.None)
                {
                    foreach (var charSequence in Enumerate(nodeOrToken.Token))
                    {
                        yield return charSequence;
                    }
                }
                else
                {
                    // If we encounter a None token make sure it has default values
                    Assert.True(nodeOrToken.Token.IsMissing);
                    Assert.True(nodeOrToken.Token.LeadingTrivia.IsDefault);
                    Assert.True(nodeOrToken.Token.TrailingTrivia.IsDefault);
                    Assert.Null(nodeOrToken.Token.Value);
                    Assert.True(nodeOrToken.Token.VirtualChars.IsDefault);
                }
            }
        }
    }
}


text:
<!--
Description: Creates the layout pattern of the home page, which should include the header that controls naviagation and dynamically loads the page layout (billboard, buttons, etc).

Requires: none
Param: none
Returns: page of the given route (i.e. /admin/user)
 !-->

<template name="HomeLayout">
    {{> Header}}
    <main class="main-layout">
        {{> Template.dynamic template=main}}
    </main>
</template>


text:
import copy
from datetime import datetime
import json

import pytest
import mock
from six import StringIO

import analyzere
from analyzere import MissingIdError
from analyzere.resources import Layer, OptimizationView, Candidate
from analyzere.base_resources import (
    AnalyzeReObject,
    DataResource,
    EmbeddedResource,
    MetricsResource,
    Reference,
    Resource,
    convert_to_analyzere_object,
    NestedResource)
from analyzere.errors import RetryAfter
import uuid

class SetBaseUrl(object):
    def setup_method(self, _):
        analyzere.base_url = 'https://api'

    def teardown_method(self, _):
        analyzere.base_url = ''

class SequentialStreamWrapper(object):
    """
    Helper class to turn any file-like object into a stream from which can only
    be sequentially read. That is, this object does not support ``seek`` and
    ``tell`` operations for random access and stream positioning.
    """
    def __init__(self, file_obj):
        self.file_obj = file_obj

    def read(self, size=None):
        if size is None:
            return self.file_obj.read()
        else:
            return self.file_obj.read(size)

class TestReferences(SetBaseUrl):
    def test_known_resource(self, reqmock):
        reqmock.get('https://api/layers/abc123', status_code=200,
                    text='{"id": "abc123", "foo": "bar"}')
        href = 'https://api/layers/abc123'
        r = Reference(href)

        # Test laziness
        assert r._id == 'abc123'
        assert reqmock.call_count == 0

        # Force evaluation
        assert r.id == 'abc123'
        assert r.foo == 'bar'
        assert reqmock.call_count == 1
        assert isinstance(r, Layer)

    def test_unknown_resource(self, reqmock):
        reqmock.get('https://api/foo/abc123', status_code=200,
                    text='{"id": "abc123", "foo": "bar"}')
        href = 'https://api/foo/abc123'
        r = Reference(href)
        assert r._id == 'abc123'
        assert r.foo == 'bar'
        assert isinstance(r, Resource)

    def test_copy_unresolved(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123"}')
        a = Reference('https://api/foos/abc123')
        b = copy.copy(a)
        assert b._id == 'abc123'
        assert reqmock.call_count == 0

    def test_copy_resolved(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "list": [1, 2, 3]}')
        a = Reference('https://api/foos/abc123')
        assert a.list == [1, 2, 3]  # Forces evaluation
        b = copy.copy(a)
        assert b.list is a.list  # Assert copy was shallow
        assert reqmock.call_count == 1

    def test_deepcopy_unresolved(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123"}')
        a = Reference('https://api/foos/abc123')
        b = copy.deepcopy(a)
        assert b._id == 'abc123'
        assert reqmock.call_count == 0

    def test_deepcopy_resolved(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "list": [1, 2, 3]}')
        a = Reference('https://api/foos/abc123')
        assert a.list == [1, 2, 3]  # Forces evaluation
        b = copy.deepcopy(a)
        assert b.id == 'abc123'
        assert b.list is not a.list  # Assert copy was not shallow
        assert reqmock.call_count == 1

class TestAnalyzeReObject:
    def test_initialize_from_kwargs(self):
        a = AnalyzeReObject(_type='sometype', foo='bar', baz='qux')
        assert a.type == 'sometype'
        assert a.foo == 'bar'
        assert a.baz == 'qux'

    def test_update(self):
        a = AnalyzeReObject(foo='bar', baz='qux')
        b = AnalyzeReObject(foo='fizz')
        a.update(b)
        assert a.foo == 'fizz'
        assert a.baz == 'qux'

    def test_clear(self):
        a = AnalyzeReObject(foo='bar', baz='qux')
        a.clear()
        assert not hasattr(a, 'foo')
        assert not hasattr(a, 'baz')

    def test_str(self):
        a = AnalyzeReObject(foo='bar', baz='qux')
        assert str(a) == '{\n  "baz": "qux",\n  "foo": "bar"\n}'

    def test_repr(self):
        a = AnalyzeReObject(foo='bar', baz='qux')
        assert (repr(a) == '<AnalyzeReObject at %s> JSON: {\n  '
                           '"baz": "qux",\n  "foo": "bar"\n}' % hex(id(a)))

    def test_hash(self):
        common_id = str(uuid.uuid4())
        different_id = str(uuid.uuid4())

        compare_object = AnalyzeReObject(id=common_id, foo='bar', baz='qux')
        no_id_object = AnalyzeReObject(foo='bar', baz='qux')
        different_id_object = AnalyzeReObject(id=different_id, foo='bar',
                                              baz='qux')
        same_id_object = AnalyzeReObject(id=common_id, foo='bar', baz='qux')
        invalid_uuid_object = AnalyzeReObject(id='not-a-uuid', foo='bar',
                                              baz='qux')

        assert compare_object.__hash__() != no_id_object.__hash__()
        assert compare_object.__hash__() != different_id_object.__hash__()
        assert compare_object.__hash__() == same_id_object.__hash__()
        assert compare_object.__hash__() != invalid_uuid_object.__hash__()

class TestAnalyzeReObjectToDict:
    def test_simple(self):
        d = datetime.today()
        s = AnalyzeReObject(
            num=1,
            str='foo',
            date=d,
            list=[1, 2, 3],
            dict={'foo': 'bar'},
            ref=Reference('https://api/layers/abc123'),
            res=Resource(id='abc123', foo='bar')
        ).to_dict()

        assert s == {
            'num': 1,
            'str': 'foo',
            'date': d,
            'list': [1, 2, 3],
            'dict': {'foo': 'bar'},
            'ref': {'ref_id': 'abc123'},
            'res': {'ref_id': 'abc123'}
        }

    def test_nested(self):
        d = datetime.today()
        num = AnalyzeReObject(num=1)
        str_ = AnalyzeReObject(str='foo')
        date = AnalyzeReObject(date=d)
        list_ = AnalyzeReObject(list=[1, 2, 3])
        dict_ = AnalyzeReObject(dict={'foo': 'bar'})
        ref = AnalyzeReObject(ref=Reference('https://api/layers/abc123'))
        res = AnalyzeReObject(res=Resource(id='abc123', foo='bar'))
        s = AnalyzeReObject(num=num, str=str_, date=date, list=list_,
                            dict=dict_, ref=ref, res=res).to_dict()
        assert s == {
            'num': {'num': 1},
            'str': {'str': 'foo'},
            'date': {'date': d},
            'list': {'list': [1, 2, 3]},
            'dict': {'dict': {'foo': 'bar'}},
            'ref': {'ref': {'ref_id': 'abc123'}},
            'res': {'res': {'ref_id': 'abc123'}}
        }

    def test_id_not_stripped(self):
        s = AnalyzeReObject(id='abc123').to_dict()
        assert 'id' in s

    def test_private_stripped(self):
        s = AnalyzeReObject(_foo='bar').to_dict()
        assert '_foo' not in s

    def test_type_renamed(self):
        s = AnalyzeReObject(type='bar').to_dict()
        assert 'type' not in s
        assert s['_type'] == 'bar'

    def test_resources_without_id_inlined(self):
        s = AnalyzeReObject(res=Resource(foo='bar')).to_dict()
        assert 'foo' in s['res']
        assert s['res']['foo'] == 'bar'
        assert 'ref_id' not in s['res']

class TestConvertToAnalyzeReObject:
    def test_simple(self):
        d = datetime.today()
        resp = {
            'num': 1,
            'str': 'foo',
            'date': d,
            'list': [1, 2, 3],
            'dict': {'foo': 'bar'},
            'ref': {'href': 'https://api/layers/abc123'},
        }

        o = convert_to_analyzere_object(resp)
        assert o.num == 1
        assert o.str == 'foo'
        assert o.date == d
        assert o.list == [1, 2, 3]
        assert o.dict == EmbeddedResource(foo='bar')
        assert type(o.dict) == EmbeddedResource

        # Shallow comparison for reference so it doesn't evaluate
        assert type(o.ref) == Reference
        assert o.ref._id == 'abc123'

    def test_nested(self):
        d = datetime.today()
        resp = {
            'num': {'num': 1},
            'str': {'str': 'foo'},
            'date': {'date': d},
            'list': {'list': [1, 2, 3]},
            'dict': {'dict': {'foo': 'bar'}},
            'ref': {'ref': {'href': 'https://api/layers/abc123'}}
        }
        o = convert_to_analyzere_object(resp)
        assert o.num.num == 1
        assert o.str.str == 'foo'
        assert o.date.date == d
        assert o.list.list == [1, 2, 3]
        assert o.dict.dict == EmbeddedResource(foo='bar')
        assert type(o.ref.ref) == Reference
        assert o.ref.ref._id == 'abc123'

    def test_object_type(self):
        o = convert_to_analyzere_object({'id': 'abc123'})
        assert type(o) == EmbeddedResource

        o = convert_to_analyzere_object({'id': 'abc123'}, cls=Resource)
        assert type(o) == Resource

        o = convert_to_analyzere_object({'foo': 'bar'}, cls=Resource)
        assert type(o) == EmbeddedResource

        resp = {'id': 'abc123', 'embedded': {'foo': 'bar'}}
        o = convert_to_analyzere_object(resp, cls=Resource)
        assert type(o.embedded) == EmbeddedResource

        resp = {'id': 'abc123', 'embedded': {'id': 'xyz456', 'foo': 'bar'}}
        o = convert_to_analyzere_object(resp, cls=Resource)
        assert type(o) == Resource
        assert type(o.embedded) == EmbeddedResource

    def test_private_not_stripped(self):
        # TODO: Maybe underscore prefixed attributes from the server
        # (besides _type) should be ignored?
        o = convert_to_analyzere_object({'_private': 'foo'})
        assert o._private == 'foo'

    def test_type_renamed(self):
        resp = {'_type': {'foo'}}
        o = convert_to_analyzere_object(resp)
        assert not hasattr(o, '_type')
        assert hasattr(o, 'type')

    def test_collection(self):
        resp = {
            'items': [{'id': 'abc123'}, {'id': 'xyz456'}],
            'meta': {
                'limit': 0,
                'offset': 0,
                'total_count': 2,
                'future_attr': 'foo'
            }
        }
        o = convert_to_analyzere_object(resp, Resource)
        assert len(o) == 2
        assert o.meta.limit == 0
        assert o.meta.offset == 0
        assert o.meta.total_count == 2
        assert o.meta.future_attr == 'foo'
        assert type(o[0]) == Resource

        # TODO: When no class is provided, the items should probably be
        # AnalyzeReObjects
        o = convert_to_analyzere_object(resp)
        assert type(o[0]) == EmbeddedResource

    def test_non_embedded_resource_requires_id(self):
        # without an ID, an EmbeddedResource with no specific type is the expected conversion
        # if the class passed was not a subclass of EmbeddedResource
        class SomeResource(Resource):
            pass

        response_dict = {}
        o = convert_to_analyzere_object(response_dict, SomeResource)
        assert type(o) == EmbeddedResource

    def test_nested_resource_does_not_require_id(self):
        class SomeEmbeddedResource(NestedResource):
            pass

        response_dict = {}
        o = convert_to_analyzere_object(response_dict, SomeEmbeddedResource)
        assert type(o) == SomeEmbeddedResource

class Foo(Resource):
    pass

class TestResource(SetBaseUrl):
    def test_retrieve(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123"}')
        f = Foo.retrieve('abc123')
        assert f == Foo(id='abc123')

    def test_list(self, reqmock):
        body = json.dumps({
            'items': [{'id': 'abc123'}, {'id': 'xyz456'}],
            'meta': {
                'limit': 0,
                'offset': 0,
                'total_count': 2,
            }
        })
        reqmock.get('https://api/foos/', status_code=200, text=body)
        f = Foo.list()
        assert len(f) == 2

        # With query params
        Foo.list(foo='bar')
        assert len(reqmock.last_request.qs) == 1
        assert reqmock.last_request.qs['foo'] == ['bar']

        Foo.list(quux='baz,qux')
        assert len(reqmock.last_request.qs) == 1
        assert reqmock.last_request.qs['quux'] == ['baz,qux']

        Foo.list(foo='bar', quux='baz,qux')
        assert len(reqmock.last_request.qs) == 2
        assert reqmock.last_request.qs['foo'] == ['bar']
        assert reqmock.last_request.qs['quux'] == ['baz,qux']

    def test_save_new(self, reqmock):
        reqmock.post('https://api/foos/', status_code=200,
                     text='{"id": "abc123", "server_generated": "foo"}')
        f = Foo(foo='bar')

        assert not hasattr(f, 'server_generated')
        f.save()
        assert reqmock.call_count == 1
        assert not hasattr(f, 'foo')
        assert f.server_generated == 'foo'

    def test_update(self, reqmock):
        reqmock.put('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "server_generated": "foo"}')
        f = Foo(id='abc123', foo='bar')
        f.save()
        assert reqmock.call_count == 1
        assert f.server_generated == 'foo'

    def test_reload(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "foo": "baz"}')

        f = Foo(foo='bar', throwaway='gone')
        with pytest.raises(MissingIdError):
            f.reload()

        f.id = 'abc123'
        f.reload()
        assert f.foo == 'baz'
        assert not hasattr(f, 'throwaway')

    def test_reference_save(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "server_generated": "foo"}')
        r = Reference('https://api/foos/abc123')
        assert r.id == 'abc123'
        assert r._id == 'abc123'

        # Check to ensure Class attribute is not touched.
        assert Reference._id is None
        assert Reference._href is None
        assert Reference._resolved is False

        # check that _id and _href are not updated when simply calling an
        # attribute.
        reqmock.put('https://api/foos/def123', status_code=200,
                    text='{"id": "def123", "server_generated": "bar"}')
        r.id = 'def123'
        r.server_generated
        assert r._id == 'abc123'
        assert Reference._id is None
        assert Reference._href is None
        assert Reference._resolved is False

        r.save()
        assert r.id == r._id
        assert r._href == 'https://api/foos/def123'
        assert Reference._id is None
        assert Reference._href is None
        assert Reference._resolved is False

    def test_reference_retrieve(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "server_generated": "foo"}')
        r = Reference('https://api/foos/abc123')
        assert r.id == 'abc123'
        assert r._id == 'abc123'

        # The retrieve method should not result in a change to the _id or _href
        # attributes
        reqmock.get('https://api/foos/def123', status_code=200,
                    text='{"id": "def123", "server_generated": "bar"}')
        r.retrieve('def123')
        assert r._id == 'abc123'
        assert r._href == 'https://api/foos/abc123'

    def test_reference_reload(self, reqmock):
        reqmock.get('https://api/foos/abc123', status_code=200,
                    text='{"id": "abc123", "server_generated": "foo"}')
        r = Reference('https://api/foos/abc123')
        assert r.id == 'abc123'
        assert r._id == 'abc123'

        # The retrieve method should not result in a change to the _id or _href
        # attributes
        reqmock.get('https://api/foos/def123', status_code=200,
                    text='{"id": "def123", "server_generated": "bar"}')
        r.id = 'def123'
        r.reload()
        assert r._id == 'def123'
        assert r._href == 'https://api/foos/def123'
        assert Reference._id is None
        assert Reference._href is None
        assert Reference._resolved is False

class Bar(DataResource):
    pass

class TestDataResource(SetBaseUrl):

    def test_download(self, reqmock):
        reqmock.get('https://api/bars/abc123/data', status_code=200,
                    text='data')
        f = Bar(id='abc123')
        assert f.download_data() == b'data'

    def test_upload_data(self, mock_bar_request):
        reqmock = mock_bar_request

        f = Bar(id='abc123')
        f.upload_data('data')
        assert reqmock.call_count == 4

        # Assert initiates session
        req = reqmock.request_history[0]
        assert req.headers['Entity-Length'] == '4'
        assert req.text is None

        # Assert uploads first chunk
        req = reqmock.request_history[1]
        assert req.headers['Content-Type'] == 'application/offset+octet-stream'
        assert req.headers['Content-Length'] == '4'
        assert req.headers['Offset'] == '0'
        assert req.text == 'data'

        # Assert session committed
        req = reqmock.request_history[2]
        assert req.text is None

        # Assert upload status checked
        req = reqmock.request_history[3]
        assert req.text is None

    def test_upload_data_file(self, mock_bar_request):
        reqmock = mock_bar_request

        f = Bar(id='abc123')

        # Create file object
        file_obj = StringIO('data')

        f.upload_data(file_obj)
        assert reqmock.call_count == 4

        # Assert initiates session
        req = reqmock.request_history[0]
        assert req.headers['Entity-Length'] == '4'
        assert req.text is None

        # Assert uploads first chunk
        req = reqmock.request_history[1]
        assert req.headers['Content-Type'] == 'application/offset+octet-stream'
        assert req.headers['Content-Length'] == '4'
        assert req.headers['Offset'] == '0'
        assert req.text == 'data'

        # Assert session committed
        req = reqmock.request_history[2]
        assert req.text is None

        # Assert upload status checked
        req = reqmock.request_history[3]
        assert req.text is None

    def test_upload_data_stream(self, mock_bar_request):
        reqmock = mock_bar_request

        f = Bar(id='abc123')

        # Create file object
        file_obj = SequentialStreamWrapper(StringIO('data'))

        f.upload_data(file_obj)
        assert reqmock.call_count == 4

        # Assert initiates session
        req = reqmock.request_history[0]
        assert 'Entity-Length' not in req.headers
        assert req.text is None

        # Assert uploads first chunk
        req = reqmock.request_history[1]
        assert req.headers['Content-Type'] == 'application/offset+octet-stream'
        assert req.headers['Content-Length'] == '4'
        assert req.headers['Offset'] == '0'
        assert req.text == 'data'

        # Assert session committed
        req = reqmock.request_history[2]
        assert req.text is None

        # Assert upload status checked
        req = reqmock.request_history[3]
        assert req.text is None

    def test_upload_data_chunking(self, mock_bar_request):
        reqmock = mock_bar_request

        f = Bar(id='abc123')

        # Create file object
        file_obj = StringIO('data')

        # Set chunking to 3 bytes per chunk
        # Upload file
        f.upload_data(file_obj, chunk_size=3)

        assert reqmock.call_count == 5

        # Assert initiates session
        req = reqmock.request_history[0]
        assert req.headers['Entity-Length'] == '4'
        assert req.text is None

        # Assert uploads first chunk
        req = reqmock.request_history[1]
        assert req.headers['Content-Type'] == 'application/offset+octet-stream'
        assert req.headers['Content-Length'] == '3'
        assert req.headers['Offset'] == '0'
        assert req.text == 'dat'

        # Assert uploads second chunk
        req = reqmock.request_history[2]
        assert req.headers['Content-Type'] == 'application/offset+octet-stream'
        assert req.headers['Content-Length'] == '1'
        assert req.headers['Offset'] == '3'
        assert req.text == 'a'

        # Assert session committed
        req = reqmock.request_history[3]
        assert req.text is None

        # Assert upload status checked
        req = reqmock.request_history[4]
        assert req.text is None

    def test_upload_data_chunking_poll_interval(self, mock_bar_request):
        f = Bar(id='abc123')

        # Create file object
        file_obj = StringIO('data')

        # call with poll_interval
        f.upload_data(file_obj, poll_interval=1.0)

    def test_upload_data_chunking_bad_callbacks(self, mock_bar_request):
        f = Bar(id='abc123')

        # Create file object
        file_obj = StringIO('data')

        # call with bad callbacks
        with pytest.raises(Exception) as e:
            f.upload_data(file_obj, chunk_size=1,
                          upload_callback='callback')
        assert str(e.value) == 'provided upload_callback is not callable'

        with pytest.raises(Exception) as e:
            f.upload_data(file_obj, chunk_size=1,
                          commit_callback='callback')
        assert str(e.value) == 'provided commit_callback is not callable'

    def test_upload_data_chunking_callbacks(self, mock_bar_request):
        reqmock = mock_bar_request
        upload_callback = mock.Mock()
        commit_callback = mock.Mock()

        f = Bar(id='abc123')

        # Create file object of 10 bytes
        file_obj = StringIO('1234567890')

        # Set chunking to 1 byte per chunk == 10 chunks
        # Upload file
        f.upload_data(file_obj, chunk_size=1,
                      upload_callback=upload_callback,
                      commit_callback=commit_callback)

        assert reqmock.call_count == 13
        assert upload_callback.call_count == 11
        # we expect calls for: 0.0, 10.0 ... 90.0,100.0
        expected_calls = [p * 10.0 for p in range(11)]
        actual_calls = [c[0][0] for c in upload_callback.call_args_list]
        assert expected_calls == actual_calls

        assert commit_callback.call_count == 1
        # we only expect a single call: 100.0
        expected_calls = [100.0]
        actual_calls = [c[0][0] for c in commit_callback.call_args_list]
        assert expected_calls == actual_calls

    def test_delete_data(self, reqmock):
        reqmock.delete('https://api/bars/abc123/data', status_code=201)
        Bar(id='abc123').delete_data()
        assert reqmock.call_count == 1

class FooView(MetricsResource):
    pass

class TestMetricsResource(SetBaseUrl):
    def test_tail_metrics(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/tail_metrics/1.0',
                    status_code=200, text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.tail_metrics(1.0).num == 1.0

        reqmock.get('https://api/foo_views/abc123/tail_metrics/0.5,1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        tm = f.tail_metrics([0.5, 1.0])
        assert len(tm) == 2
        assert tm[0].num == 1.0
        assert tm[1].num == 2.0

    def test_window_metrics(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/window_metrics/0.0_1.0',
                    status_code=200, text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.window_metrics((0.0, 1.0)).num == 1.0

        reqmock.get('https://api/foo_views/abc123/window_metrics/0.0_0.5,0.0_1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        wm = f.window_metrics([(0.0, 0.5), (0.0, 1.0)])
        assert len(wm) == 2
        assert wm[0].num == 1.0
        assert wm[1].num == 2.0

    def test_co_metrics(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/co_metrics/1.0',
                    status_code=200, text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.co_metrics(1.0).num == 1.0

        reqmock.get('https://api/foo_views/abc123/co_metrics/0.5,1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        tm = f.co_metrics([0.5, 1.0])
        assert len(tm) == 2
        assert tm[0].num == 1.0
        assert tm[1].num == 2.0

    def test_window_co_metrics(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/window_co_metrics/0.0_1.0',
                    status_code=200, text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.window_co_metrics((0.0, 1.0)).num == 1.0

        reqmock.get('https://api/foo_views/abc123/window_co_metrics/0.0_0.5,0.0_1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        wm = f.window_co_metrics([(0.0, 0.5), (0.0, 1.0)])
        assert len(wm) == 2
        assert wm[0].num == 1.0
        assert wm[1].num == 2.0

    def test_el(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/el', status_code=200,
                    text='1.0')
        f = FooView(id='abc123')
        assert f.el() == 1.0

    def test_ep(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/exceedance_probabilities/1',
                    status_code=200, text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.ep(1).num == 1.0

        reqmock.get('https://api/foo_views/abc123/exceedance_probabilities/'
                    '100,200', status_code=200,
                    text='[{"num": 1.0}, {"num": 2.0}]')
        tm = f.ep([100, 200])
        assert len(tm) == 2
        assert tm[0].num == 1.0
        assert tm[1].num == 2.0

    def test_ep_auto_retry_true(self, reqmock):
        responses = [
            {'status_code': 503, 'headers': {'Retry-After': '0.01'}},
            {'status_code': 200, 'text': '{"num": 1.0}'}
        ]
        reqmock.get('https://api/foo_views/abc123/exceedance_probabilities/1',
                    responses)
        f = FooView(id='abc123')
        with mock.patch('time.sleep') as sleep:
            assert f.ep(1, auto_retry=True).num == 1.0
        sleep.assert_called_once_with(0.01)

    def test_ep_auto_retry_false(self, reqmock):
        responses = [
            {'status_code': 503, 'headers': {'Retry-After': '0.01'}},
            {'status_code': 200, 'text': '{"num": 1.0}'}
        ]
        reqmock.get('https://api/foo_views/abc123/exceedance_probabilities/1',
                    responses)
        f = FooView(id='abc123')
        with pytest.raises(RetryAfter):
            f.ep(1, auto_retry=False).num
        assert f.ep(1, auto_retry=False).num == 1.0

    def test_tvar(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/tvar/1.0', status_code=200,
                    text='1.0')
        f = FooView(id='abc123')
        assert f.tvar(1.0) == 1.0

        reqmock.get('https://api/foo_views/abc123/tvar/0.5,1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        tm = f.tvar([0.5, 1.0])
        assert len(tm) == 2
        assert tm[0].num == 1.0
        assert tm[1].num == 2.0

    def test_window_var(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/window_var/0.0_1.0', status_code=200,
                    text='{"num": 1.0}')
        f = FooView(id='abc123')
        assert f.window_var((0.0, 1.0)).num == 1.0

        reqmock.get('https://api/foo_views/abc123/window_var/0.0_0.5,0.0_1.0',
                    status_code=200, text='[{"num": 1.0}, {"num": 2.0}]')
        wm = f.window_var([(0.0, 0.5), (0.0, 1.0)])
        assert len(wm) == 2
        assert wm[0].num == 1.0
        assert wm[1].num == 2.0

    def test_download_ylt(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/ylt', status_code=200,
                    text='ylt-data')
        f = FooView(id='abc123')
        assert f.download_ylt() == b'ylt-data'

    def test_download_yelt(self, reqmock):
        reqmock.get('https://api/foo_views/abc123/yelt', status_code=200,
                    text='yelt-data')
        f = FooView(id='abc123')
        assert f.download_yelt() == b'yelt-data'

    def test_download_yelt_auto_retry_true(self, reqmock):
        responses = [
            {'status_code': 503, 'headers': {'Retry-After': '0.01'}},
            {'status_code': 200, 'text': 'yelt-data'}
        ]
        reqmock.get('https://api/foo_views/abc123/yelt', responses)
        f = FooView(id='abc123')
        with mock.patch('time.sleep') as sleep:
            assert f.download_yelt() == b'yelt-data'
        sleep.assert_called_once_with(0.01)

    def test_download_yelt_auto_retry_false(self, reqmock):
        responses = [
            {'status_code': 503, 'headers': {'Retry-After': '0.01'}},
            {'status_code': 200, 'text': 'yelt-data'}
        ]
        reqmock.get('https://api/foo_views/abc123/yelt', responses)
        f = FooView(id='abc123')
        with pytest.raises(RetryAfter):
            f.download_yelt(auto_retry=False)
        assert f.download_yelt(auto_retry=False) == b'yelt-data'

    def test_unknown_resource_equality(self, reqmock):
        reqmock.get('https://api/foo/abc123', status_code=200,
                    text='{"id": "abc123", "foo": "bar"}')
        href = 'https://api/foo/abc123'
        r1 = Reference(href)
        r2 = Reference(href)
        assert r1 == r2

    def test_back_allocation(self, reqmock):
        reqmock.get(
            'https://api/foo_views/abc123/back_allocations?source_id=321cba',
            status_code=200,
            text='"response_object"'
        )
        f = FooView(id='abc123')
        response = f.back_allocation("321cba")
        assert response == "response_object"

    # TODO: Add tests for id: None

class TestOptimizationResource(SetBaseUrl):
    def test_retrieve(self, reqmock):
        reqmock.get('https://api/optimization_views/abc123',
                    status_code=200,
                    text='{"num": 1.0}')
        f = OptimizationView.retrieve('abc123')
        assert f.num == 1.0

    def test_result(self, reqmock):
        reqmock.get('https://api/optimization_views/abc123/result',
                    status_code=200,
                    text='{"num": 1.0}')
        f = OptimizationView(id='abc123').result()
        assert f.num == 1.0

    def test_candidates(self, reqmock):
        candidates_response = ('{'
                               ' "items": [{"foo": "bar"}],'
                               ' "meta": {"total_count": 1,"limit": 100,"offset": 0}'
                               '}')
        reqmock.get('https://api/optimization_views/abc123/candidates',
                    status_code=200,
                    text=candidates_response)
        r = OptimizationView(id='abc123').candidates()
        assert isinstance(r, list)
        assert len(r) == 1
        assert type(r[0]) == Candidate
        assert r[0].foo == 'bar'

    def test_candidate_parameters(self, reqmock):
        candidate_parameters_response = ('{'
                                         ' "items": [{"foo": "bar"}],'
                                         ' "meta": {"total_count": 1,"limit": 100,"offset": 0}'
                                         '}')
        reqmock.get('https://api/optimization_views/abc123/candidate_parameters',
                    status_code=200,
                    text=candidate_parameters_response)
        r = OptimizationView(id='abc123').candidate_parameters()
        assert isinstance(r, list)
        assert len(r) == 1
        assert type(r[0]) == Candidate
        assert r[0].foo == 'bar'

    def test_candidate_metrics(self, reqmock):
        reqmock.get('https://api/optimization_views/abc123/candidate_metrics',
                    status_code=200,
                    text='{"num": 1.0}')
        f = OptimizationView(id='abc123').candidate_metrics()
        assert f.num == 1.0

    def test_initial_portfolio_metrics(self, reqmock):
        reqmock.get('https://api/optimization_views/abc123/initial_portfolio_metrics',
                    status_code=200,
                    text='{"num": 1.0}')
        f = OptimizationView(id='abc123').initial_metrics()
        assert f.num == 1.0

    sensitivity_text = """
    {"sensitivities": [
    {"normalized_interquartile_range": 0.25, "min": 0.0, "normalized_standard_deviation": 0.29,
    "initial_share": 0.18, "hist": { "0.05": 5, "0.1": 0, "0.15": 0, "0.2": 0, "0.25": 0, "0.3": 9, "0.35": 0,
    "0.4": 0, "0.45": 0, "0.5": 3, "0.55": 0, "0.6": 5, "0.65": 0, "0.7": 3, "0.75": 0, "0.8": 3, "0.85": 2,
    "0.9": 4, "0.95": 2, "1.0": 64}, "mean": 0.81, "max": 1.0, "ref_id": "layer2"
    },
    { "normalized_interquartile_range": 0.71, "min": 0.0, "normalized_standard_deviation": 0.35,
    "initial_share": 0.08, "hist": {"0.05": 36, "0.1": 0, "0.15": 8, "0.2": 1, "0.25": 1, "0.3": 3,
    "0.35": 2, "0.4": 3, "0.45": 0, "0.5": 0, "0.55": 8, "0.6": 0, "0.65": 12, "0.7": 0, "0.75": 1,
    "0.8": 10, "0.85": 0, "0.9": 7, "0.95": 0, "1.0": 8}, "mean": 0.37, "max": 1.0, "ref_id": "layer1" }
    ] } """

    required_attributes = ['hist', 'min', 'max', 'mean', 'normalized_standard_deviation',
                           'normalized_interquartile_range', 'ref_id']

    @pytest.mark.parametrize("get_string, candidates, expected_len", [
        ('https://api/optimization_views/abc_id/sensitivity_analysis', [], 2),
        ('https://api/optimization_views/abc_id/sensitivity_analysis?candidates=0,2,5', [0, 2, 5], 2),
        ('https://api/optimization_views/abc_id/sensitivity_analysis?candidates=0,2,5', [0, 2, 5, 'a', 1.1, -2], 2)
    ])
    def test_sensitivity_analysis_with_candidates(self, reqmock, candidates, expected_len, get_string):
        # list of candidates should be translated to the correct api request
        reqmock.get('https://api/optimization_views/abc_id',
                    status_code=200, text='{"id":"abc_id"}')
        ov = OptimizationView.retrieve('abc_id')
        reqmock.get(get_string,
                    status_code=200, text=TestOptimizationResource.sensitivity_text)
        r = ov.sensitivity_analysis(candidates=candidates)
        assert hasattr(r, 'sensitivities')
        assert len(r.sensitivities) == expected_len
        for i in range(len(r.sensitivities)):
            for attribute in TestOptimizationResource.required_attributes:
                assert hasattr(r.sensitivities[i], attribute)

    def test_sensitivity_analysis_empty(self, reqmock):
        # result can be an empty list
        reqmock.get('https://api/optimization_views/abc_id',
                    status_code=200, text='{"id":"abc_id"}')
        ov = OptimizationView.retrieve('abc_id')
        reqmock.get('https://api/optimization_views/abc_id/sensitivity_analysis',
                    status_code=200, text='{"sensitivities": []}')
        r = ov.sensitivity_analysis()
        assert hasattr(r, 'sensitivities')
        assert len(r.sensitivities) == 0


text:
npm install node-telegram-bot-api slackbots slack-node scrape-it jsonfile -save
#set permissions
chmod a+x run.sh
#install daemontools
apt-get -y install daemontools-run daemontools
#make daemontools service folder for bot
mkdir /etc/service/tsbot
#create the run file
cat <<EOT > /etc/service/tsbot/run
#!/bin/bash
`pwd`/run.sh
EOT
chmod +x /etc/service/tsbot/run