text:
"""Morphing PDF
"""
# =============================================================================
__version__ = "$Revision:"
__author__  = "Vanya BELYAEV Ivan.Belyaev@itep.ru"
__date__    = "2020-07-22"
__all__     = (
    ##
    'MorphingN1_pdf'  , ## 1D-morphing PDF
    'MorphingN2_pdf'  , ## 2D-morphing PDF
    'MorphingN3_pdf'  , ## 3D-morphing PDF
    'LinearMorph_pdf' , ## linear morphing
    ##
    )
# =============================================================================
from   ostap.fitting.pdfbasic import PDF1, Generic1D_pdf
from   ostap.core.ostap_types import integer_types
import ROOT
# =============================================================================
from   ostap.logger.logger import getLogger
if '__main__' ==  __name__ : logger = getLogger ( 'ostap.fitting.morphing_pdf' )
else                       : logger = getLogger ( __name__                     )
# =============================================================================
## @class LinearMorph_pdf
#  Wrapper for RooIntegralMorth PDF
#  @see RooIntegralMorph
#  @see Alex Read, 'Linear interpolation of histograms', NIM A 425 (1999) 357-369
#  @see DOI: 10.1016/S0168-9002(98)01347-3
#  @see https://doi.org/10.1016/S0168-9002(98)01347-3
class LinearMorph_pdf (PDF1) :
    """Wrapper for RooIntegralMorth PDF
    - see RooIntegralMorph
    - see Alex Read, 'Linear interpolation of histograms', NIM A 425 (1999) 357-369
    - see DOI: 10.1016/S0168-9002(98)01347-3
    - see https://doi.org/10.1016/S0168-9002(98)01347-3
    """
    def __init__ ( self                ,
                   name                ,   ## PDF name
                   pdf1                ,   ## pdf at low  value of alppha
                   pdf2                ,   ## pdf at high value of alpha
                   alpha       = None  ,   ## morphing variable
                   xvar        = None  ,
                   cache_alpha = False ) : ## observable

        self.__pdf1 , xvar = self.make_PDF1 ( pdf1 , xvar = xvar )
        self.__pdf2 , xvar = self.make_PDF1 ( pdf2 , xvar = xvar )

        ## initialize the base class
        PDF1.__init__ ( self , name , xvar )

        ## create morphing variable
        self.__alpha = self.make_var (
            alpha               ,
            "alpha_%s"   % name ,
            "#alpha(%s)" % name , False , 0 , 1 )

        self.__cache_alpha = True if cache_alpha else False

        ## finally creathe the PDF
        self.pdf = ROOT.RooIntegralMorph (
            self.new_roo_name ( 'linMorph_' ),
            "Linear Morphing %s" % self.name ,
            self.pdf1.pdf    ,
            self.pdf2.pdf    ,
            self.xvar        ,
            self.alpha       ,
            self.cache_alpha )

        self.config = {
            'name'        : self.name        ,
            'pdf1'        : self.pdf1        ,
            'pdf2'        : self.pdf2        ,
            'xvar'        : self.xvar        ,
            'alpha'       : self.alpha       ,
            'cache_alpha' : self.cache_alpha ,
            }

    @property
    def pdf1 ( self ) :
        """'pdf1' : the first PDF (value of resulting pdf at the left edge of 'alpha')"""
        return self.__pdf1
    @property
    def pdf2 ( self ) :
        """'pdf2' : the first PDF (value of resulting pdf at the right edge of 'alpha')"""
        return self.__pdf2
    @property
    def alpha ( self ) :
        """'alpha' : morphing parameter"""
        return self.__alpha
    @alpha.setter
    def alpha ( self , value ) :
        self.set_value ( self.__alpha , value )
    @property
    def cache_alpha ( self ) :
        """'cache_alpha' : create cache for morphing parameter 'alpha'?"""
        return self.__cache_alpha

# =============================================================================
## @class MorphingN1_pdf
#  Wrapper for RooMomentMorph PDF
#  @see RooMomentMorph
#  @see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
#       "Interpolation between multi-dimensional histograms using
#       a new non-linear moment morphing method".
#       Nuclear Instruments & Methods in Physics Research.
#       Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
#  @see https://doi.org/10.1016/j.nima.2014.10.033
class MorphingN1_pdf (PDF1) :
    """ Wrapper for ROOT.RooMomentMorph PDF
    - see ROOT.RooMomentMorph
    - see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
    'Interpolation between multi-dimensional histograms using
    a new non-linear moment morphing method'.
    Nuclear Instruments & Methods in Physics Research.
    Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
    - see https://doi.org/10.1016/j.nima.2014.10.033
    """
    def __init__ ( self                ,
                   name                , ## PDF name
                   pdfs                , ## dictionary {mu1,mu2 -> pdf }
                   setting    = None   , ## morphing setting
                   morph_var  = None   , ## morphing variable mu
                   xvar       = None ) : ## observable (1D)

        assert pdfs and 2 <= len ( pdfs ) , \
               "Invalid dictionary of morphing PDFs!"

        if setting is None : setting = ROOT.RooMomentMorph.Linear

        assert isinstance ( setting , integer_types ) and 0 <= setting < 5,\
               'Invalid value for the setting %s/%s' %  ( setting , type ( setting ) )

        for k in pdfs :
            if xvar : break
            p = pdfs [ k ]
            if isinstance ( p , PDF ) :
                xvar = p.xvar
                break
        else :
            raise TypeError("Morphing_pdf: cannot identify xvar!")

        ## initialize the base class
        PDF1.__init__ ( self , name , xvar )

        ## convert the dictionary of PDFs into  ordered list/tuple of pairs (mu,pdf)
        self.__pdflist = []
        for k in sorted ( pdfs.keys()  ) :

            pdfk = pdfs [ k ]

            if   isinstance ( pdfk , PDF1           ) and pdfk.xvar is self.xvar : pass
            elif isinstance ( pdfk , ROOT.RooAbsPdf ) :
                pdfk = Generic1D_pdf ( pdfk , xvar = self.xvar )
            else :
                pass

            pair = k , pdfk
            self.pdflist.append ( pair )

        ## convert to tuple
        self.__pdflist = tuple ( self.__pdflist )

        ## save setting
        self.__setting = setting

        ## min and maximal value of morhing parameter
        mu_min = self.pdflist[ 0][0]
        mu_max = self.pdflist[-1][0]

        ## create morphing variable
        self.__mu = self.make_var (
            morph_var                ,
            "mu_%s"           % name ,
            "morphing mu(%s)" % name , False , mu_min , mu_max )

        ## vector of morphing values
        muvct  = ROOT.TVectorD ( len ( self.pdflist ) )
        pdflst = ROOT.RooArgList()
        for i , p in enumerate ( self.pdflist ) :
            muvct [ i ] = p [ 0 ]
            pdflst.add (  p [ 1 ].pdf )

        observables = ROOT.RooArgList (  self.xvar )
        self.aux_keep.append  ( observables )

        ## create the PDF
        self.pdf = ROOT.RooMomentMorph (
            self.roo_name ( 'morph_' ) ,
            "Morphing %s" % self.name  ,
            self.mu               , ## morphing variable
            observables           , ## observables
            pdflst                , ## ordered list of PDFs
            muvct                 , ## values of morhing parameter
            self.setting          ) ## morphing setting

        #
        self.config = {
            'name'      : self.name             ,
            'setting'   : self.setting          ,
            'xvar'      : self.xvar             ,
            'morph_var' : self.mu               ,
            'pdfs'      : dict ( self.pdflist ) ,
            }

    @property
    def mu ( self ) :
        """'mu' : morphing variable"""
        return self.__mu
    @mu.setter
    def mu ( self , value ) :
        self.set_value ( self.__mu , value )

    @property
    def pdflist ( self ) :
        """'pdflist' : (sorted) tuple of (morphing parameter, pdf) pairs"""
        return self.__pdflist

    @property
    def setting ( self ) :
        """'setting': morphing setting"""
        return self.__setting

# =============================================================================
## @class MorphingN2_pdf
#  Wrapper for RooMomentMorph PDF
#  - 1D morphing/2D  PDF
#  @see RooMomentMorphND
#  @see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
#       "Interpolation between multi-dimensional histograms using
#       a new non-linear moment morphing method".
#       Nuclear Instruments & Methods in Physics Research.
#       Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
#  @see https://doi.org/10.1016/j.nima.2014.10.033
class MorphingN2_pdf (PDF1) :
    """ Wrapper for ROOT.RooMomentMorphND PDF for N = 2
    - 1D morphing/2D PDF
    - see ROOT.RooMomentMorphND
    - see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
    'Interpolation between multi-dimensional histograms using
    a new non-linear moment morphing method'.
    Nuclear Instruments & Methods in Physics Research.
    Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
    - see https://doi.org/10.1016/j.nima.2014.10.033
    """
    def __init__ ( self                ,
                   name                , ## PDF name
                   pdfs                , ## dictionary {mu1,mu2 -> pdf }
                   setting    = None   , ## morphing setting
                   morph_var1 = None   , ## morphing variable mu1
                   morph_var2 = None   , ## morphing variable mu2
                   xvar       = None ) : ## observable (1D)

        assert pdfs and 4 <= len ( pdfs ) , \
               "Invalid dictionary of morphing PDFs!"

        if setting is None : setting = ROOT.RooMomentMorphND.Linear

        assert isinstance ( setting , integer_types ) and 0 <= setting < 5,\
               'Invalid value for the setting %s/%s' %  ( setting , type ( setting ) )

        v1ps = set ()
        v2ps = set ()

        for k in pdfs :
            v1 , v2 = k
            v1ps.add ( v1 )
            v2ps.add ( v2 )
            p = pdfs [ k ]
            if not xvar and isinstance ( p , PDF1 ) :
                xvar = p.xvar

        assert xvar and isinstance ( xvar , ROOT.RooAbsReal ) , 'Cannot deduce xvar!'

        assert 2 <= len ( v1ps ) and 2 <= len ( v2ps ) , 'Invalid number of bins!'

        v1ps = list ( v1ps )
        v2ps = list ( v2ps )

        v1ps.sort ()
        v2ps.sort ()

        assert  len ( pdfs ) ==  len ( v1ps ) * len ( v2ps ) ,\
               'Invalid table/dict structure!'

        ## initialize the base class
        PDF1.__init__ ( self , name , xvar )

        ## create morphing variables
        self.__mu1 = self.make_var (
            morph_var1                ,
            "mu1_%s"           % name ,
            "morphing mu1(%s)" % name , False , v1ps[0] , v1ps[-1] )

        ## create morphing variables
        self.__mu2 = self.make_var (
            morph_var2                ,
            "mu2_%s"           % name ,
            "morphing mu2(%s)" % name , False , v2ps[0] , v2ps[-1] )

        self.__pdfdict = {}
        for k in sorted ( pdfs.keys()  ) :

            v1 , v2 = k

            pdfk = pdfs [ k ]
            if   isinstance ( pdfk , PDF1           ) and pdfk.xvar is self.xvar : pass
            elif isinstance ( pdfk , ROOT.RooAbsPdf ) :
                pdfk = Generic1D_pdf ( pdfk , xvar = self.xvar )
            else :
                raise TypeError( "Invalid component type: %s/%s" % ( pdfk , type ( pdfk ) ) )

            pair = k , pdfk
            self.pdfdict [ ( v1, v2 ) ] = pdfk

        ## save setting
        self.__setting = setting

        ## fill morphing grid
        from ostap.fitting.variables import binning

        bins_v1     = binning ( v1ps , name = 'morph1' )
        bins_v2     = binning ( v2ps , name = 'morph2' )
        self.__grid = ROOT.RooMomentMorphND.Grid ( bins_v1 , bins_v2 )

        for k in self.pdfdict :

            p       = self.pdfdict [ k ]

            v1 , v2 = k

            assert v1 in v1ps , 'MorphingN2_pdf: Invalid v1 value %s' % v1
            assert v2 in v2ps , 'MorphingN2_pdf: Invalid v2 value %s' % v2

            ib1 = v1ps.index ( v1 )
            ib2 = v2ps.index ( v2 )

            ## ib1 = bins_v1.binNumber ( v1 )
            ## ib2 = bins_v2.binNumber ( v2 )

            self.__grid.addPdf ( p.pdf , ib1 , ib2 )

        morph_vars  = ROOT.RooArgList ( self.mu1 , self.mu2 )
        observables = ROOT.RooArgList ( self.xvar )

        self.aux_keep.append  ( morph_vars  )
        self.aux_keep.append  ( observables )

        ## create the PDF
        self.pdf = ROOT.RooMomentMorphND (
            self.roo_name ( 'morph2_' )   ,
            "Morphing 2D %s" % self.name  ,
            morph_vars              , ## morphing variables
            observables             , ## observables
            self.grid               , ## morphing grid
            self.setting            ) ## morphing setting

        #
        self.config = {
            'name'       : self.name    ,
            'setting'    : self.setting ,
            'xvar'       : self.xvar    ,
            'morph_var1' : self.mu1     ,
            'morph_var2' : self.mu2     ,
            'pdfs'       : self.pdfdict ,
            }

    @property
    def mu1 ( self ) :
        """'mu1' : the first morphing variable"""
        return self.__mu1
    @mu1.setter
    def mu1 ( self , value ) :
        self.set_value  ( self.__mu1 , value )

    @property
    def mu2 ( self ) :
        """'mu2' : the second morphing variable"""
        return self.__mu2
    @mu2.setter
    def mu2 ( self , value ) :
        self.set_value  ( self.__mu2 , value )

    @property
    def grid    ( self ) :
        """'grid' : morphing 2D-grid"""
        return self.__grid

    @property
    def pdfdict ( self ) :
        """'pdfdict' : Dictionary { morphing parameters : pdf } """
        return self.__pdfdict

    @property
    def setting ( self ) :
        """'setting': morphing setting"""
        return self.__setting

# =============================================================================
## @class MorphingN3_pdf
#  Wrapper for RooMomentMorph PDF
#  - 1D morphing/3D  PDF
#  @see RooMomentMorphND
#  @see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
#       "Interpolation between multi-dimensional histograms using
#       a new non-linear moment morphing method".
#       Nuclear Instruments & Methods in Physics Research.
#       Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
#  @see https://doi.org/10.1016/j.nima.2014.10.033
class MorphingN3_pdf (PDF1) :
    """ Wrapper for ROOT.RooMomentMorphND PDF for N = 2
    - 1D morphing/3D PDF
    - see ROOT.RooMomentMorphND
    - see Baak, M., Gadatsch, S., Harrington, R., & Verkerke, W. (2015).
    'Interpolation between multi-dimensional histograms using
    a new non-linear moment morphing method'.
    Nuclear Instruments & Methods in Physics Research.
    Section A - Accelerators Spectrometers Detectors and Associated Equipment, 771, 39-48.
    - see https://doi.org/10.1016/j.nima.2014.10.033
    """
    def __init__ ( self                ,
                   name                , ## PDF name
                   pdfs                , ## dictionary {mu1,mu2 -> pdf }
                   setting    = None   , ## morphing setting
                   morph_var1 = None   , ## morphing variable mu1
                   morph_var2 = None   , ## morphing variable mu2
                   morph_var3 = None   , ## morphing variable mu3
                   xvar       = None ) : ## observable (1D)

        assert pdfs and 6 <= len ( pdfs ) , \
               "Invalid dictionary of morphing PDFs!"

        if setting is None : setting = ROOT.RooMomentMorphND.Linear

        assert isinstance ( setting , integer_types ) and 0 <= setting < 5,\
               'Invalid value for the setting %s/%s' %  ( setting , type ( setting ) )

        v1ps = set ()
        v2ps = set ()
        v3ps = set ()

        for k in pdfs :
            v1 , v2 , v3 = k
            v1ps.add ( v1 )
            v2ps.add ( v2 )
            v3ps.add ( v3 )
            p = pdfs [ k ]
            if not xvar and isinstance ( p , PDF1 ) :
                xvar = p.xvar

        assert xvar and isinstance ( xvar , ROOT.RooAbsReal ) , 'Cannot deduce xvar!'

        assert 2 <= len ( v1ps ) and 2 <= len ( v2ps ) and 2 <= len ( v3ps ) , 'Invalid number of bins!'

        v1ps = list ( v1ps )
        v2ps = list ( v2ps )
        v3ps = list ( v3ps )

        v1ps.sort ()
        v2ps.sort ()
        v3ps.sort ()

        assert  len ( pdfs ) ==  len ( v1ps ) * len ( v2ps ) * len ( v3ps ) ,\
               'Invalid table/dict structure!'

        ## initialize the base class
        PDF1.__init__ ( self , name , xvar )

        ## create morphing variables
        self.__mu1 = self.make_var (
            morph_var1                ,
            "mu1_%s"           % name ,
            "morphing mu1(%s)" % name , False , v1ps[0] , v1ps[-1] )

        ## create morphing variables
        self.__mu2 = self.make_var (
            morph_var2                ,
            "mu2_%s"           % name ,
            "morphing mu2(%s)" % name , False , v2ps[0] , v2ps[-1] )

        ## create morphing variables
        self.__mu3 = self.make_var (
            morph_var3                ,
            "mu3_%s"           % name ,
            "morphing mu3(%s)" % name , False , v3ps[0] , v3ps[-1] )

        self.__pdfdict = {}
        for k in sorted ( pdfs.keys()  ) :

            v1 , v2 . v3 = k

            pdfk = pdfs [ k ]
            if   isinstance ( pdfk , PDF1           ) and pdfk.xvar is self.xvar : pass
            elif isinstance ( pdfk , ROOT.RooAbsPdf ) :
                pdfk = Generic1D_pdf ( pdfk , xvar = self.xvar )
            else :
                raise TypeError( "Invalid component type: %s/%s" % ( pdfk , type ( pdfk ) ) )

            pair = k , pdfk
            self.pdfdict [ ( v1, v2 , v3 ) ] = pdfk

        ## save setting
        self.__setting = setting

        ## fill morphing grid
        from ostap.fitting.variables import binning

        bins_v1     = binning ( v1ps , name = 'morph1' )
        bins_v2     = binning ( v2ps , name = 'morph2' )
        bins_v3     = binning ( v3ps , name = 'morph3' )
        self.__grid = ROOT.RooMomentMorphND.Grid ( bins_v1 , bins_v2 . bins_v3 )

        for k in self.pdfdict :

            p       = self.pdfdict [ k ]

            v1 , v2 , v3 = k

            assert v1 in v1ps , 'MorphingN3_pdf: Invalid v1 value %s' % v1
            assert v2 in v2ps , 'MorphingN3_pdf: Invalid v2 value %s' % v2
            assert v3 in v3ps , 'MorphingN3_pdf: Invalid v3 value %s' % v3

            ib1 = v1ps.index ( v1 )
            ib2 = v2ps.index ( v2 )
            ib3 = v3ps.index ( v3 )

            ## ib1 = bins_v1.binNumber ( v1 )
            ## ib2 = bins_v2.binNumber ( v2 )

            self.__grid.addPdf ( p.pdf , ib1 , ib2 , ib3 )

        morph_vars  = ROOT.RooArgList ( self.mu1 , self.mu2 , self.mu3 )
        observables = ROOT.RooArgList ( self.xvar )

        self.aux_keep.append  ( morph_vars  )
        self.aux_keep.append  ( observables )

        ## create the PDF
        self.pdf = ROOT.RooMomentMorphND (
            self.roo_name ( 'morph3_' )   ,
            "Morphing 3D %s" % self.name  ,
            morph_vars              , ## morphing variables
            observables             , ## observables
            self.grid               , ## morphing grid
            self.setting            ) ## morphing setting

        #
        self.config = {
            'name'       : self.name    ,
            'setting'    : self.setting ,
            'xvar'       : self.xvar    ,
            'morph_var1' : self.mu1     ,
            'morph_var2' : self.mu2     ,
            'morph_var3' : self.mu3     ,
            'pdfs'       : self.pdfdict ,
            }

    @property
    def mu1 ( self ) :
        """'mu1' : the first morphing variable"""
        return self.__mu1
    @mu1.setter
    def mu1 ( self , value ) :
        self.set_value  ( self.__mu1 , value )

    @property
    def mu2 ( self ) :
        """'mu2' : the second morphing variable"""
        return self.__mu2
    @mu2.setter
    def mu2 ( self , value ) :
        self.set_value  ( self.__mu2 , value )

    @property
    def mu3 ( self ) :
        """'mu3' : the third morphing variable"""
        return self.__mu3
    @mu3.setter
    def mu3 ( self , value ) :
        self.set_value  ( self.__mu3 , value )

    @property
    def grid    ( self ) :
        """'grid' : morphing 2D-grid"""
        return self.__grid

    @property
    def pdfdict ( self ) :
        """'pdfdict' : Dictionary { morphing parameters : pdf } """
        return self.__pdfdict

    @property
    def setting ( self ) :
        """'setting': morphing setting"""
        return self.__setting

# =============================================================================
if '__main__' == __name__ :

    from ostap.utils.docme import docme
    docme ( __name__ , logger = logger )

# =============================================================================
##                                                                      The END
# =============================================================================


text:
const path = require("path");

module.exports = pathName => path.isAbsolute(pathName) ? pathName : path.resolve(process.cwd(), pathName);

redpajama_set_name: RedPajamaGithub


text:
var util = require('../util');

var affixes = require('../../data/affixes');
var affixMap = require('../../data/affixes/affix-map');
var classMap = require('../../data/class-map');

var baseItem = require('./item-base');

//for rare (yellow) items with random primary and suffix rolling
var itemRare = function(rarity, slot, dClass) {

	//inherit properties from base d3item object
	baseItem.call(this, rarity, slot, dClass);
	this.color='yellow';

	//initialize the primary and secondary objects
	this.primaries = {};
	this.secondaries = {};

	//if a class is given and the item type can roll it
	//ensure that there is a main stat primary;
	if (Object.keys(classMap).indexOf(dClass) !== -1 &&
		affixMap[classMap[dClass]].hasOwnProperty('exclude') &&
		affixMap[classMap[dClass]].exclude.indexOf(this.type) !== -1) {

		this.primaries.MAIN = null;
		//then roll between 1-3 primaries
		this.primaries.RANDOM = util.intRandom(1,3);
	}
	else{
		this.primaries.RANDOM = util.intRandom(1,4);
	}

	//roll for secondaries;
	this.secondaries.RANDOM = util.intRandom(1,2);

	//placeholder name for now;
	this.name = 'Rare ' + affixes[slot.toLowerCase()].type[this.type].name_en;

};

module.exports = itemRare;


text:
package scrupal.core

import com.reactific.helpers.{TossedException, Registrable, Registry}
import org.specs2.mutable.Specification
import scrupal.test.ClassFixture
import scrupal.utils.ScrupalException

class Scenario extends AutoCloseable {
  object TSRegistry extends Registry[TestScope] { val registryName = "TestScopes"; val registrantsName = "test scopes" }
  case class TestScope(id : Symbol, children : Seq[Enablement[_]] = Seq())
    extends Enablement[TestScope] with Registrable[TestScope] {
    def registry : Registry[TestScope] = TSRegistry
    def isChildScope(x : Enablement[_]) : Boolean = children.contains(x)
  }
  object TERegistry extends Registry[TestEnablee] {
    val registryName = "TestEnablees"; val registrantsName = "test enablees"
  }

  case class TestEnablee(id : Symbol, override val parent : Option[Enablee] = None)
    extends Enablee with Registrable[TestEnablee] {
    def registry : Registry[TestEnablee] = TERegistry
  }

  val root_1_a = TestScope('root_1_a)
  val root_1_b = TestScope('root_1_b)
  val root_1 = TestScope('root_1, Seq(root_1_a, root_1_b))
  val root_2_a = TestScope('root_2_a)
  val root_2 = TestScope('root_2, Seq(root_2_a))
  val root = TestScope('root, Seq(root_1, root_2))

  val e_root = TestEnablee('e_root)
  val e_root_1 = TestEnablee('e_root_1, Some(e_root))
  val e_root_2 = TestEnablee('e_root_2, Some(e_root))

  def close() = {}
}

/** Test Suite For Enablement */
class EnablementSpec extends Specification {

  val scenario = new ClassFixture(new Scenario)

  "Enablee" should {
    "have parent hierarchy" in scenario { s ⇒
      val e = new Enablee {
        override def id: Identifier = 'foo
      }
      e.parent must beEqualTo(None)
      s.e_root.parent must beEqualTo(None)
      s.e_root_1.parent must beEqualTo(Some(s.e_root))
    }

    "allow enable on multiple scopes" in scenario { s ⇒
      s.e_root.enable(s.root)
      s.e_root.isEnabled(s.root) must beTrue
      s.e_root.isEnabled(s.root, how=true) must beTrue
      s.e_root.isEnabled(s.root, how=false) must beFalse
      s.e_root.enable(s.root_1)
      s.e_root.isEnabled(s.root_1) must beTrue
      s.e_root.isEnabled(s.root_1, how=true) must beTrue
      s.e_root.isEnabled(s.root_1, how=false) must beFalse
    }

    "allow enabled with various interfaces" in scenario { s ⇒
      s.e_root.enable(s.root, how=true)
      s.e_root.isEnabled(s.root) must beTrue
      s.e_root.enable(s.root, how=false)
      s.e_root.isEnabled(s.root) must beFalse
      s.e_root.isEnabled(s.root, how=true) must beFalse
      s.e_root.isEnabled(s.root, how=false) must beTrue
    }

    "allow disable on multiple scopes" in scenario { s ⇒
      s.e_root.disable(s.root)
      s.e_root.isEnabled(s.root) must beFalse
      s.e_root.disable(s.root_1)
      s.e_root.isEnabled(s.root_1) must beFalse
    }
  }

  "Enablement" should {
    "allow query on arbitrary scopes" in scenario { s ⇒
      s.root.enable(s.e_root, s.root_1)
      s.e_root.isEnabled(s.root) must beFalse
      s.e_root.isEnabled(s.root_1) must beFalse
      s.root.isEnabled(s.e_root, s.root_1) must beTrue
      s.root_1.isEnabled(s.e_root) must beFalse
      s.root_1_a.isEnabled(s.e_root) must beFalse
    }

    "not be enabled if parent is disabled" in scenario { s ⇒
      s.root.disable(s.e_root)
      s.root.enable(s.e_root_1)
      s.root.isEnabled(s.e_root_1) must beFalse
      s.e_root_1.isEnabled(s.root) must beFalse
    }

    "not allow enabling of a parent scope" in scenario { s ⇒
      s.root_1.enable(s.e_root_1, s.root) must throwA[ScrupalException]
      s.root_1.disable(s.e_root_1, s.root) must throwA[ScrupalException]
      s.root_1.isEnabled(s.e_root_1, s.root) must throwA[ScrupalException]
    }

    "allow enabling with an Option" in scenario { s ⇒
      s.root_1.enable(Some(s.e_root_1))
      s.root_1.enable(Some(s.e_root_1), Some(s.root_1))
      success
    }

    "allow enabling" in scenario { s ⇒
      s.root.enable(s.e_root, s.root_1)
      s.root.disable(s.e_root, s.root_1)
      s.root.enable(s.e_root_1, s.root_1)
      s.root.mapEnabled { e : Enablee ⇒ s.root_1.isEnabled(e) must beTrue }
      success
    }
  }
}


text:
@interface EGSecondViewController : UIViewController

@end


text:
<?php

namespace Frisbee\View;

use App\Resource\Fetcher\Template as TemplateFetcher;

class TwigView extends AbstractView
{
    /**
     * @var string
     */
    protected $templateName;

    public function __construct($template, $vars = [])
    {
        $this->templateName = $template;
        parent::__construct($vars);
    }

    public function run()
    {
        if (!isset($this->resources['template'])) {
            throw new TemplateFetcher('template', $this);
        }

        $template = $this->resources['template'];
        echo $template->render($this->templateName, $this->vars);
    }
}


text:
package com.github.violetlaw.citegen;

import java.util.List;

import com.github.violetlaw.citegen.Citation.CitationRequest;
import com.github.violetlaw.citegen.Citation.Publication;
import com.github.violetlaw.citegen.Text.Style;
import com.github.violetlaw.citegen.Text.TextBlock;
import com.github.violetlaw.citegen.Text.TextBlock.Builder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.common.collect.Iterables;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class CitationGenerator {

  public TextBlock handleRequest(CitationRequest request) {

    // TODO(nnaze): Implement.
    TextBlock.Builder builder = TextBlock.newBuilder();

    TextBlock authorsBlock = createAuthorsTextBlock(request.getAuthorsList());
    if (authorsBlock != null) {
      builder.addChildren(authorsBlock);

      TextBlock commaTextBlock = TextBlock.newBuilder().setText(", ").build();
      builder.addChildren(commaTextBlock);
    }

    String titleString = getTitleString(request);
    if (titleString != null) {
      TextBlock titleBlock =
          TextBlock.newBuilder().setText(titleString).addStyle(Style.ITALICS).build();
      builder.addChildren(titleBlock);
    }

    // Separating space
    builder.addChildren(TextBlock.newBuilder().setText(" ").build());

    TextBlock publicationBlock = getPublicationBlock(request.getPublication());
    builder.addChildren(publicationBlock);

    String pinCite = request.getPincite();
    if (!pinCite.isEmpty()) {
      builder.addChildren(getText(" "));
      builder.addChildren(getText(pinCite));
    }

    return builder.build();
  }

  private static TextBlock getPublicationBlock(Publication publication) {
    // TODO(nanaze): Rendering can differ based
    return TextBlock.newBuilder().setText(publication.getTitle()).build();
  }

  @Nullable
  private static String getTitleString(CitationRequest request) {
    if (request.getTitle() == null) {
      return null;
    }

    StringBuilder builder = new StringBuilder();
    builder.append(request.getTitle());

    String volume = request.getVolume();
    if (volume != null) {
      builder.append(String.format(", %s", volume));
    }

    return builder.toString();
  }

  @Nullable
  private static TextBlock createAuthorsTextBlock(List<String> authors) {

    String authorsText = createAuthorsText(authors);
    if (authorsText == null) {
      return null;
    }

    TextBlock.Builder builder = TextBlock.newBuilder();
    builder.setText(createAuthorsText(authors));
    return builder.build();
  }

  @VisibleForTesting
  static String createAuthorsText(List<String> authors) {
    // With one author, we just list the author.
    if (authors.size() == 1) {
      return Iterables.getOnlyElement(authors);
    }

    // For two authors, join with ampersand.
    if (authors.size() == 2) {
      Joiner joiner = Joiner.on(" & ");
      return joiner.join(authors);
    }

    // > 2, use "et al."
    if (authors.size() > 2) {
      String firstAuthor = authors.get(0);
      return firstAuthor + " et al.";
    }

    return null;
  }

  private static TextBlock getText(String text) {
    return TextBlock.newBuilder().setText(text).build();
  }
}


text:
package org.onosproject.net.device;

import java.util.Collections;
import java.util.List;

import org.onosproject.net.Device;
import org.onosproject.net.Device.Type;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;

import com.google.common.collect.FluentIterable;

/**
 * Test adapter for device service.
 */
public class DeviceServiceAdapter implements DeviceService {

    private List<Port> portList;

    /**
     * Constructor with port list.
     *
     * @param portList port list
     */
    public DeviceServiceAdapter(List<Port> portList) {
        this.portList = portList;
    }

    /**
     * Default constructor.
     */
    public DeviceServiceAdapter() {

    }

    @Override
    public int getDeviceCount() {
        return 0;
    }

    @Override
    public Iterable<Device> getDevices() {
        return Collections.emptyList();
    }

    @Override
    public Iterable<Device> getAvailableDevices() {
        return FluentIterable.from(getDevices())
                .filter(input -> isAvailable(input.id()));
    }

    @Override
    public Device getDevice(DeviceId deviceId) {
        return null;
    }

    @Override
    public MastershipRole getRole(DeviceId deviceId) {
        return MastershipRole.NONE;
    }

    @Override
    public List<Port> getPorts(DeviceId deviceId) {
        return portList;
    }

    @Override
    public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
        return null;
    }

    @Override
    public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
        return null;
    }

    @Override
    public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
        return null;
    }

    @Override
    public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
        return null;
    }

    @Override
    public Port getPort(DeviceId deviceId, PortNumber portNumber) {
        return getPorts(deviceId).stream()
                   .filter(port -> deviceId.equals(port.element().id()))
                   .filter(port -> portNumber.equals(port.number()))
                   .findFirst().orElse(null);
    }

    @Override
    public boolean isAvailable(DeviceId deviceId) {
        return false;
    }

    @Override
    public void addListener(DeviceListener listener) {
    }

    @Override
    public void removeListener(DeviceListener listener) {
    }

    @Override
    public Iterable<Device> getDevices(Type type) {
        return Collections.emptyList();
    }

    @Override
    public Iterable<Device> getAvailableDevices(Type type) {
        return Collections.emptyList();
    }

    @Override
    public String localStatus(DeviceId deviceId) {
        return null;
    }

}


text:
namespace json {

    //==========================================================================

    struct case_insensitive_compare
    {
        bool operator () (const string& a, const string& b) const
        {
            return strcasecmp(a.c_str(), b.c_str()) < 0;
        }
    };

    struct object : std::map<string, value, case_insensitive_compare>
    {
    public: // types

        using base = std::map<string, value, case_insensitive_compare>;

    public: // structors

        object();

        explicit
        object(const object&);
        object(      object&&);

        object(std::initializer_list<json::pair>);

        static object parse(const char*);
        static object parse(const string&);
        static object parse(std::istream&);

    public: // operators

        object& operator = (const object&);
        object& operator = (      object&&);

        bool operator == (const object&) const;
        bool operator != (const object&) const;

    public: // algorithms

        bool contains(const string&) const;

        const value* find(const string&) const;
              value* find(const string&);

        value remove(const string&);
    };

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

    object& operator << (object&, const char*);
    object& operator << (object&, const string&);
    object& operator << (object&, std::istream&);

    std::ostream& operator << (std::ostream&, const object&);

    //==========================================================================

};

// for lldb debugging, lldb often doesn't grok namespaces and std::cout
extern void debugPrintJSONObject(const json::object&);


text:
layout: single
header:
    image: page_outlining_header.jpg

author_profile: true
---

    Hello,
    I'm Hang GAO.

    I am currently a M.S. student in Computer Science at Columbia, targeted in pursuing a Ph.D. degree in the field of Machine Learning. I am most interested in deep generative models and its transfer learning application, whether it be in their development, inference, or more generally their foundations for computational and statistical analysis.

To briefly define myself, I'd like to go for:

a consistent learner,

an independent developer,

and a clumsy observer.

    If you want to get in touch with me, email could be the best way.


text:
r"""Exports an SSD detection model to use with tf-lite.

Outputs file:
* A tflite compatible frozen graph - $output_directory/tflite_graph.pb

The exported graph has the following input and output nodes.

Inputs:
'normalized_input_image_tensor': a float32 tensor of shape
[1, height, width, 3] containing the normalized input image. Note that the
height and width must be compatible with the height and width configured in
the fixed_shape_image resizer options in the pipeline config proto.

In floating point Mobilenet model, 'normalized_image_tensor' has values
between [-1,1). This typically means mapping each pixel (linearly)
to a value between [-1, 1]. Input image
values between 0 and 255 are scaled by (1/128.0) and then a value of
-1 is added to them to ensure the range is [-1,1).
In quantized Mobilenet model, 'normalized_image_tensor' has values between [0,
255].
In general, see the `preprocess` function defined in the feature extractor class
in the object_detection/models directory.

Outputs:
If add_postprocessing_op is true: frozen graph adds a
  TFLite_Detection_PostProcess custom op node has four outputs:
  detection_boxes: a float32 tensor of shape [1, num_boxes, 4] with box
  locations
  detection_classes: a float32 tensor of shape [1, num_boxes]
  with class indices
  detection_scores: a float32 tensor of shape [1, num_boxes]
  with class scores
  num_boxes: a float32 tensor of size 1 containing the number of detected boxes
else:
  the graph has two outputs:
   'raw_outputs/box_encodings': a float32 tensor of shape [1, num_anchors, 4]
    containing the encoded box predictions.
   'raw_outputs/class_predictions': a float32 tensor of shape
    [1, num_anchors, num_classes] containing the class scores for each anchor
    after applying score conversion.

Example Usage:
--------------
python object_detection/export_tflite_ssd_graph \
    --pipeline_config_path path/to/ssd_mobilenet.config \
    --trained_checkpoint_prefix path/to/model.ckpt \
    --output_directory path/to/exported_model_directory

The expected output would be in the directory
path/to/exported_model_directory (which is created if it does not exist)
with contents:
 - tflite_graph.pbtxt
 - tflite_graph.pb
Config overrides (see the `config_override` flag) are text protobufs
(also of type pipeline_pb2.TrainEvalPipelineConfig) which are used to override
certain fields in the provided pipeline_config_path.  These are useful for
making small changes to the inference graph that differ from the training or
eval config.

Example Usage (in which we change the NMS iou_threshold to be 0.5 and
NMS score_threshold to be 0.0):
python object_detection/export_tflite_ssd_graph \
    --pipeline_config_path path/to/ssd_mobilenet.config \
    --trained_checkpoint_prefix path/to/model.ckpt \
    --output_directory path/to/exported_model_directory
    --config_override " \
            model{ \
            ssd{ \
              post_processing { \
                batch_non_max_suppression { \
                        score_threshold: 0.0 \
                        iou_threshold: 0.5 \
                } \
             } \
          } \
       } \
       "
"""

import tensorflow as tf
from google.protobuf import text_format
from object_detection import export_tflite_ssd_graph_lib
from object_detection.protos import pipeline_pb2

flags = tf.app.flags
flags.DEFINE_string('output_directory', None, 'Path to write outputs.')
flags.DEFINE_string(
    'pipeline_config_path', None,
    'Path to a pipeline_pb2.TrainEvalPipelineConfig config '
    'file.')
flags.DEFINE_string('trained_checkpoint_prefix', None, 'Checkpoint prefix.')
flags.DEFINE_integer('max_detections', 10,
                     'Maximum number of detections (boxes) to show.')
flags.DEFINE_integer('max_classes_per_detection', 1,
                     'Number of classes to display per detection box.')
flags.DEFINE_bool('add_postprocessing_op', True,
                  'Add TFLite custom op for postprocessing to the graph.')
flags.DEFINE_string(
    'config_override', '', 'pipeline_pb2.TrainEvalPipelineConfig '
    'text proto to override pipeline_config_path.')

FLAGS = flags.FLAGS

def main(argv):
  del argv  # Unused.
  flags.mark_flag_as_required('output_directory')
  flags.mark_flag_as_required('pipeline_config_path')
  flags.mark_flag_as_required('trained_checkpoint_prefix')

  pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()

  with tf.gfile.GFile(FLAGS.pipeline_config_path, 'r') as f:
    text_format.Merge(f.read(), pipeline_config)
  text_format.Merge(FLAGS.config_override, pipeline_config)
  export_tflite_ssd_graph_lib.export_tflite_graph(
      pipeline_config, FLAGS.trained_checkpoint_prefix, FLAGS.output_directory,
      FLAGS.add_postprocessing_op, FLAGS.max_detections,
      FLAGS.max_classes_per_detection)

if __name__ == '__main__':
  tf.app.run(main)


text:
Unofficial fork of [automator-scp][1]. Notiable changes:

1. Removed _check for update_ button
2. Removed link to explaining how to setup SSH keys

[1]: http://code.google.com/p/automator-scp/


text:
package com.spollo.player.format;

import android.text.TextUtils;

public class Capitalize {

    /* This class is never initiated */
    public Capitalize() {
    }

    public static final String capitalize(String str) {
        return capitalize(str, null);
    }

    /**
     * Capitalizes the first character in a string
     *
     * @param str The string to capitalize
     * @param delimiters The delimiters
     * @return A captitalized string
     */
    public static final String capitalize(String str, char... delimiters) {
        final int delimLen = delimiters == null ? -1 : delimiters.length;
        if (TextUtils.isEmpty(str) || delimLen == 0) {
            return str;
        }
        final char[] buffer = str.toCharArray();
        boolean capitalizeNext = true;
        for (int i = 0; i < buffer.length; i++) {
            char ch = buffer[i];
            if (isDelimiter(ch, delimiters)) {
                capitalizeNext = true;
            } else if (capitalizeNext) {
                buffer[i] = Character.toTitleCase(ch);
                capitalizeNext = false;
            }
        }
        return new String(buffer);
    }

    /**
     * Is the character a delimiter.
     *
     * @param ch the character to check
     * @param delimiters the delimiters
     * @return true if it is a delimiter
     */
    private static final boolean isDelimiter(char ch, char[] delimiters) {
        if (delimiters == null) {
            return Character.isWhitespace(ch);
        }
        for (char delimiter : delimiters) {
            if (ch == delimiter) {
                return true;
            }
        }
        return false;
    }
}


text:
<meta charset="UTF-8">
<title>SuffixWordProbabilityModel.getFilter - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.tnt / SuffixWordProbabilityModel / getFilter

getFilter

open fun getFilter(): WordCapFilter


text:
package com.google.firebase.database;

import com.google.firebase.FirebaseApp;
import com.google.firebase.database.core.DatabaseConfig;
import com.google.firebase.database.core.Path;
import com.google.firebase.database.core.Repo;
import com.google.firebase.database.core.RepoInfo;
import com.google.firebase.database.snapshot.IndexedNode;
import com.google.firebase.database.snapshot.Node;

/**
 * Internal helpers in com.google.firebase.database package (for use by core, tests, etc.)
 *
 * @hide
 */
public class InternalHelpers {

  /** So Repo, etc. can create DatabaseReference instances. */
  public static DatabaseReference createReference(Repo repo, Path path) {
    return new DatabaseReference(repo, path);
  }

  /** So Repo, etc. can create DataSnapshots. */
  public static DataSnapshot createDataSnapshot(DatabaseReference ref, IndexedNode node) {
    return new DataSnapshot(ref, node);
  }

  /** So Repo can create FirebaseDatabase objects to keep legacy tests working. */
  public static FirebaseDatabase createDatabaseForTests(
      FirebaseApp app, RepoInfo repoInfo, DatabaseConfig config) {
    return FirebaseDatabase.createForTests(app, repoInfo, config);
  }

  /** For Repo to create MutableData objects. */
  public static MutableData createMutableData(Node node) {
    return new MutableData(node);
  }

  /**
   * For Repo to check if the database has been destroyed.
   */
  public static void checkNotDestroyed(Repo repo) {
    repo.getDatabase().checkNotDestroyed();
  }
}


text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.logaggregation.ContainerLogsRetentionPolicy;
import org.apache.hadoop.yarn.logaggregation.LogAggregationUtils;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.LogHandler;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppStartedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerContainerFinishedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerEvent;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class LogAggregationService extends AbstractService implements
    LogHandler {

  private static final Log LOG = LogFactory
      .getLog(LogAggregationService.class);

  /*
   * Expected deployment TLD will be 1777, owner=<NMOwner>, group=<NMGroup -
   * Group to which NMOwner belongs> App dirs will be created as 770,
   * owner=<AppOwner>, group=<NMGroup>: so that the owner and <NMOwner> can
   * access / modify the files.
   * <NMGroup> should obviously be a limited access group.
   */
  /**
   * Permissions for the top level directory under which app directories will be
   * created.
   */
  private static final FsPermission TLDIR_PERMISSIONS = FsPermission
      .createImmutable((short) 01777);
  /**
   * Permissions for the Application directory.
   */
  private static final FsPermission APP_DIR_PERMISSIONS = FsPermission
      .createImmutable((short) 0770);

  private final Context context;
  private final DeletionService deletionService;
  private final Dispatcher dispatcher;

  private LocalDirsHandlerService dirsHandler;
  Path remoteRootLogDir;
  String remoteRootLogDirSuffix;
  private NodeId nodeId;

  private final ConcurrentMap<ApplicationId, AppLogAggregator> appLogAggregators;

  private final ExecutorService threadPool;

  public LogAggregationService(Dispatcher dispatcher, Context context,
      DeletionService deletionService, LocalDirsHandlerService dirsHandler) {
    super(LogAggregationService.class.getName());
    this.dispatcher = dispatcher;
    this.context = context;
    this.deletionService = deletionService;
    this.dirsHandler = dirsHandler;
    this.appLogAggregators =
        new ConcurrentHashMap<ApplicationId, AppLogAggregator>();
    this.threadPool = Executors.newCachedThreadPool(
        new ThreadFactoryBuilder()
          .setNameFormat("LogAggregationService #%d")
          .build());
  }

  protected void serviceInit(Configuration conf) throws Exception {
    this.remoteRootLogDir =
        new Path(conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
            YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR));
    this.remoteRootLogDirSuffix =
        conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR_SUFFIX,
            YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR_SUFFIX);

    super.serviceInit(conf);
  }

  @Override
  protected void serviceStart() throws Exception {
    // NodeId is only available during start, the following cannot be moved
    // anywhere else.
    this.nodeId = this.context.getNodeId();
    super.serviceStart();
  }

  @Override
  protected void serviceStop() throws Exception {
    LOG.info(this.getName() + " waiting for pending aggregation during exit");
    stopAggregators();
    super.serviceStop();
  }

  private void stopAggregators() {
    threadPool.shutdown();
    // politely ask to finish
    for (AppLogAggregator aggregator : appLogAggregators.values()) {
      aggregator.finishLogAggregation();
    }
    while (!threadPool.isTerminated()) { // wait for all threads to finish
      for (ApplicationId appId : appLogAggregators.keySet()) {
        LOG.info("Waiting for aggregation to complete for " + appId);
      }
      try {
        if (!threadPool.awaitTermination(30, TimeUnit.SECONDS)) {
          threadPool.shutdownNow(); // send interrupt to hurry them along
        }
      } catch (InterruptedException e) {
        LOG.warn("Aggregation stop interrupted!");
        break;
      }
    }
    for (ApplicationId appId : appLogAggregators.keySet()) {
      LOG.warn("Some logs may not have been aggregated for " + appId);
    }
  }

  protected FileSystem getFileSystem(Configuration conf) throws IOException {
    return FileSystem.get(conf);
  }

  void verifyAndCreateRemoteLogDir(Configuration conf) {
    // Checking the existence of the TLD
    FileSystem remoteFS = null;
    try {
      remoteFS = getFileSystem(conf);
    } catch (IOException e) {
      throw new YarnRuntimeException("Unable to get Remote FileSystem instance", e);
    }
    boolean remoteExists = true;
    try {
      FsPermission perms =
          remoteFS.getFileStatus(this.remoteRootLogDir).getPermission();
      if (!perms.equals(TLDIR_PERMISSIONS)) {
        LOG.warn("Remote Root Log Dir [" + this.remoteRootLogDir
            + "] already exist, but with incorrect permissions. "
            + "Expected: [" + TLDIR_PERMISSIONS + "], Found: [" + perms
            + "]." + " The cluster may have problems with multiple users.");
      }
    } catch (FileNotFoundException e) {
      remoteExists = false;
    } catch (IOException e) {
      throw new YarnRuntimeException(
          "Failed to check permissions for dir ["
              + this.remoteRootLogDir + "]", e);
    }
    if (!remoteExists) {
      LOG.warn("Remote Root Log Dir [" + this.remoteRootLogDir
          + "] does not exist. Attempting to create it.");
      try {
        Path qualified =
            this.remoteRootLogDir.makeQualified(remoteFS.getUri(),
                remoteFS.getWorkingDirectory());
        remoteFS.mkdirs(qualified, new FsPermission(TLDIR_PERMISSIONS));
        remoteFS.setPermission(qualified, new FsPermission(TLDIR_PERMISSIONS));
      } catch (IOException e) {
        throw new YarnRuntimeException("Failed to create remoteLogDir ["
            + this.remoteRootLogDir + "]", e);
      }
    }
  }

  Path getRemoteNodeLogFileForApp(ApplicationId appId, String user) {
    return LogAggregationUtils.getRemoteNodeLogFileForApp(
        this.remoteRootLogDir, appId, user, this.nodeId,
        this.remoteRootLogDirSuffix);
  }

  private void createDir(FileSystem fs, Path path, FsPermission fsPerm)
      throws IOException {
    FsPermission dirPerm = new FsPermission(fsPerm);
    fs.mkdirs(path, dirPerm);
    FsPermission umask = FsPermission.getUMask(fs.getConf());
    if (!dirPerm.equals(dirPerm.applyUMask(umask))) {
      fs.setPermission(path, new FsPermission(fsPerm));
    }
  }

  private boolean checkExists(FileSystem fs, Path path, FsPermission fsPerm)
      throws IOException {
    boolean exists = true;
    try {
      FileStatus appDirStatus = fs.getFileStatus(path);
      if (!APP_DIR_PERMISSIONS.equals(appDirStatus.getPermission())) {
        fs.setPermission(path, APP_DIR_PERMISSIONS);
      }
    } catch (FileNotFoundException fnfe) {
      exists = false;
    }
    return exists;
  }

  protected void createAppDir(final String user, final ApplicationId appId,
      UserGroupInformation userUgi) {
    try {
      userUgi.doAs(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          try {
            // TODO: Reuse FS for user?
            FileSystem remoteFS = getFileSystem(getConfig());

            // Only creating directories if they are missing to avoid
            // unnecessary load on the filesystem from all of the nodes
            Path appDir = LogAggregationUtils.getRemoteAppLogDir(
                LogAggregationService.this.remoteRootLogDir, appId, user,
                LogAggregationService.this.remoteRootLogDirSuffix);
            appDir = appDir.makeQualified(remoteFS.getUri(),
                remoteFS.getWorkingDirectory());

            if (!checkExists(remoteFS, appDir, APP_DIR_PERMISSIONS)) {
              Path suffixDir = LogAggregationUtils.getRemoteLogSuffixedDir(
                  LogAggregationService.this.remoteRootLogDir, user,
                  LogAggregationService.this.remoteRootLogDirSuffix);
              suffixDir = suffixDir.makeQualified(remoteFS.getUri(),
                  remoteFS.getWorkingDirectory());

              if (!checkExists(remoteFS, suffixDir, APP_DIR_PERMISSIONS)) {
                Path userDir = LogAggregationUtils.getRemoteLogUserDir(
                    LogAggregationService.this.remoteRootLogDir, user);
                userDir = userDir.makeQualified(remoteFS.getUri(),
                    remoteFS.getWorkingDirectory());

                if (!checkExists(remoteFS, userDir, APP_DIR_PERMISSIONS)) {
                  createDir(remoteFS, userDir, APP_DIR_PERMISSIONS);
                }

                createDir(remoteFS, suffixDir, APP_DIR_PERMISSIONS);
              }

              createDir(remoteFS, appDir, APP_DIR_PERMISSIONS);
            }
          } catch (IOException e) {
            LOG.error("Failed to setup application log directory for "
                + appId, e);
            throw e;
          }
          return null;
        }
      });
    } catch (Exception e) {
      throw new YarnRuntimeException(e);
    }
  }

  @SuppressWarnings("unchecked")
  private void initApp(final ApplicationId appId, String user,
      Credentials credentials, ContainerLogsRetentionPolicy logRetentionPolicy,
      Map<ApplicationAccessType, String> appAcls) {
    ApplicationEvent eventResponse;
    try {
      verifyAndCreateRemoteLogDir(getConfig());
      initAppAggregator(appId, user, credentials, logRetentionPolicy, appAcls);
      eventResponse = new ApplicationEvent(appId,
          ApplicationEventType.APPLICATION_LOG_HANDLING_INITED);
    } catch (YarnRuntimeException e) {
      LOG.warn("Application failed to init aggregation", e);
      eventResponse = new ApplicationEvent(appId,
          ApplicationEventType.APPLICATION_LOG_HANDLING_FAILED);
    }
    this.dispatcher.getEventHandler().handle(eventResponse);
  }

  protected void initAppAggregator(final ApplicationId appId, String user,
      Credentials credentials, ContainerLogsRetentionPolicy logRetentionPolicy,
      Map<ApplicationAccessType, String> appAcls) {

    // Get user's FileSystem credentials
    final UserGroupInformation userUgi =
        UserGroupInformation.createRemoteUser(user);
    if (credentials != null) {
      userUgi.addCredentials(credentials);
    }

    // New application
    final AppLogAggregator appLogAggregator =
        new AppLogAggregatorImpl(this.dispatcher, this.deletionService,
            getConfig(), appId, userUgi, dirsHandler,
            getRemoteNodeLogFileForApp(appId, user), logRetentionPolicy,
            appAcls);
    if (this.appLogAggregators.putIfAbsent(appId, appLogAggregator) != null) {
      throw new YarnRuntimeException("Duplicate initApp for " + appId);
    }
    // wait until check for existing aggregator to create dirs
    try {
      // Create the app dir
      createAppDir(user, appId, userUgi);
    } catch (Exception e) {
      appLogAggregators.remove(appId);
      closeFileSystems(userUgi);
      if (!(e instanceof YarnRuntimeException)) {
        e = new YarnRuntimeException(e);
      }
      throw (YarnRuntimeException)e;
    }

    // TODO Get the user configuration for the list of containers that need log
    // aggregation.

    // Schedule the aggregator.
    Runnable aggregatorWrapper = new Runnable() {
      public void run() {
        try {
          appLogAggregator.run();
        } finally {
          appLogAggregators.remove(appId);
          closeFileSystems(userUgi);
        }
      }
    };
    this.threadPool.execute(aggregatorWrapper);
  }

  protected void closeFileSystems(final UserGroupInformation userUgi) {
    try {
      FileSystem.closeAllForUGI(userUgi);
    } catch (IOException e) {
      LOG.warn("Failed to close filesystems: ", e);
    }
  }

  // for testing only
  @Private
  int getNumAggregators() {
    return this.appLogAggregators.size();
  }

  private void stopContainer(ContainerId containerId, int exitCode) {

    // A container is complete. Put this containers' logs up for aggregation if
    // this containers' logs are needed.

    AppLogAggregator aggregator = this.appLogAggregators.get(
        containerId.getApplicationAttemptId().getApplicationId());
    if (aggregator == null) {
      LOG.warn("Log aggregation is not initialized for " + containerId
          + ", did it fail to start?");
      return;
    }
    aggregator.startContainerLogAggregation(containerId, exitCode == 0);
  }

  private void stopApp(ApplicationId appId) {

    // App is complete. Finish up any containers' pending log aggregation and
    // close the application specific logFile.

    AppLogAggregator aggregator = this.appLogAggregators.get(appId);
    if (aggregator == null) {
      LOG.warn("Log aggregation is not initialized for " + appId
          + ", did it fail to start?");
      return;
    }
    aggregator.finishLogAggregation();
  }

  @Override
  public void handle(LogHandlerEvent event) {
    switch (event.getType()) {
      case APPLICATION_STARTED:
        LogHandlerAppStartedEvent appStartEvent =
            (LogHandlerAppStartedEvent) event;
        initApp(appStartEvent.getApplicationId(), appStartEvent.getUser(),
            appStartEvent.getCredentials(),
            appStartEvent.getLogRetentionPolicy(),
            appStartEvent.getApplicationAcls());
        break;
      case CONTAINER_FINISHED:
        LogHandlerContainerFinishedEvent containerFinishEvent =
            (LogHandlerContainerFinishedEvent) event;
        stopContainer(containerFinishEvent.getContainerId(),
            containerFinishEvent.getExitCode());
        break;
      case APPLICATION_FINISHED:
        LogHandlerAppFinishedEvent appFinishedEvent =
            (LogHandlerAppFinishedEvent) event;
        stopApp(appFinishedEvent.getApplicationId());
        break;
      default:
        ; // Ignore
    }

  }
}


text:
{% load staticfiles %}
<!DOCTYPE html>

        <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">

Specific schedule Views

            {% if specificdatetime_list %}

                    Start Date/Time

            {% for specificdatetime in specificdatetime_list %}

                        {{ specificdatetime.start_datetime }}
                        edit

                            <form method="POST" action="{% url 'delete_spec_date_time' spec_date_time.pk %}">
                                {% csrf_token %}
                                <input type="submit" class="btn btn-sm btn-danger" value="delete">
                            </form>

                {% endfor %}

            {% endif %}

Create a new specific date time schedule


text:
const app = document.getElementById('app')

app.innerHTML =
  'This is an app in the template.

' +
  'Some variables from your webpack.config.js:
' +
  'title: ' + document.title + '
' +
  'window.env.apiHost: ' + window.env.apiHost


text:
from . import restart_driver

__all__ = ['restart_driver']


text:
<?php

namespace app\controllers;

use Yii;
use app\models\TinTuc;
use app\models\TinTucSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * TinTucController implements the CRUD actions for TinTuc model.
 */
class TinTucController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all TinTuc models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TinTucSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single TinTuc model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new TinTuc model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new TinTuc();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing TinTuc model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing TinTuc model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the TinTuc model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return TinTuc the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = TinTuc::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
#include <vector>
#include <cmath>
#include <string>

using std::vector;
using std::pair;
using std::string;

/* converts vector of gains to corresponding column indices in obs matrix */
vector<int> gains2indices(vector<int>& gains);

/* Finds relative theta, and puts into range [0,35] */
int calculate_theta_rel(vector<int>& theta_rel, vector<double>& theta_v, int theta_j);

/* Creates the observation matrix (theta_rel by rssi) */
vector<vector<double> > make_obs_matrix();

int gains2normgain(int dir_gain, int omni_gain);
int gains2normgain(double dir_gain, double omni_gain);

/**
 * Actual methods to get bearing:
 *  MLE
 *  Bayesian
 *  cc_norm (cross-correlation of normalized)
 *  cc (cross-correlation, only after full rotation)
 *  max (angle at max rssi value received)
 */
double get_bearing_mle(vector<double>& theta_v, vector<int>& gains, vector<vector<double> >& obs_matrix);
double get_bearing_mle(vector<double>& theta_v, vector<int>& gains);

double get_bearing_bayes(vector<double>& theta_v, vector<int>& gains, vector<vector<double> >& obs_matrix);

double get_bearing_cc(vector<double> &angles, vector<double> &gains);

double get_bearing_max(vector<double> &angles, vector<double> &gains);
double get_bearing_max3(vector<double> &angles, vector<double> &gains);

pair<vector<double>, vector<double> > get_gains(string filename);

bool validgain(double gain);


text:
namespace Microsoft.ApplicationInsights.TraceListener.Tests
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Reflection;
    using Microsoft.ApplicationInsights.CommonTestShared;
    using Microsoft.ApplicationInsights.DataContracts;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.Extensibility.Implementation;
    using Microsoft.ApplicationInsights.Tracing.Tests;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using static System.Globalization.CultureInfo;

    [TestClass]
    public sealed class ApplicationInsightsTraceListenerTests : IDisposable
    {
        private readonly AdapterHelper adapterHelper = new AdapterHelper();

        public TestContext TestContext { get; set; }

        public void Dispose()
        {
            this.adapterHelper.Dispose();
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerInitializeDoesNotThrowWhenInstrumentationKeyIsNull()
        {
            var listener = new ApplicationInsightsTraceListener(null);
            listener.Dispose();
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerInitializeTDoesNoThrowWhenInstrumentationKeyIsEmpty()
        {
            var listener = new ApplicationInsightsTraceListener(string.Empty);
            listener.Dispose();
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerWriteUsedApplicationInsightsConfigInstrumentationKeyWhenUnspecifiedInstrumentationKey()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.InstrumentationKey = this.adapterHelper.InstrumentationKey;

            // Changing the channel to Mock channel to verify
            // the Telemetry event is assigned with the InstrumentationKey from configuration
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(null))
            {
                this.VerifyMessagesInMockChannel(listener, this.adapterHelper.InstrumentationKey);
            }
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerWriteNotUsingAppliocationInsightsConfigInstrumentationKeyWhenspecifiedInstrumentationKey()
        {
            // Changing the channel to Mock channel to verify
            // the Telemetry event is assigned with the InstrumentationKey from configuration
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete
            string instrumentationKey = Guid.NewGuid().ToString();

            using (var listener = new ApplicationInsightsTraceListener(instrumentationKey))
            {
                this.VerifyMessagesInMockChannel(listener, instrumentationKey);
            }
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerWriteLineUseApplicationEventSourceToLogMessage()
        {
            // Changing the channel to Mock channel to verify
            // the Telemetry event is assigned with the InstrumentationKey from configuration
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                var expectedMessage = "A Message to write line";
                listener.WriteLine(expectedMessage);

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();
                Assert.AreEqual(expectedMessage, telemetry.Message);
                Assert.IsFalse(telemetry.Properties.ContainsKey("EventId"));
                Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
            }
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void SdkVersionIsCorrect()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                listener.WriteLine("A Message to write line");

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();

                string expectedVersion = SdkVersionHelper.GetExpectedSdkVersion(prefix: "sd:", loggerType: typeof(ApplicationInsightsTraceListener));
                Assert.AreEqual(expectedVersion, telemetry.Context.GetInternalContext().SdkVersion);
            }
        }

        [TestMethod]
        [Ignore]
        [TestCategory("TraceListener")]
        public void TelemetryIsAcceptedByValidateEndpoint()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                listener.WriteLine("A Message to write line");

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();

                Assert.IsNull(TelemetrySender.ValidateEndpointSend(telemetry));
            }
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerTraceEventWithMessage()
        {
            TraceOptions options = TraceOptions.Timestamp;
            var expectedTraceEventType = TraceEventType.Information;
            var expectedMessage = "A simple message";
            var expectedEventId = 3;

            this.ValidateASingleMessageActionBased(
                (ApplicationInsightsTraceListener listener, TraceEventCache cache) =>
                listener.TraceEvent(cache, this.TestContext.TestName, expectedTraceEventType, expectedEventId, expectedMessage),
                this.adapterHelper.InstrumentationKey,
                options);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(expectedMessage, telemetry.Message);
            Assert.AreEqual(expectedEventId.ToString(InvariantCulture), telemetry.Properties["EventId"]);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerTraceEventWithFormat()
        {
            TraceOptions options = TraceOptions.Timestamp;
            var formatString = "{0} event";
            int arg0 = 1;
            var expectedTraceEventType = TraceEventType.Information;
            var expectedEventId = 3;

            this.ValidateASingleMessageActionBased(
                (ApplicationInsightsTraceListener listener, TraceEventCache cache) =>
                listener.TraceEvent(cache, this.TestContext.TestName, expectedTraceEventType, expectedEventId, formatString, arg0),
                this.adapterHelper.InstrumentationKey,
                options);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(string.Format(InvariantCulture, formatString, arg0), telemetry.Message);
            Assert.AreEqual(expectedEventId.ToString(InvariantCulture), telemetry.Properties["EventId"]);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceDataStoresDataConvertedToStringInTraceMessage()
        {
            object expectedData = new Tuple<int, double>(123, 123.456);
            TraceOptions options = TraceOptions.Timestamp;
            var expectedTraceEventType = TraceEventType.Information;
            var expectedEventId = 3;

            this.ValidateASingleMessageActionBased(
                (ApplicationInsightsTraceListener listener, TraceEventCache cache) =>
                listener.TraceData(cache, "hello", expectedTraceEventType, expectedEventId, expectedData),
                this.adapterHelper.InstrumentationKey,
                options);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual("(123, 123.456)", telemetry.Message);
            Assert.AreEqual(expectedEventId.ToString(InvariantCulture), telemetry.Properties["EventId"]);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerStoresDataItemsConvertedToStringInTraceMessage()
        {
            object[] expectedData = new object[] { new Tuple<int, double>(123, 123.456), new Uri("https://foobar") };
            TraceOptions options = TraceOptions.Timestamp;
            var expectedTraceEventType = TraceEventType.Information;
            var expectedEventId = 3;

            this.ValidateASingleMessageActionBased(
                (ApplicationInsightsTraceListener listener, TraceEventCache cache) =>
                listener.TraceData(cache, "hello", expectedTraceEventType, expectedEventId, expectedData),
                this.adapterHelper.InstrumentationKey,
                options);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual("(123, 123.456), https://foobar/", telemetry.Message);
            Assert.AreEqual(expectedEventId.ToString(InvariantCulture), telemetry.Properties["EventId"]);
        }

#if NET45
        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsResumeAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Resume, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsStartAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Start, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsStopAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Stop, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsSuspendAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Suspend, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsTransferAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Transfer, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }
#endif

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsVerboseAsVerbose()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Verbose, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Verbose, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsInformationAsInformation()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Information, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Information, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsWarningAsWarning()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Warning, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Warning, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsErrorAsError()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Error, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Error, telemetry.SeverityLevel);
        }

        [TestMethod]
        [TestCategory("TraceListener")]
        public void TraceListenerSendsCriticalAsCritical()
        {
            this.ValidateASingleMessageActionBased(
                (listener, cache) => listener.TraceData(cache, "hello", TraceEventType.Critical, 3),
                this.adapterHelper.InstrumentationKey,
                TraceOptions.Timestamp);

            TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
            Assert.AreEqual(SeverityLevel.Critical, telemetry.SeverityLevel);
        }

        [TestMethod]
        public void TraceEventDoesNotThrowArgumentNullExceptionWhenArgsIsNull()
        {
            var source = new TraceSource("Test", SourceLevels.All);
            source.Listeners.Add(new ApplicationInsightsTraceListener());
            source.TraceInformation("TestMessage");
        }

#if NET45
        [TestMethod]
        public void TraceEventDoesNotStoreLogicalOperationStackInTelemetryPropertiesBecauseLongValuesAreRejected()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
            var listener = new ApplicationInsightsTraceListener();
            listener.TraceOutputOptions = TraceOptions.LogicalOperationStack;

            Trace.CorrelationManager.StartLogicalOperation(42);
            listener.TraceEvent(new TraceEventCache(), string.Empty, TraceEventType.Information, default(int));

            var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.Single();
            Assert.IsFalse(telemetry.Properties.ContainsKey("LogicalOperationStack"));
        }

        [TestMethod]
        public void TraceEventDoesNotStoreCallStackInTelemetryPropertiesBecauseLongValuesAreRejected()
        {
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
            var listener = new ApplicationInsightsTraceListener();
            listener.TraceOutputOptions = TraceOptions.Callstack;

            listener.TraceEvent(new TraceEventCache(), string.Empty, TraceEventType.Information, default(int));

            var telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.Single();
            Assert.IsFalse(telemetry.Properties.ContainsKey("CallStack"));
        }
#endif

        [TestMethod]
        public void TraceListenerFlushesChannel()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(Guid.NewGuid().ToString()))
            {
                try
                {
                    listener.Flush();
                    Assert.Fail();
                }
                catch (Exception ex)
                {
                    Assert.AreEqual("Flush called", ex.Message);
                }
            }
        }

        private void ValidateASingleMessageActionBased(
            Action<ApplicationInsightsTraceListener, TraceEventCache> callTraceAction,
            string instrumentationKey,
            TraceOptions options)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            TelemetryConfiguration.Active.TelemetryChannel = this.adapterHelper.Channel;
#pragma warning restore CS0618 // Type or member is obsolete

            using (var listener = new ApplicationInsightsTraceListener(instrumentationKey))
            {
                listener.TraceOutputOptions = options;
                TraceEventCache traceEventCache = new TraceEventCache();
#if NET45
                PrivateObject privateObject = new PrivateObject(traceEventCache);
                privateObject.SetField("timeStamp", DateTime.Now.Ticks);
                privateObject.SetField("stackTrace", "Environment.StackTrace");
#else
                TypeInfo traceEventCacheType = traceEventCache.GetType().GetTypeInfo();
                traceEventCacheType.GetDeclaredField("_timeStamp").SetValue(traceEventCache, DateTime.Now.Ticks);
#endif
                callTraceAction(listener, traceEventCache);

                TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.FirstOrDefault();
                Assert.IsNotNull(telemetry, "didn't got the event trace to the inner channel");
                Assert.AreEqual(telemetry.Context.InstrumentationKey, instrumentationKey);
            }
        }

        private void VerifyMessagesInMockChannel(
            ApplicationInsightsTraceListener aiListener,
            string instrumentationKey)
        {
            aiListener.Write("Sample Write message");
            aiListener.WriteLine("Sample WriteLine message");
            aiListener.TraceEvent(new TraceEventCache(), "Sample TraceEvent", TraceEventType.Error, 0);
            aiListener.TraceData(new TraceEventCache(), "Sample warning message GUID:{0}", TraceEventType.Information, 0, Guid.NewGuid());

            AdapterHelper.ValidateChannel(this.adapterHelper, instrumentationKey, 4);
        }
    }
}


text:
package com.github.deprecated.testng.listeners;

import java.util.List;

import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.reporters.XMLReporter;
import org.testng.xml.XmlSuite;
import com.github.deprecated.utils.DateUtils;
import com.github.deprecated.utils.FileUtils;

public class ReporterListener implements IReporter {

    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
                               String outputDirectory) {

        // 设置reportng,html报告可插入链接
        System.setProperty("org.uncommons.reportng.escape-output", "false");
        FileUtils.createNewFile(outputDirectory + "\\testng-results.xml");
        // 生成reportng html报告
        new HTMLReporter().generateReport(xmlSuites, suites, outputDirectory);
        new XMLReporter().generateReport(xmlSuites, suites, outputDirectory);
        FileUtils.waitFor(outputDirectory + "\\html\\index.html", 10);

        String cpDir = String.format("logs\\Reports\\%s_%s", DateUtils.format("yyyy-MM-dd_HH-mm-ss"),
                xmlSuites.get(0).getName());
        // 报告存储至日志目录
        FileUtils.copyDirectory(outputDirectory, cpDir);

    }

}