text:
"""Central place for the XML generation"""
import os
import sys
import xml.dom.minidom
import numpy as np
try:
    import astropy.io.fits as fits
except ImportError:
    import pyfits as fits
from enrico import utils
import enrico.environ as env
from enrico.environ import CATALOG_TEMPLATE_DIR, TAG_ISO
from os.path import join

def addParameter(el, name, free, value, scale, min, max):
    """Add a parameter to a source"""
    doc = el.ownerDocument
    param = doc.createElement('parameter')
    param.setAttribute('name', name)
    param.setAttribute('free', '%d' % free)
    param.setAttribute('scale', '%g' % scale)
    # if value outside limits, set it to the closest limit
    if value>max:
        print(('Parameter {2} value outside limits {0}>{1}, clipping.'.format(value,max,name)))
        value=max
    if value<min:
        print(('Parameter {2} value outside limits {0}<{1}, clipping.'.format(value,min,name)))
        value=min
    param.setAttribute('value', '%g' % value)
    param.setAttribute('max', '%g' % max)
    param.setAttribute('min', '%g' % min)
    el.appendChild(param)

def addDiffusePL(lib, file, free=1, value=1.0, max=10.0, min=1.0,
               name='iso_p7v6source'):
    """Add the diffuse extragalactic diffuse"""
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    spec.setAttribute('file', file)
    spec.setAttribute('type', 'FileFunction')
    spec.setAttribute('apply_edisp', 'false')
    addParameter(spec, 'Normalization', free, 1, 1, 0.001, 1000)
    src.appendChild(spec)
    spatial = doc.createElement('spatialModel')
    spatial.setAttribute('type', 'ConstantValue')
    addParameter(spatial, 'Value', 0, 1, 1.0, 0.0, 10.0)
    src.appendChild(spatial)
    lib.appendChild(src)

def addGalprop(lib, file, free=1, value=1.0, scale=1.0, max=10.0, min=.010,
               name='gal_2yearp7v6_v0'):
    """Add the diffuse galactic diffuse"""
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    spec.setAttribute('type', 'ConstantValue')
    addParameter(spec, 'Value', free, value, scale, min, max)
    src.appendChild(spec)
    spatial = doc.createElement('spatialModel')
    spatial.setAttribute('file', file)
    spatial.setAttribute('type', 'MapCubeFunction')
    addParameter(spatial, 'Normalization', 0, 1, 1, 0.001, 1000)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPowerLaw1(lib, name, ra, dec, ebl=None, eflux=0, emin=200, emax=3e5,
                   flux_free=1, flux_value=1e-9, flux_scale=0,
                   flux_max=10000.0, flux_min=0,
                   index_free=1, index_value=-2.0,
                   index_min=-6.0, index_max=-0.5,extendedName=""):
    """Add a source with a POWERLAW1 model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')

    try:
        spec.setAttribute('type', 'EblAtten::PowerLaw')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PowerLaw')

    addParameter(spec, 'Prefactor',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'Index', index_free, index_value, 1.0,
                 index_min, index_max)
    addParameter(spec, 'Scale', 0, eflux, 1.0, elim_min, elim_max)
    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPowerLaw2(lib, name, ra, dec, ebl=None, emin=200, emax=3e5,
                   flux_free=1, flux_value=1.6e-8, flux_scale=0,
                   flux_max=10000.0, flux_min=0,
                   index_free=1, index_value=-2.0,
                   index_min=-5.0, index_max=-0.5,extendedName=""):
    """Add a source with a POWERLAW2 model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::PowerLaw2')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PowerLaw2')
    addParameter(spec, 'Integral',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'Index', index_free, index_value, 1.0,
                 index_min, index_max)
    addParameter(spec, 'LowerLimit', 0, emin, 1.0, elim_min, elim_max)
    addParameter(spec, 'UpperLimit', 0, emax, 1.0, elim_min, elim_max)
    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSLogparabola(lib, name, ra, dec, ebl=None, enorm=1000, emin=200, emax=3e5,
                   norm_free=1, norm_value=1e-9, norm_scale=0,
                   norm_max=10000.0, norm_min=0,
                   alpha_free=1, alpha_value=1.0,
                   alpha_min=.5, alpha_max=3.,
                   beta_free=1, beta_value=1.0,
                   beta_min=0, beta_max=1.0,extendedName=""):
    """Add a source with a LOGPARABOLA model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax

    if enorm == 0:
        enorm = 2e5  # meanEnergy(emin,emax,index_value)
        norm_value *= (enorm / 100.0) ** alpha_value
    if norm_scale == 0:
        norm_scale = utils.fluxScale(norm_value)
    norm_value /= norm_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::LogParabola')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'LogParabola')
    addParameter(spec, 'norm',
                 norm_free, norm_value, norm_scale, norm_min, norm_max)
    addParameter(spec, 'alpha', alpha_free, alpha_value, 1.0,
                 alpha_min, alpha_max)
    addParameter(spec, 'Eb', 0, enorm, 1.0, elim_min, elim_max)
    addParameter(spec, 'beta', beta_free, beta_value, 1.0, beta_min, beta_max)
    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSBrokenPowerLaw2(lib, name, ra, dec, ebl=None, emin=200, emax=100000,
                         ebreak_free=1, ebreak=1000, ebreak_min=200, ebreak_max=100000,
                         flux_free=1, flux_value=1.6, flux_scale=1e-6,
                         flux_max=10000.0, flux_min=0,
                         index_lo_free=1, index_lo_value=-2.0,
                         index_lo_min=-5.0, index_lo_max=-1.0,
                         index_hi_free=1, index_hi_value=-4.0,
                         index_hi_min=-5.0, index_hi_max=-1.0,extendedName=""):
    """Add a source with a BROKENPOWERLAW2 model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if ebreak_min == 0:
        ebreak_min = emin
    if ebreak_max == 0:
        ebreak_max = emax
    if ebreak == 0:
        ebreak = np.sqrt(ebreak_min * ebreak_max)
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::BrokenPowerLaw2')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'BrokenPowerLaw2')
    addParameter(spec, 'Integral',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'Index1',
                 index_lo_free, index_lo_value, 1.0,
                 index_lo_min, index_lo_max)
    addParameter(spec, 'Index2',
                 index_hi_free, index_hi_value, 1.0,
                 index_hi_min, index_hi_max)
    addParameter(spec, 'BreakValue',
                 ebreak_free, ebreak, 1.0, ebreak_min, ebreak_max)
    addParameter(spec, 'LowerLimit', 0, emin, 1.0, elim_min, elim_max)
    addParameter(spec, 'UpperLimit', 0, emax, 1.0, elim_min, elim_max)
    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPLSuperExpCutoff(lib, name, ra, dec, ebl=None, eflux=0, emin=200, emax=3e5,
                   flux_free=1, flux_value=1e-9, flux_scale=0,
                   flux_max=10000.0, flux_min=0,
                   index1_free=1, index1_value=-2.0,
                   index1_min=-5.0, index1_max=-0.,
                   cutoff_free=1, cutoff_value=1e4,
                   cutoff_min=20, cutoff_max=3.1e5,
                   index2_free=0, index2_value=1.0,
                   index2_min=0.0, index2_max=5.0,extendedName=""):
    """Add a source with a SUPEREXPCUTOFF model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::PLSuperExpCutoff')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PLSuperExpCutoff')
    addParameter(spec, 'Prefactor',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'Index1', index1_free, index1_value, 1.0,
                 index1_min, index1_max)
    addParameter(spec, 'Scale', 0, eflux, 1.0, elim_min, elim_max)
    addParameter(spec, 'Cutoff', cutoff_free, cutoff_value, 1.0,
                 cutoff_min, cutoff_max)
    addParameter(spec, 'Index2', index2_free, index2_value, 1.0,
                 index2_min, index2_max)

    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPLSuperExpCutoff2(lib, name, ra, dec, ebl=None, eflux=0, emin=200, emax=3e5,
                   flux_free=1, flux_value=10.976, flux_scale=1e-11,
                   flux_max=1000.0, flux_min=0,
                   index1_free=1, index1_value=-1.436,
                   index1_min=-5.0, index1_max=1.5,
                   expfac_free=1, expfac_value=0.001,
                   expfac_min=-1, expfac_max=1,
                   index2_free=0, index2_value=1.0,
                   index2_min=0.0, index2_max=5.0,extendedName=""):
    """Add a source with a SUPEREXPCUTOFF model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::PLSuperExpCutoff2')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PLSuperExpCutoff2')
    addParameter(spec, 'Prefactor',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'Index1', index1_free, index1_value, 1.0,
                 index1_min, index1_max)
    addParameter(spec, 'Scale', 0, eflux, 1.0, elim_min, elim_max)
    addParameter(spec, 'Expfactor', expfac_free, expfac_value, 1.0,
                 expfac_min, expfac_max)
    addParameter(spec, 'Index2', index2_free, index2_value, 1.0,
                 index2_min, index2_max)

    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPLSuperExpCutoff3(lib, name, ra, dec, ebl=None, eflux=0, emin=200, emax=3e5,
                   flux_free=1, flux_value=1e-9, flux_scale=0,
                   flux_max=10000.0, flux_min=0,
                   index1_free=1, index1_value=-1.7,
                   index1_min=-5, index1_max=1.5,
                   expfac2_free=1, expfac2_value=2,
                   expfac2_min=0, expfac2_max=10,
                   index2_free=0, index2_value=1.0,
                   index2_min=0.0, index2_max=2.0,extendedName=""):
    """Add a source with a SUPEREXPCUTOFF model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::PLSuperExpCutoff3')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PLSuperExpCutoff3')
    addParameter(spec, 'Prefactor',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'IndexS', index1_free, index1_value, 1.0,
                 index1_min, index1_max)
    addParameter(spec, 'Scale', 0, eflux, 1.0, elim_min, elim_max)
    addParameter(spec, 'Expfactor2', expfac2_free, expfac2_value, 1.0,
                 expfac2_min, expfac2_max)
    addParameter(spec, 'Index2', index2_free, index2_value, 1.0,
                 index2_min, index2_max)

    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def addPSPLSuperExpCutoff4(lib, name, ra, dec, ebl=None, eflux=0, emin=200, emax=3e5,
                   flux_free=1, flux_value=1, flux_scale=1e-11,
                   flux_max=1000.0, flux_min=1e-5,
                   indexS_free=1, indexS_value=-1.7,
                   indexS_min=-5.0, indexS_max=0.,
                   expfacS_free=1, expfacS_value=0.4,
                   expfacS_min=0, expfacS_max=5,
                   index2_free=0, index2_value=0.66,
                   index2_min=-0.5, index2_max=2.0,extendedName=""):
    """Add a source with a SUPEREXPCUTOFF model"""
    elim_min = 30
    elim_max = 300000
    if emin < elim_min:
        elim_min = emin
    if emax > elim_max:
        elim_max = emax
    if flux_scale == 0:
        flux_scale = utils.fluxScale(flux_value)
    flux_value /= flux_scale
    doc = lib.ownerDocument
    src = doc.createElement('source')
    src.setAttribute('name', name)
    if extendedName=="":
      src.setAttribute('type', 'PointSource')
    else:
      src.setAttribute('type', 'DiffuseSource')
    spec = doc.createElement('spectrum')
    try:
        spec.setAttribute('type', 'EblAtten::PLSuperExpCutoff4')
        addParameter(spec, 'tau_norm', ebl['free_tau_norm'], ebl['tau_norm'], 1.0, 0, 2.5)
        addParameter(spec, 'redshift', ebl['free_redshift'], ebl['redshift'], 1.0, 0, 5)
        addParameter(spec, 'ebl_model', 0, ebl['model'], 1.0, 0, 20)
    except TypeError as NameError:
        spec.setAttribute('type', 'PLSuperExpCutoff4')
    addParameter(spec, 'Prefactor',
                 flux_free, flux_value, flux_scale, flux_min, flux_max)
    addParameter(spec, 'IndexS', indexS_free, indexS_value, 1.0,
                 indexS_min, indexS_max)
    addParameter(spec, 'Scale', 0, eflux, 1.0, elim_min, elim_max)
    addParameter(spec, 'ExpfactorS', expfacS_free, expfacS_value, 1.0,
                 expfacS_min, expfacS_max)
    addParameter(spec, 'Index2', index2_free, index2_value, 1.0,
                 index2_min, index2_max)

    src.appendChild(spec)
    spatial = AddSpatial(doc,ra,dec,extendedName)
    src.appendChild(spatial)
    lib.appendChild(src)

def AddSpatial(doc,ra,dec,extendedName=""):
    spatial = doc.createElement('spatialModel')
    if extendedName=="":
      spatial.setAttribute('type', 'SkyDirFunction')
      addParameter(spatial, 'RA', 0, ra, 1.0, -360.0, 360.0)
      addParameter(spatial, 'DEC', 0, dec, 1.0, -90.0, 90.0)
    else :
      spatialModel = join(CATALOG_TEMPLATE_DIR, extendedName)
      spatial.setAttribute('type', 'SpatialMap')
      spatial.setAttribute('file', spatialModel)
      addParameter(spatial, 'Prefactor', 1, 1, 1.0, 0.0001,1000)

    return spatial

def GetlistFromFits(config, catalog):
    from enrico import Loggin
    mes = Loggin.Message()
    """Read the config and catalog file and generate the list of sources to include"""
    #Get the informations for the config file
    srcname = config['target']['name']
    ra_src = config['target']['ra']
    dec_src = config['target']['dec']
    redshift = config['target']['redshift']
    ebl_model = config['target']['ebl_model']
    ra_space = config['space']['xref']
    dec_space = config['space']['yref']
    emin = config['energy']['emin']
    max_radius = config['model']['max_radius']
    min_significance_free = config['model']['min_significance_free']
    min_significance_catalog = config['model']['min_significance_catalog']
    model = config['target']['spectrum']

    #Change the roi, legacy std roi
    original_roi = config['space']['rad']
    try:
        roi = config['space']['rad']+config['model']['max_roi']
    except NameError:
        roi = config['space']['rad']+2

    if model == "Generic":
        mes.warning("Generic model found. Will turn it to PowerLaw")
        model = "PowerLaw"

    #read the catalog file
    cfile = fits.open(catalog)
    data = cfile[1].data
    names = data.field('Source_Name')
    ra = data.field('RAJ2000')
    dec = data.field('DEJ2000')
    flux = data.field('PL_Flux_Density')
    pivot = data.field('Pivot_Energy')
    spectype = data.field('SpectrumType')
    is8yr = 'FL8Y' in cfile[1].header['CDS-NAME']
    try :  # valid for the 2FGH, not for the 1FHL
      # if is8yr:
      spectype = data.field('SpectrumType')
      index  = np.zeros(names.size)
      cutoff = 1e5 * np.ones(names.size)
      expind = np.zeros(names.size)
      expfac = np.zeros(names.size)
      beta   = np.zeros(names.size)
      # iterate over each source, check the selected spectrum and get the params.
      for k,spec in enumerate(spectype):
          if spec == 'PowerLaw':
              index[k] = data.field('PL_Index')[k]
          elif spec == 'LogParabola':
              index[k] = data.field('LP_Index')[k]
              beta[k]  = data.field('LP_beta')[k]
          elif spec == 'PLSuperExpCutoff':
              # From the makeFL8Yxml.py script
              try:
                # from 4FGL-DR3
                spectype[k]='PLSuperExpCutoff4'
                index[k]  = data.field('PLEC_IndexS')[k]
                expfac[k] = data.field('PLEC_ExpfactorS')[k]
              except KeyError:
                # before 4FGL-DR3
                spectype[k]='PLSuperExpCutoff2'
                index[k]  = data.field('PLEC_Index')[k]
                expfac[k] = data.field('PLEC_Expfactor')[k]

              expind[k] = data.field('PLEC_Exp_Index')[k]
              if (expfac[k]!=0 and expind[k]!=0): cutoff[k] =(1./expfac[k])**(1./expind[k])

        #cutoff = data.field('Cutoff')
        #beta = data.field('LP_beta')
      # else:
      #   index = data.field('Spectral_Index')
      #   cutoff = data.field('Cutoff')
      #   beta = data.field('beta')
    except :
      raise
      index = data.field('Spectral_Index')
      cutoff = np.zeros(names.size)
      beta = np.zeros(names.size)
      spectype = np.array(names.size*["PowerLaw"])
      pivot *= 1e3 ## energy in the 1FHL are in GeV
      flux *= 1e3

    try :
      extendedName    = data.field('Extended_Source_Name')
      # if is8yr:
      extendedfits    = cfile[2].data.field('Spatial_Filename')
      extendedsrcname = cfile[2].data.field('Source_Name')
      # else:
      #   extendedfits    = cfile[5].data.field('Spatial_Filename')
      #   extendedsrcname = cfile[5].data.field('Source_Name')
    except:
      raise
      mes.warning("Cannot find the extended source list: please check the xml")
      extendedName = np.array(names.size*[""])
      extendedsrcname = []

    sigma = data.field('Signif_Avg')
    sources = []
    Nfree = 0
    Nextended = 0

    parameter_noise = config['model']['parameters_noise']

    #loop over all the sources of the catalog
    for i in range(len(names)):
        #distance from the center of the maps to the given source
        rspace = utils.calcAngSepDeg(float(ra[i]), float(dec[i]), ra_space, dec_space)
        #distance for the target to the given source
        rsrc = utils.calcAngSepDeg(float(ra[i]), float(dec[i]), ra_src, dec_src)

        j=0
        extended_fitsfilename = ""
        for extname in extendedsrcname:
            if extname == extendedName[i]:
                extended_fitsfilename = extendedfits[j]
            j+=1

        if (rsrc < 0.04) or (rsrc<.1 and sigma[i] > min_significance_free): # and extended_fitsfilename=="":
            # if the source has a separation less than 0.1deg to the target and has a reasonable TS
            # or if it is very close (0.04deg, similar to the PSF) regardless of the TS, assume it is our target
            # with our given coordinates and add it with the 4FGL spectral parameters.
            # NOTE: Extended sources as targets are not tested.
            # possibly add gaussian noise to the parameter values

            Nfree += 1
            spectype[i] = model

            if model == 'PowerLaw':
                index[i] = data.field('PL_Index')[i]
            elif model == 'LogParabola':
                index[i] = data.field('LP_Index')[i]
                beta[i]  = data.field('LP_beta')[i]
            elif model == 'PLSuperExpCutoff':
                # From the makeFL8Yxml.py script
                index[i]  = data.field('PLEC_Index')[i]
                try:
                  # from 4FGL-DR3
                  index[i]  = data.field('PLEC_IndexS')[i]
                  expfac[i] = data.field('PLEC_ExpfactorS')[i]
                  spectype[i] = 'PLSuperExpCutoff4'
                except KeyError:
                  # before 4FGL-DR3
                  index[i]  = data.field('PLEC_Index')[i]
                  expfac[i] = data.field('PLEC_Expfactor')[i]
                  spectype[i] = 'PLSuperExpCutoff2'
                expind[i] = data.field('PLEC_Exp_Index')[i]
                if (expfac[i]!=0 and expind[i]!=0): cutoff[i] =(1./expfac[i])**(1./expind[i])
                else: cutoff[i] = 2.99e5

            flux[i]   = (flux[i])*(np.random.normal(1,parameter_noise))
            index[i]  *= np.random.normal(1,parameter_noise)
            beta[i]   *= np.random.normal(1,parameter_noise)
            cutoff[i] = cutoff[i]*(np.random.normal(1,parameter_noise))

            mes.info("Adding [free] target source, Catalog name is %s, dist is %.2f and TS is %.2f" %(names[i],rsrc,sigma[i]) )

            if len(sources)>0:
                if (sources[0]['name'] != srcname):
                    sources.insert(0,{'name': srcname, 'ra': ra_src, 'dec': dec_src,
                                      'flux': flux[i], 'index': -index[i], 'scale': pivot[i],
                                      'cutoff': cutoff[i], 'beta': beta[i], 'expfac': expfac[i], 'expind': expind[i],
                                      'IsFree': 1, 'IsFreeShape' : 1,
                                      'SpectrumType': spectype[i], 'ExtendedName': extended_fitsfilename})

        elif rsrc < max_radius and rsrc >= .1 and sigma[i] > min_significance_free:
            # if the source is close to the target and is bright : add it as a free source
            # add gaussian noise
            flux[i]   = (flux[i])*(np.random.normal(1,parameter_noise))
            index[i]  *= np.random.normal(1,parameter_noise)
            beta[i]   *= np.random.normal(1,parameter_noise)
            cutoff[i] = cutoff[i]*(np.random.normal(1,parameter_noise))

            Nfree += 1
            mes.info("Adding [free] source, Catalog name is %s, dist is %.2f and TS is %.2f" %(names[i],rsrc,sigma[i]) )
            if not(extended_fitsfilename==""):
                if not os.path.isfile(join(CATALOG_TEMPLATE_DIR, extended_fitsfilename)):
                    mes.warning("Filename %s for extended source %s does not exist. Skipping." %(extended_fitsfilename,extendedName[i]))
                    continue
                mes.info("Adding extended source "+extendedName[i]+", Catalogue name is "+names[i])
                Nextended+=1
            sources.append({'name': names[i], 'ra': ra[i], 'dec': dec[i],
                            'flux': flux[i], 'index': -index[i], 'scale': pivot[i],
                            'cutoff': cutoff[i], 'beta': beta[i], 'expfac': expfac[i], 'expind': expind[i],
                            'IsFree': 1, 'IsFreeShape': 1,
                            'SpectrumType': spectype[i], 'ExtendedName': extended_fitsfilename})
        elif (rsrc < 2*max_radius and rsrc >= .1 and sigma[i] > min_significance_free) or (sigma[i] > 100 and rspace < original_roi):
            flux[i]   = (flux[i])*(np.random.normal(1,parameter_noise))
            # if the source is within 2 radius or it is very bright : add it with only the norm free
            # add gaussian noise
            Nfree += 1
            mes.info("Adding [free norm/fixed shape] source, Catalog name is %s, dist is %.2f and TS is %.2f" %(names[i],rsrc,sigma[i]) )
            if not(extended_fitsfilename==""):
                if not os.path.isfile(join(CATALOG_TEMPLATE_DIR, extended_fitsfilename)):
                    mes.warning("Filename %s for extended source %s does not exist. Skipping." %(extended_fitsfilename,extendedName[i]))
                    continue
                mes.info("Adding extended source "+extendedName[i]+", Catalogue name is "+names[i])
                Nextended+=1
            sources.append({'name': names[i], 'ra': ra[i], 'dec': dec[i],
                            'flux': flux[i], 'index': -index[i], 'scale': pivot[i],
                            'cutoff': cutoff[i], 'beta': beta[i], 'expfac': expfac[i], 'expind': expind[i],
                            'IsFree': 1, 'IsFreeShape': 0,
                            'SpectrumType': spectype[i], 'ExtendedName': extended_fitsfilename})

        elif (sigma[i] > min_significance_catalog):
            # if the source is inside the extended ROI: add them as a frozen source
            if  rspace < roi and rsrc > .1: #  and sigma[i] > min_significance:
                mes.info("Adding [fixed] source, Catalog name is %s, dist is %.2f and TS is %.2f" %(names[i],rsrc,sigma[i]) )
                if not(extended_fitsfilename==""):
                    if not os.path.isfile(join(CATALOG_TEMPLATE_DIR, extended_fitsfilename)):
                        mes.warning("Filename %s for extended source %s does not exist. Skipping." %(extended_fitsfilename,extendedName[i]))
                        continue
                    mes.info("Adding extended source "+extendedName[i]+", Catalogue name is "+names[i])
                    Nextended+=1
                sources.append({'name': names[i], 'ra': ra[i], 'dec': dec[i],
                                'flux': flux[i], 'index': -index[i], 'scale': pivot[i],
                                'cutoff': cutoff[i], 'beta': beta[i], 'expfac': expfac[i], 'expind': expind[i],
                                'IsFree': 0, 'IsFreeShape': 0,
                                'SpectrumType': spectype[i],'ExtendedName': extended_fitsfilename})

    # if the target has not been added from catalog, add it now
    if sources[0]['name']!=srcname:
        # add gaussian noise
        Nfree += 1
        #add the target to the list of sources in first position
        emin = config['energy']['emin']
        emax = config['energy']['emax']
        scale_failback = 10**((2*np.log10(emin)+np.log10(emax))/3.)
        if model == 'LogParabola':
            index_failback = 1.8
        elif model == 'PLSuperExpCutoff':
            index_failback = 1.8
        else:
            index_failback = 2.0

        sources.insert(0,{'name':srcname, 'ra': ra_src, 'dec': dec_src,
                       'flux': 1e-9, 'index': index_failback,
                       'scale': scale_failback,
                       'cutoff': 1e4, 'beta': 0.03, 'IsFree': 1, 'IsFreeShape': 1,
                       'SpectrumType': model,'ExtendedName': ""})

    mes.info("Summary of the XML model generation")
    print(("Add ", len(sources), " sources in the ROI of ", roi, "(",config['space']['rad'],"+", roi-config['space']['rad'],") degrees"))
    print((Nfree, " sources have free parameters inside ", max_radius, " degrees"))
    print((Nextended, " source(s) is (are) extended"))

    #save log of the generation of the xml
    save =  "\n"
    save += "catalog: "+catalog+"\n"
    save += "Add "+str(len(sources))+" sources in the ROI of "+str(roi)+ "("+str(config['space']['rad'])+"+ 2 ) degrees\n"
    save += " sources have free parameters inside "+str(max_radius)+" degrees\n"
    save += str(Nextended)+" source(s) is (are) extended\n"
    savexml = open(config['out']+'/'+ config['target']['name']+"_"+config['target']['spectrum']+"_generation.log","w")
    savexml.write(save)
    savexml.close()

    return sources

def IsIn(name, sources):
    for source in sources:
        if source == name:
            return True
    return False

def WriteXml(lib, doc, srclist, config):
    from enrico import Loggin
    mes = Loggin.Message()
    """Fill and write the library of sources into an XML file"""
    emin = config['energy']['emin']
    emax = config['energy']['emax']

    # Check if it is an energy bin, so we won't take the pivot energy from the catalog
    is_energy_bin = 1 if 'Ebin' in config['file']['tag'] else 0

    Galname = "GalDiffModel"
    Isoname = "IsoDiffModel"

    #test if the user provides diffuse files. if not  use the default one
    if config['model']['diffuse_gal_dir'] == "":
        Gal_dir = env.DIFFUSE_DIR
    else:
        Gal_dir = config['model']['diffuse_gal_dir']

    if config['model']['diffuse_iso_dir'] == "":
        Iso_dir = env.DIFFUSE_DIR
    else:
        Iso_dir = config['model']['diffuse_iso_dir']

    if config['model']['diffuse_gal'] == "":
        Gal = Gal_dir + "/" + env.DIFFUSE_GAL
    else:
        Gal = Gal_dir + "/" + config['model']['diffuse_gal']

    if config['model']['diffuse_iso'] == "":
        Iso = utils.GetIso(config["event"]["evclass"],config["event"]["evtype"])
        try :
            if not(os.path.isfile(Iso)):
                raise IOError
        except IOError:
            mes.warning("Cannot find Iso file %s, please have a look. Switching to default one" %Iso)
            Iso = Iso_dir + "/" + env.DIFFUSE_ISO_SOURCE
    else:
        Iso = Iso_dir + "/" + config['model']['diffuse_iso']

    #add diffuse sources
    addDiffusePL(lib, Iso, free=1, value=1.0,
                 max=10.0, min=1.0, name=Isoname)
    addGalprop(lib, Gal, free=1, value=1.0, scale=1.0,
               max=10.0, min=.010, name=Galname)

    print(("Iso model file ",Iso))
    print(("Galactic model file ",Gal))

    yesnodict = {}
    for y in ['yes',True,'true',1,1.0,'1','1.0']:
        yesnodict[y] = 1
    for n in ['no',False,'false',0,0.0,'0','0.0']:
        yesnodict[n] = 0

    try:
        ebldict = {}
        ebldict['tau_norm']      = 1.0
        ebldict['free_redshift'] = 0 # NOTE:ToDo
        ebldict['free_tau_norm'] = yesnodict[config['target']['fit_tau']]
        ebldict['redshift']      = float(config['target']['redshift'])
        ebldict['model']         = int(config['target']['ebl_model'])
        if ebldict['redshift'] < 1.e-3:
            ebldict = None
    except NameError:
        ebldict = None

    # loop over the list of sources and add it to the library
    for i in range(len(srclist)):
        name = srclist[i].get('name')
        if (name == config['target']['name']):
            ebl = ebldict
        else:
            ebl = None
        ra = srclist[i].get('ra')
        dec = srclist[i].get('dec')
        free      = srclist[i].get('IsFree')
        freeshape = srclist[i].get('IsFreeShape')
        spectype  = srclist[i].get('SpectrumType')
        extendedName = srclist[i].get('ExtendedName')
        # Check the spectrum model
        if spectype.strip() == "PowerLaw":
            if (ebl==None):
                energyscale = utils.GetE0(emin,emax) if is_energy_bin else srclist[i].get('scale')
                addPSPowerLaw1(lib, name, ra, dec, "None",
                              emin=emin, emax=emax,
                              eflux=energyscale,
                              flux_free=free, flux_value=srclist[i].get('flux'),
                              index_free=freeshape, index_value=srclist[i].get('index'),extendedName=extendedName)
            if (ebl!=None):
                # EblAtten::Powerlaw used to not exist, so we use instead a LogParabola with fixed b=0.
                addPSLogparabola(lib, name, ra, dec, ebl,
                              emin=emin, emax=emax,
                              norm_free=free, norm_value=srclist[i].get('flux'),
                              alpha_free=freeshape, alpha_value=abs(srclist[i].get('index')),
                              beta_free=0, beta_min=0, beta_max=0,
                              beta_value=0,extendedName=extendedName)
        elif spectype.strip() == "PowerLaw2":
            addPSPowerLaw2(lib, name, ra, dec, ebl,
                            emin=emin, emax=emax,
                            flux_free=free, flux_value=srclist[i].get('flux'),
                            index_free=freeshape, index_value=srclist[i].get('index'),extendedName=extendedName)
        elif spectype.strip() == "LogParabola":
            addPSLogparabola(lib, name, ra, dec, ebl, enorm=srclist[i].get('scale'),
                              emin=emin, emax=emax,
                              norm_free=free, norm_value=srclist[i].get('flux'),
                              alpha_free=freeshape, alpha_value=abs(srclist[i].get('index')),
                              beta_free=freeshape, beta_value=srclist[i].get('beta'),extendedName=extendedName)
        elif spectype.strip() == "PLExpCutoff" or spectype == "PLSuperExpCutoff":
            addPSPLSuperExpCutoff(lib, name, ra, dec, ebl,
                              emin=emin, emax=emax,
                              eflux=srclist[i].get('scale'),
                              flux_free=free, flux_value=srclist[i].get('flux'),
                              index1_free=freeshape, index1_value=srclist[i].get('index'),
                              cutoff_free=freeshape, cutoff_value=srclist[i].get('cutoff'),
                              extendedName=extendedName)
        elif spectype.strip() == "PLSuperExpCutoff2":
            addPSPLSuperExpCutoff2(lib, name, ra, dec, ebl,
                              emin=emin, emax=emax,
                              eflux=srclist[i].get('scale'),
                              flux_free=free, flux_value=srclist[i].get('flux'),
                              index1_free=freeshape, index1_value=srclist[i].get('index'),
                              expfac_free=freeshape, expfac_value=srclist[i].get('expfac'),
                              index2_free=0, index2_value=srclist[i].get('expind'),
                              extendedName=extendedName)
        elif spectype.strip() == "PLSuperExpCutoff3":
            addPSPLSuperExpCutoff3(lib, name, ra, dec, ebl,
                              emin=emin, emax=emax,
                              eflux=srclist[i].get('scale'),
                              flux_free=free, flux_value=srclist[i].get('flux'),
                              indexS_free=freeshape, indexS_value=srclist[i].get('index'),
                              expfacS_free=freeshape, expfacS_value=srclist[i].get('expfac'),
                              index2_free=0,index2_value=srclist[i].get('expind'),
                              extendedName=extendedName)
        elif spectype.strip() == "PLSuperExpCutoff4":
            addPSPLSuperExpCutoff4(lib, name, ra, dec, ebl,
                              emin=emin, emax=emax,
                              eflux=srclist[i].get('scale'),
                              flux_free=free, flux_value=srclist[i].get('flux'),
                              indexS_free=freeshape, indexS_value=srclist[i].get('index'),
                              expfacS_free=freeshape, expfacS_value=srclist[i].get('expfac'),
                              index2_free=0,index2_value=srclist[i].get('expind'),
                              extendedName=extendedName)
        elif  spectype.strip() == "BrokenPowerLaw":
            addPSBrokenPowerLaw2(lib, name, ra, dec, ebl,
                       emin=emin, emax=emax,
                        flux_value=1.6, flux_scale=1e-6, extendedName=extendedName)

        else:
            print(('Warning!!!, unknown model %s' %spectype.strip()))

    folder = config['out']
    utils.mkdir_p(folder)

    output = config['file']['xml']

    mes.info("write the Xml file in "+output)
    open(output, 'w').write(doc.toprettyxml('  '))#save it

def CreateLib():
    """@todo: document me"""
    import sys
    import time
    domimpl = xml.dom.minidom.getDOMImplementation()
    doc = domimpl.createDocument(None, "source_library", None)
    lib = doc.documentElement
    lib.setAttribute("title", "source library")
    lib.appendChild(doc.createComment('Source library created by %s at %s' %
                                      (sys.argv[0], time.asctime())))
    return lib, doc

def Xml_to_Reg(Filename, listSource, Prog=None):
    """Convert model from xml format to ds9 format"""
    fds9 = open(Filename + ".reg", "w")
    if Prog != None:
        fds9.write('# File generated by ' + Prog + '\n')
    fds9.write('global color=green dashlist=8 3 width=1 '
               'font="helvetica 10 normal roman" select=1 highlite=1 '
               'dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n')
    fds9.write("fk5\n")

    for src in listSource:
        ra = src.get('ra')
        dec = src.get('dec')
        name = src.get('name')
        if src.get('IsFree'):
            color = 'blue'
        else:
            color = 'green'
        fds9.write("circle(" + str(ra) + "," + str(dec) + ",0.2)  # color=" +
                   color + " text={" + str(name) + "}\n")
    fds9.close()

def XmlMaker(config):
    folder = config['out']
    utils.mkdir_p(folder)
    # test if the user provide a catalog or not.
    #if not use the default one
    if config['environ']['FERMI_CATALOG_DIR'] == '':
        catalogDir = env.CATALOG_DIR
        print("use the default location of the catalog")
    else:
        catalogDir = config['environ']['FERMI_CATALOG_DIR']

    if config['environ']['FERMI_CATALOG'] == '':
        catalog = catalogDir + "/" + env.CATALOG
        print("use the default catalog")
    else:
        catalog = catalogDir + "/" + config['environ']['FERMI_CATALOG']

    print("Use the catalog : ", catalog)
    print("Use the extended directory : ", CATALOG_TEMPLATE_DIR)

    lib, doc = CreateLib()
    srclist = GetlistFromFits(config, catalog)

    WriteXml(lib, doc, srclist, config)

    Xml_to_Reg(folder + "/Roi_model",
        srclist, Prog=sys.argv[0])


text:
require "extend/module"
require "extend/fileutils"
require "extend/pathname"
require "extend/git_repository"
require "extend/ARGV"
require "extend/string"
require "extend/enumerable"
require "os"
require "utils"
require "exceptions"
require "set"
require "rbconfig"
require "official_taps"

ARGV.extend(HomebrewArgvExtension)

HOMEBREW_PRODUCT = ENV["HOMEBREW_PRODUCT"]
HOMEBREW_VERSION = ENV["HOMEBREW_VERSION"]
HOMEBREW_WWW = "http://brew.sh".freeze

require "config"

HOMEBREW_REPOSITORY.extend(GitRepositoryExtension)

RUBY_PATH = Pathname.new(RbConfig.ruby)
RUBY_BIN = RUBY_PATH.dirname

HOMEBREW_USER_AGENT_CURL = ENV["HOMEBREW_USER_AGENT_CURL"]
HOMEBREW_USER_AGENT_RUBY = "#{ENV["HOMEBREW_USER_AGENT"]} ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}".freeze

HOMEBREW_CURL_ARGS = [
  "--fail",
  "--progress-bar",
  "--remote-time",
  "--location",
  "--user-agent", HOMEBREW_USER_AGENT_CURL
].freeze

require "tap_constants"

module Homebrew
  include FileUtils
  extend self

  attr_accessor :failed
  alias failed? failed

  attr_accessor :raise_deprecation_exceptions
  alias raise_deprecation_exceptions? raise_deprecation_exceptions
end

HOMEBREW_PULL_API_REGEX = %r{https://api\.github\.com/repos/([\w-]+)/([\w-]+)?/pulls/(\d+)}
HOMEBREW_PULL_OR_COMMIT_URL_REGEX = %r[https://github\.com/([\w-]+)/([\w-]+)?/(?:pull/(\d+)|commit/[0-9a-fA-F]{4,40})]

require "compat" unless ARGV.include?("--no-compat") || ENV["HOMEBREW_NO_COMPAT"]

ORIGINAL_PATHS = ENV["PATH"].split(File::PATH_SEPARATOR).map do |p|
  begin
    Pathname.new(p).expand_path
  rescue
    nil
  end
end.compact.freeze

# TODO: remove this as soon as it's removed from commands.rb.
HOMEBREW_INTERNAL_COMMAND_ALIASES = {
  "ls" => "list",
  "homepage" => "home",
  "-S" => "search",
  "up" => "update",
  "ln" => "link",
  "instal" => "install", # gem does the same
  "rm" => "uninstall",
  "remove" => "uninstall",
  "configure" => "diy",
  "abv" => "info",
  "dr" => "doctor",
  "--repo" => "--repository",
  "environment" => "--env",
  "--config" => "config",
}.freeze

redpajama_set_name: RedPajamaGithub


text:
El API proporciona recursos para buscar, cargar, editar y organizar documentos, así como para trabajar con proyectos. Además, un servicio oEmbed proporciona una fácil integración de incrustación de documentos, páginas y notas.

Use of the DocumentCloud API indicates you have read and agree to our [Directrices y Condiciones del Servicio de API](/terms/api).

## Contenido

* General:
  * [Directrices y Condiciones del Servicio de API](/terms/api)
* Métodos de Documento:
  * [Busque](#search-documents)
  * [Cargar](#upload-documents)
  * [Obtener](#get-document)
  * [Actualizar](#update-document)
  * [Borre](#delete-document)
  * [Entitades](#get-entities)
* Métodos de Proyecto:
  * [Crear](#create-project)
  * [Listar de proyectos](#get-projects)
  * [Actualizar](#update-project)
  * [Borre](#delete-project)
* [oEmbed](#oembed):
  * [Documentos](#oembed-documents)
  * [Páginas](#oembed-pages)
  * [Notas](#oembed-notes)
* [Envolturas de la API y Utilidades](#api-wrappers)

# Métodos de Documento

## GET /api/search.json

Busque en el catálogo de documentos públicos. Este método se puede utilizar para extraer los documentos públicos de su cuenta con fines incrustarlos, o para permitir búsquedas de su archivo de documentos cargados directamente desde tu propio sitio web. Consulte  nuestra información de búsqueda para más ayuda con las consultas de búsqueda.

Parámetro     | Descripción           |  Ejemplo
--------------|-----------------------|--------------
q 	          |  la consulta de búsqueda			|          group:nytimes title:nuclear
page	      |  respuesta número de página			|         3 (defaults to 1)
per_page      |  el número de documentos a regresar por página 	      |      100 (defaults to 10, max  is 1000)
sections      |  incluyen secciones del documento en los resultados   |  true (not present by default)
annotations   |  incluyen notas de documentos en los resultados       |     true (not present by default)
data	      |  incluyen datos clave/de valor en los resultados	  |       true (not present by default)
mentions      |  incluyen las menciones destacadas de la frase de búsqueda    |      3 (not present by default, max is 10)

### Ejemplo

    /api/search.json?q=obama&page=2

    Utilice el campo de búsqueda de abajo para intentar consultas y ver como es el JSON resultante.

    <form id="search_form" action="about:blank" autocomplete="off">

Search

            <input type="text" name="q" id="q" />

        Consulta de búsqueda

ej.: "title:arrest"

    </form>

### Consejos

 * Si desea obtener resultados de búsqueda con más de diez documentos en una página, pase el parámetro per_page. Un máximo de 1000 documentos se devolverán a la vez.

## POST /api/upload.json

Nuestra API para cargas en conjunto expone el mismo método que se utiliza internamente, pero lo envuelve en la autenticación básica a través de HTTPS. Los documentos se cargan en la cuenta autenticada.

Puede cargar un archivo local utilizando una carga estándar de varias partes, u ordenando a DocumentCloud que descargue el archivo de un servidor público por medio de un URL.

Parámetro 	|	Descripción 					|	Ejemplo
------------|-----------------------------------|------------
file  	    | (requerido) ya sea el contenido de un archivo local o la  dirección URL donde el documento se puede encontrar | --
title 		| (requerido) el titulo canónico del documento 		| Declaración de impuestos de Blagojevich 2008
source		| (opcional) la fuente que produjo el documento 	|	U.S.  Attorney's Office
description	| (opcional) un párrafo de descripción detallada impuestos 	|  Esta muestra de la acusación es la declaración conjunta de del 2008 de Rod y Patti Blagojevich.
language        | (optional) El lenguaje del documento. Se utilizará para determinar qué paquete de OCR que se utilizará para los archivos que requieren procesamiento de OCR. Tome por defecto "eng" | spa
related_article | (opcional) la dirección URL del artículo asociado     | http://example.com/news/blago/2010-5-3.html
published_url   |   (opcional) la dirección URL de la página en la que se integrará el documento | http://documents.example.com/blago-transcript.html
access		    |(opcional), una de "publico", "privado", "organización",público predeterminado como  "privado" |
project		    | (opcional) una identificación de proyectos numérica, para cargar el documento en un proyecto existente.   |       1012
data 		    | (opcional) una mezcla  de pares clave / valor de datos {"data": {"status": "active"}} (json) arbitrarios | data[status]=active (query string)
secure	        |   (opcional) Si está trabajando con un documento  realmente sensible, pase el parámetro "seguro" con el fin de evitar que el documento sea enviado a OpenCalais para extracción de entidades. | true
force_ocr | (opcional) especifica que un documento debe OCR'd incluso si tiene texto en él (default is "false") | true

### Consejos

 * Por favor asegúrese de envíar la solicitud adecuadamente codificada como "multipart/form-data"
 * Revise sus archivos cargados y agregue  fuente y descripción si no lo ha hecho.

### Ejemplo

Usando biblioteca RestClient de Ruby podría hacerlo siguiente:

    RestClient.post('https://ME%40TEST.COM:SECRET@www.documentcloud.org/api/upload.json',
      :file   => File.new('/full/path/to/document/document.pdf','rb'),
      :title  => "2008 Blagojevich Tax Return",
      :source => "U.S. Attorney's Office",
      :access => 'private',
      :data   => {"date" => "2009-04-01", "exhibit" => "E1146"}
    )

## GET /api/documents/[id].json

Recupere la representación canónica JSON de un documento en particular, según especificado por el identificador del documento (normalmente algo como: **1659580-economic-analysis-of-the-south-pole-traverse**).

## Ejemplo de respuesta

    {"document":{
      "id":"1659580-economic-analysis-of-the-south-pole-traverse",
      "title":"Economic Analysis of the South Pole Traverse",
      "access":"public"
      "pages":38,
      "description":"The South Pole Traverse is a highway of compacted snow built to provide an overland supply route between McMurdo Station on the Antarctic coast and the Amundsen–Scott South Pole Station.  This report provides an account of the logistical costs associated with transport across the Traverse compared with air transport via LC-130 Hercules aircraft.",
      "source":"http://www.dtic.mil/cgi-bin/GetTRDoc?AD=ADA602402",
      "created_at":"Wed, 11 Feb 2015 18:30:58 +0000",
      "updated_at":"Sun, 08 Mar 2015 15:23:02 +0000",
      "canonical_url":"https://www.documentcloud.org/documents/1659580-economic-analysis-of-the-south-pole-traverse.html",
      "language":"eng",
      "file_hash":"c07f7b640c4df2132bacb8dbfac1dcb65f978418",
      "contributor":"Ted Han",
      "contributor_organization":"DocumentCloud",
      "display_language":"eng",
      "resources":{
        "pdf":"https://assets.documentcloud.org/documents/1659580/economic-analysis-of-the-south-pole-traverse.pdf",
        "text":"https://assets.documentcloud.org/documents/1659580/economic-analysis-of-the-south-pole-traverse.txt",
        "thumbnail":"https://assets.documentcloud.org/documents/1659580/pages/economic-analysis-of-the-south-pole-traverse-p1-thumbnail.gif",
        "search":"https://www.documentcloud.org/documents/1659580/search.json?q={query}",
        "print_annotations":"https://www.documentcloud.org/notes/print?docs[]=1659580",
        "translations_url":"https://www.documentcloud.org/translations/{realm}/{language}",
        "page":{
          "image":"https://assets.documentcloud.org/documents/1659580/pages/economic-analysis-of-the-south-pole-traverse-p{page}-{size}.gif",
          "text":"https://www.documentcloud.org/documents/1659580/pages/economic-analysis-of-the-south-pole-traverse-p{page}.txt"
          },
        "annotations_url":"https://www.documentcloud.org/documents/1659580/annotations"
      },
      "sections":[],
      "data":{},
      "annotations":[]
    }}

### Consejos

 * **Nota de seguridad:** Por fidelidad con el documento de origen, el texto extraído (disponible a través de las direcciones URL proporcionadas en `document.resources.text` y `document.resources.page.text` modelo paginación iteración) no es verificada. Siempre debe escape de documentos y páginas de texto antes de la inserción en el DOM.

## PUT /api/documents/[id].json

Actualice el **título**, **fuente**, **descripción**, **artículo relacionado**, **nivel de acceso**, o los datos de un documento, con este método. Refiérase a su documento por su ID (normalmente algo como: **1659580-economic-analysis-of-the-south-pole-traverse**).

Parámetro 	|	Descripción 					|	Ejemplo
------------|-----------------------------------|------------
file  	    | (requerido) ya sea el contenido de un archivo local o la  dirección URL donde el documento se puede encontrar | --
title 		| (requerido) el titulo canónico del documento 		| Declaración de impuestos de Blagojevich 2008
source		| (opcional) la fuente que produjo el documento 	|	U.S.  Attorney's Office
description	| (opcional) un párrafo de descripción detallada impuestos 	|  Esta muestra de la acusación es la declaración conjunta de del 2008 de Rod y Patti Blagojevich.
related_article | (opcional) la dirección URL del artículo asociado     | http://example.com/news/blago/2010-5-3.html
published_url   |   (opcional) la dirección URL de la página en la que se integrará el documento | http://documents.example.com/blago-transcript.html
access		    |(opcional), una de "publico", "privado", "organización",público predeterminado como  "privado" |
project		    | (opcional) una identificación de proyectos numérica, para cargar el documento en un proyecto existente.   |       1012
data 		    | (opcional) una mezcla  de pares clave / valor de datos {"data": {"status": "active"}} (json) arbitrarios | data[status]=active (query string)
secure	        |   (opcional) Si está trabajando con un documento  realmente sensible, pase el parámetro "seguro" con el fin de evitar que el documento sea enviado a OpenCalais para extracción de entidades. | true

El valor en la respuesta de este método será la representación JSON de su documento (como se ve en el método GET arriba), con todos las actualizaciones aplicadas.

## Consejos

 * Si su cliente HTTP no puede crear una solicitud PUT, puede enviarlo como POST, y añadir un parámetro adicional: `_method=put`

## DELETE/api/documents /[id].Json

Elimine un documento de DocumentCloud. Debe ser autentificado como el propietario del documento para que este método funcione.
Consejos

 * Si su cliente HTTP no puede crear una petición DELETE, puede enviarlo como POST, y añadir un parámetro adicional: `_method=delete`

## GET/api/documents/[id]/entities.json

Recupere el JSON de todas las entidades que un determinado documento contiene, especificado por el ID del documento (normalmente algo como: **1659580-economic-analysis-of-the-south-pole-traverse**). Las entidades son ordenadas por su relevancia al  el documento según es determinado por OpenCalais.

### Ejemplo de respuesta

    {
      "entities":{
        "person":[
          { "value":"Ramadan Aff", "relevance":0.72 },
          { "value":"Sarah Normand", "relevance":0.612 },
          ...
        ],
        "organization":[
          { "value":"Supreme Court", "relevance":0.619 },
          { "value":"Hamas", "relevance":0.581 },
          ...
        ]
        ...
      }
    }

# Métodos de Proyecto

## POST /api/projects.json

Cree un nuevo proyecto para la cuenta autenticada, con un título, una descripción opcional y los identificadores (IDs) de documentos opcionales.

Parámetro 	|	Descripción 					|	Ejemplo
------------|-----------------------------------|------------
title 		| (obligatorio) El título del proyecto 	    	|	Drywall Complaints
description	| (opcional) un párrafo de descripción detallada  	| Una colección de documentos de 2007-2009 relacionados con los informes de paneles de yeso contaminados en Florida.
document_ids | 	(opcional) una lista de los documentos que el proyecto contiene, por id | 28-rammussen, 207-petersen

## Consejos
 * Tenga en cuenta que tiene que utilizar la convención para pasar una matriz de cadenas: `?document_ids[]=28-boumediene&document_ids[]=207-academy&document_ids[]=30-insider-trading`

## GET/api/projects.json

Recupere una lista de nombres de proyectos y IDs de documentos. Debe utilizar la autenticación básica a través de HTTPS para hacer esta solicitud. Los proyectos presentados a continuación pertenecen a la cuenta autenticada.

### Ejemplo de respuesta

    {"projects": [
      {
        "id": 5,
        "title": "Literate Programming",
        "document_ids":[
          "103-literate-programming-a-practioners-view",
          "104-reverse-literate-programming"
        ]
      },
      ...
    ]}

## PUT/api/projects/[id].json

Actualice un proyecto existente para la cuenta actual autenticada. Puede definir el título, la descripción o la lista de documentos. Véase POST, arriba.

## DELETE/api/projects /[id].json

Borre un proyecto que pertenezca a la cuenta actual autenticada.

# oEmbed

## GET /api/oembed.json

Generar un código de inserción para un recurso (un documento o una nota) utilizando nuestro servicio [oEmbed](http://oembed.com/). Devuelve una rica respuesta JSON.

### Formato de respuesta

    {
      "type": "rich",
      "version": "1.0",
      "provider_name": "DocumentCloud",
      "provider_url": "https://www.documentcloud.org/",
      "cache_age": 300,
      "resource_url": "https://www.documentcloud.org/documents/doc-name.html",
      "height": 750,
      "width": 600,
      "display_language": "en",
      "html": ""
    }

### Ejemplo petición documento

    /api/oembed.json?url=https%3A%2F%2Fwww.documentcloud.org%2Fdocuments%2Fdoc-name.html

### Parámetros para documentos

Parámetro   | Descripción           | Ejemplo
-----------------|-----------------------|--------------
url              | **(requerido)** De escape de URL documento para incrustar | https%3A%2F%2Fwww.documentcloud.org %2Fdocuments%2Fdoc-name.html
maxheight        | (opcional) La altura del espectador (pixels)    | 750
maxwidth         | (opcional) La ancho del espectador (pixels)     | 600
container        | (opcional) Especifique el contenedor DOM en el que se incorporará al espectador | #my-document-div
notes            | (opcional) Activar la pestaña de notas   | true (default)
text             | (opcional) Activar la pestaña de texto   | true (default)
zoom             | (opcional) Mostrar el deslizador de zoom    | true (default)
search           | (opcional) Mostrar el caja de búsqueda    | true (default)
sidebar          | (opcional) Mostrar la barra lateral    | true (default)
pdf              | (opcional) Para incluir un enlace al PDF original    | true (default)
responsive       | (opcional) Hacer que el espectador adaptable    | false (default)
responsive_offset| (opcional) Especifique la altura del cabezal (pixels)    | 4
note             | (opcional) Abra el documento en una nota específica. Un entero que representa el ID de nota | 214279
page             | (opcional) Abra el documento a una página específica   | 3

### Ejemplo petición página

    /api/oembed.json?url=https%3A%2F%2Fwww.documentcloud.org%2Fdocuments%2Fdoc-name%2Fpages%2F5.html

### Parameters for pages

Parameter        | Description           |  Example
-----------------|-----------------------|--------------
url              | **(required)** De escape de URL documento página para incrustar     | https%3A%2F%2Fwww.documentcloud.org%2F documents%2Fdoc-name%2Fpages%2F5.html

### Ejemplo petición nota

    /api/oembed.json?url=https%3A%2F%2Fwww.documentcloud.org%2Fdocuments%2Fdoc-name%2Fannotations%2F220666.html

### Parámetros para notas

Parámetro   | Descripción           | Ejemplo
-----------------|-----------------------|--------------
url              | **(required)** De escape de URL documento para incrustar     | https%3A%2F%2Fwww.documentcloud.org%2F documents%2Fdoc-name%2Fannotations%2F220666.html
container        | (optional) Especifique el contenedor DOM en el que se incorporará al espectador | #my-document-div

# Envolturas de la API y Utilidades

La comunidad de código abierto ha contribuido varias aplicaciones votos para interactuar con el API del DocumentCloud. Ver la documentación de ejemplos y más información:

**Node**

* [node-documentcloud](https://github.com/rdmurphy/node-documentcloud): Una envoltura alrededor de la API Node.js DocumentCloud.

**Python:**

* [python-documentcloud](http://python-documentcloud.readthedocs.org/en/latest/): Un envoltorio de Python simple para la API DocumentCloud.
* [pneumatic](http://pneumatic.readthedocs.org/en/latest/): Una biblioteca de carga para cargas masivas de DocumentCloud.

**Ruby:**

* [Documentcloud](https://rubygems.org/gems/documentcloud/): Rubygem para interactuar con el API DocumentCloud.

# Preguntas?

¿Aún tiene preguntas acerca de cómo colaborar? No dude en [comunicarse con nosotros](javascript:dc.ui.Dialog.contact(\)).


text:
import Scene from './scene';
import ModelInstance from './modelinstance';
import EmittedObject from './emittedobject';

/**
 * An emitter.
 */
export default abstract class Emitter {
  instance: ModelInstance;
  objects: EmittedObject[] = [];
  alive = 0;
  currentEmission = 0;

  abstract createObject(): EmittedObject;
  abstract updateEmission(dt: number): void;
  abstract emit(): void;

  constructor(instance: ModelInstance) {
    this.instance = instance;
  }

  /**
   * Update this emitter.
   */
  update(dt: number): void {
    // Emit new objects if needed.
    this.updateEmission(dt);

    const currentEmission = this.currentEmission;

    if (currentEmission >= 1) {
      for (let i = 0; i < currentEmission; i += 1) {
        this.emit();
      }
    }
  }

  /**
   * Clear any emitted objects.
   */
  clear(): void {
    const objects = this.objects;

    for (let i = 0, l = this.alive; i < l; i++) {
      const object = objects[i];

      object.health = 0;
    }

    this.currentEmission = 0;
  }

  emitObject(emitData?: unknown): EmittedObject {
    const objects = this.objects;

    // If there are no unused objects, create a new one.
    if (this.alive === objects.length) {
      objects.push(this.createObject());
    }

    // Get the first unused object.
    const object = objects[this.alive];

    object.index = this.alive;

    object.bind(emitData);

    this.alive += 1;
    this.currentEmission -= 1;

    const scene = <Scene>this.instance.scene;

    scene.emittedObjectUpdater.add(object);

    return object;
  }

  kill(object: EmittedObject): void {
    const objects = this.objects;

    this.alive -= 1;

    const otherObject = objects[this.alive];

    objects[object.index] = otherObject;
    objects[this.alive] = object;

    otherObject.index = object.index;
    object.index = -1;
  }
}


text:
package com.cognizant.devops.platformcommons.config;

import java.io.Serializable;

public class DALData implements Serializable{
	private String dbUser;
	private String password;
	private String dbURL;

	public String getDbUser() {
		return dbUser;
	}
	public void setDbUser(String dbUser) {
		this.dbUser = dbUser;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getDbURL() {
		return dbURL;
	}
	public void setDbURL(String dbURL) {
		this.dbURL = dbURL;
	}
}


text:
//
//  UIButton+HYBHelperBlockKit.h
//  HYBHelperKit
//
//  Created by huangyibiao on 16/6/30.
//  Copyright © 2016年 huangyibiao. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "HYBHelperBlocksKit.h"
#import "HYBCommonKit.h"

@interface UIButton (HYBHelperBlockKit)

/**
 *	@author https://github.com/CoderJackyHuang
 *
 *	The most easy way to create a button with a touch up event callback block.
 *
 *	@param onTouchUp	The touch up event callback block.
 *
 *	@return UIButton instance.
 */
+ (instancetype)hyb_buttonWithTouchUp:(HYBButtonBlock)onTouchUp;

/**
 *	@author https://github.com/CoderJackyHuang
 *
 *	Create a button with super view, masonry auto layout, and touch up callback.
 *
 *	@param superView		Add the button to the superView.
 *	@param constraints	Using Masonry to add constraints.
 *	@param touchUp			The callback of touching up event.
 *
 *	@return UIButton instance.
 */
+ (instancetype)hyb_buttonWithSuperView:(UIView *)superView
                            constraints:(HYBConstraintMaker)constraints
                                touchUp:(HYBButtonBlock)touchUp;

/**
 *	@author https://github.com/CoderJackyHuang
 *
 *	Create a button with title, super view, masonry auto layout, and touch up callback.
 *
 *	@param title				Set title for the button.
 *	@param superView		Add the button to the superView.
 *	@param constraints	Using Masonry to add constraints.
 *	@param touchUp			The callback of touching up event.
 *
 *	@return UIButton instance.
 */
+ (instancetype)hyb_buttonWithTitle:(NSString *)title
                          superView:(UIView *)superView
                        constraints:(HYBConstraintMaker)constraints
                            touchUp:(HYBButtonBlock)touchUp;

/**
 *	@author https://github.com/CoderJackyHuang
 *
 *	Create a button with image, super view, masonry auto layout, and touch up callback.
 *
 *	@param image				Set normal state image for the button, it can be
 *                      a image name or a real UIImage.
 *	@param superView		Add the button to the superView.
 *	@param constraints	Using Masonry to add constraints.
 *	@param touchUp			The callback of touching up event.
 *
 *	@return UIButton instance.
 */
+ (instancetype)hyb_buttonWithImage:(id)image
                          superView:(UIView *)superView
                        constraints:(HYBConstraintMaker)constraints
                            touchUp:(HYBButtonBlock)touchUp;

/**
 *	@author https://github.com/CoderJackyHuang
 *
 *	Create a button with normal image, selected image, super view,
 *  masonry auto layout, and touch up callback.
 *
 *	@param image				Set normal state image for the button, it can be
 *                      a image name or a real UIImage.
 *  @param selectedImage Set selected state image for the button, it can be
 *                      a image name or a real UIImage.
 *	@param superView		Add the button to the superView.
 *	@param constraints	Using Masonry to add constraints.
 *	@param touchUp			The callback of touching up event.
 *
 *	@return UIButton instance.
 */
+ (instancetype)hyb_buttonWithImage:(id)image
                      selectedImage:(id)selectedImage
                          superView:(UIView *)superView
                        constraints:(HYBConstraintMaker)constraints
                            touchUp:(HYBButtonBlock)touchUp;

@end


text:
void standalone_mmult (float A[32][32], float B[32][32], float C[32][32])
{
	mmult_hw <float, 32>(A, B, C);
}

//void HLS_accel (AXI_VAL in_stream[2*MCR_SIZE], AXI_VAL out_stream[MCR_SIZE])
void HLS_accel (AXI_VAL INPUT_STREAM[2*MCR_SIZE], AXI_VAL OUTPUT_STREAM[MCR_SIZE])
{
#pragma HLS INTERFACE s_axilite port=return     bundle=CONTROL_BUS
#pragma HLS INTERFACE axis      port=OUTPUT_STREAM
#pragma HLS INTERFACE axis      port=INPUT_STREAM

// HLS DEPRECATED MODE
//	// Map ports to Vivado HLS interfaces
//	#pragma HLS INTERFACE ap_fifo port=in_stream
//	#pragma HLS INTERFACE ap_fifo port=out_stream
//	// Map HLS ports to AXI interfaces
//	#pragma HLS RESOURCE variable=in_stream  core=AXIS metadata="-bus_bundle INPUT_STREAM"
//	#pragma HLS RESOURCE variable=out_stream core=AXIS metadata="-bus_bundle OUTPUT_STREAM"
//	#pragma HLS RESOURCE variable=return core=AXI4LiteS metadata="-bus_bundle CONTROL_BUS"

	wrapped_mmult_hw <float, 32, 32*32, 4, 5, 5>(INPUT_STREAM, OUTPUT_STREAM);

	return;
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.facet.impl.invalid;

import com.intellij.facet.ui.FacetEditorContext;
import com.intellij.facet.ui.FacetEditorTab;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.ui.ex.MultiLineLabel;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author nik
 */
public class InvalidFacetEditor extends FacetEditorTab {
  private final String myErrorMessage;
  private JPanel myMainPanel;
  private MultiLineLabel myDescriptionLabel;
  private JCheckBox myIgnoreCheckBox;
  private JLabel myIconLabel;
  private final InvalidFacetManager myInvalidFacetManager;
  private final InvalidFacet myFacet;

  public InvalidFacetEditor(FacetEditorContext context, String errorMessage) {
    myErrorMessage = errorMessage;
    myFacet = (InvalidFacet)context.getFacet();
    myInvalidFacetManager = InvalidFacetManager.getInstance(context.getProject());
  }

  @Nls
  @Override
  public String getDisplayName() {
    return "";
  }

  public JCheckBox getIgnoreCheckBox() {
    return myIgnoreCheckBox;
  }

  @NotNull
  @Override
  public JComponent createComponent() {
    myIconLabel.setIcon(AllIcons.General.BalloonError);
    myDescriptionLabel.setText(myErrorMessage);
    return myMainPanel;
  }

  @Override
  public boolean isModified() {
    return myIgnoreCheckBox.isSelected() != myInvalidFacetManager.isIgnored(myFacet);
  }

  @Override
  public void reset() {
    myIgnoreCheckBox.setSelected(myInvalidFacetManager.isIgnored(myFacet));
  }

  @Override
  public void apply() {
    myInvalidFacetManager.setIgnored(myFacet, myIgnoreCheckBox.isSelected());
  }
}


text:
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import "ScrubberItemView.h"
#import "JTypes.h"
#import "Utils.h"

static const NSUserInterfaceItemIdentifier g_scrubberItemIdentifier = @"scrubberItem";
static const int g_heightOfTouchBar = 30;
static const int g_interItemSpacings = 5;

@interface ScrubberItem : NSObject
@property (retain, nonatomic) NSString * text;
@property (retain, nonatomic) NSImage * img;
@property (nonatomic) execute jaction;
@end

@implementation ScrubberItem
@end

@interface NSScrubberContainer : NSCustomTouchBarItem<NSScrubberDataSource, NSScrubberDelegate, NSScrubberFlowLayoutDelegate>
{
    ScrubberItemView * _lastSelected;
}
@property (retain, nonatomic) NSMutableArray * items;
@end

static NSMutableArray * _convertItems(ScrubberItemData * items, int count) {
    NSMutableArray * nsarray = [[[NSMutableArray alloc] initWithCapacity:count] autorelease];
    for (int c = 0; c < count; ++c) {
        ScrubberItem * si = [[[ScrubberItem alloc] init] autorelease];
        si.text = createString(&items[c]);
        si.img = createImg(&items[c]);
        si.jaction = items[c].action;
        [nsarray addObject:si];
    }
    return nsarray;
}

@implementation NSScrubberContainer

- (NSInteger)numberOfItemsForScrubber:(NSScrubber *)scrubber {
    // NOTE: called from AppKit
    nstrace(@"scrubber [%@]: items count %d", self.identifier, self.items.count);
    return self.items.count;
}

- (NSScrubberItemView *)scrubber:(NSScrubber *)scrubber viewForItemAtIndex:(NSInteger)itemIndex {
    // NOTE: called from AppKit-thread (creation when TB becomes visible), uses default autorelease-pool (create before event processing)
    nstrace(@"scrubber [%@]: create viewForItemAtIndex %d", self.identifier, itemIndex);
    ScrubberItemView *itemView = [scrubber makeItemWithIdentifier:g_scrubberItemIdentifier owner:nil];

    ScrubberItem * itemData = [self.items objectAtIndex:itemIndex];
    if (itemData == nil) {
        nserror(@"scrubber [%@]: null item-data at index %d", self.identifier, itemIndex);
        return nil;
    }

    [itemView setImgAndText:itemData.img text:itemData.text];
    return itemView;
}

- (NSSize)scrubber:(NSScrubber *)scrubber layout:(NSScrubberFlowLayout *)layout sizeForItemAtIndex:(NSInteger)itemIndex {
    // NOTE: called from AppKit-thread (creation when TB becomes visible), uses default autorelease-pool (create before event processing)
    ScrubberItem * itemData = [self.items objectAtIndex:itemIndex];
    if (itemData == nil) {
        nserror(@"scrubber [%@]: null item-data at index %d", self.identifier, itemIndex);
        return NSMakeSize(0, 0);
    }

    NSFont * font = [NSFont systemFontOfSize:0]; // Specify a system font size of 0 to automatically use the appropriate size.
    const int imgW = itemData.img != nil ? itemData.img.size.width : 0;
    NSSize txtSize = itemData.text != nil ? [itemData.text sizeWithAttributes:@{ NSFontAttributeName:font }] : NSMakeSize(0, 0);

    CGFloat width = txtSize.width + imgW + 2*g_marginBorders + g_marginImgText + 13/*empiric diff for textfield paddings*/; // TODO: get rid of empiric, use size obtained from NSTextField
    nstrace(@"scrubber [%@]: sizeForItemAtIndex %d: txt='%@', iconW=%d, txt size = %1.2f, %1.2f, result width = %1.2f, font = %@", self.identifier, itemIndex, itemData.text, imgW, txtSize.width, txtSize.height, width, font);
    return NSMakeSize(width, g_heightOfTouchBar);
}

- (void)scrubber:(NSScrubber *)scrubber didSelectItemAtIndex:(NSInteger)selectedIndex {
    ScrubberItem * itemData = [self.items objectAtIndex:selectedIndex];
    if (itemData == nil) {
        nserror(@"scrubber [%@]: called didSelectItemAtIndex %d, but item-data at this index is null", self.identifier, selectedIndex);
        return;
    }

    NSScrubberItemView * view = [scrubber itemViewForItemAtIndex:selectedIndex];
    if (view != nil) {
        if (_lastSelected != nil)
            [_lastSelected setBackgroundSelected:false];

        _lastSelected = (ScrubberItemView *) view;
        [_lastSelected setBackgroundSelected:true];
    }

    nstrace(@"scrubber [%@]: perform action of scrubber item at %d", self.identifier, selectedIndex);
    (*itemData.jaction)();
}

@end

// NOTE: called from AppKit-thread (creation when TB becomes visible), uses default autorelease-pool (create before event processing)
id createScrubber(const char* uid, int itemWidth, ScrubberItemData * items, int count) {
    NSString * nsid = [NSString stringWithUTF8String:uid];
    nstrace(@"create scrubber [%@] (thread: %@)", nsid, [NSThread currentThread]);

    NSScrubberContainer * scrubberItem = [[NSScrubberContainer alloc] initWithIdentifier:nsid]; // create non-autorelease object to be owned by java-wrapper
    scrubberItem.items = _convertItems(items, count);

    NSScrubber *scrubber = [[[NSScrubber alloc] initWithFrame:NSMakeRect(0, 0, itemWidth, g_heightOfTouchBar)] autorelease];

    scrubber.delegate = scrubberItem;
    scrubber.dataSource = scrubberItem;

    [scrubber registerClass:[ScrubberItemView class] forItemIdentifier:g_scrubberItemIdentifier];

    scrubber.selectedIndex = -1;

    NSScrubberFlowLayout *scrubberLayout = [[[NSScrubberFlowLayout alloc] init] autorelease];
    scrubberLayout.itemSpacing = g_interItemSpacings;
    [scrubberLayout invalidateLayout];
    scrubber.scrubberLayout = scrubberLayout;

    scrubber.mode = NSScrubberModeFree;
    scrubber.showsArrowButtons = NO;
    scrubber.showsAdditionalContentIndicators = YES;
    scrubber.selectionOverlayStyle = nil;
    [scrubber.widthAnchor constraintGreaterThanOrEqualToConstant:itemWidth].active = YES;

    scrubberItem.view = scrubber;
    return scrubberItem;
}

void updateScrubber(id scrubObj, int itemWidth, ScrubberItemData * items, int count) {
    // NOTE: called from EDT (when update UI)
    NSScrubberContainer * container = scrubObj; // TODO: check types
    nstrace(@"async update scrubber [%@] (thread: %@)", container.identifier, [NSThread currentThread]);
    NSAutoreleasePool * edtPool = [[NSAutoreleasePool alloc] init];
    NSMutableArray * nsitems = _convertItems(items, count);
    dispatch_async(dispatch_get_main_queue(), ^{
        container.items = nsitems;
        NSScrubber * scrubber = container.view;     // TODO: check types
//        nstrace(@"\tinvalidate layout of scrubber [%@] (thread: %@)", container.identifier, [NSThread currentThread]);
        [scrubber.scrubberLayout invalidateLayout];
//        nstrace(@"\treload scrubber [%@] (thread: %@)", container.identifier, [NSThread currentThread]);
        [scrubber reloadData];
    });
    [edtPool release];
}


text:
Given /^the database "([^\"]*)" exists$/ do |uri|
  RestClient.delete(uri) rescue nil
  RestClient.put(uri, '')
end

Given /^the default Recliner::Document database is set to "([^\"]*)"$/ do |uri|
  Recliner::Document.use_database! uri
end


text:
using System;

namespace SkylineToolkit.Debugging.Commands
{
    internal class EvalCommand : DebugCommand
    {
        public override int Execute(ICommandContext ctx, string[] args, char[] flags)
        {
            int position = ctx.RawCommand.IndexOf(' ');

            if (position == -1)
            {
                ctx.SendOutput("No code specified. Type 'help eval' for more information.");

                return 1;
            }

            string code = ctx.RawCommand.Substring(position);

            ctx.SendOutput("Evaluating code...");

            object result = null;

            try
            {
                result = Debug.Evaluate(code);
            }
            catch (Exception ex)
            {
                ctx.SendOutput("Error while evaluating the code.");
                Log.Exception(ex);

                return 1;
            }

            if (result != null)
            {
                Log.Info(result.ToString());

                ctx.SendOutput("Output was sent to log");
            }
            else
            {
                ctx.SendOutput("<null>");
            }

            return 0;
        }

        public override bool CanExecute(ICommandContext ctx)
        {
            return true;
        }

        public override string GetHelp()
        {
            return "Evaluates the given code.";
        }

        public override string GetUsage()
        {
            return "eval <code>";
        }
    }
}


text:
set -x

apt-get update -y

apt-get upgrade -y

apt-get install -y git

apt-get install -y python-dev python-setuptools

apt-get install -y libtiff4-dev libjpeg8-dev zlib1g-dev \
        libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk


text:
<?php

/**
 * @file
 * Definition of Drupal\Core\Ajax\AlertCommand.
 */

namespace Drupal\Core\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * AJAX command for a javascript alert box.
 */
class AlertCommand implements CommandInterface {

  /**
   * The text to be displayed in the alert box.
   *
   * @var string
   */
  protected $text;

  /**
   * Constructs an AlertCommand object.
   *
   * @param string $text
   *   The text to be displayed in the alert box.
   */
  public function __construct($text) {
    $this->text = $text;
  }

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   */
  public function render() {

    return array(
      'command' => 'alert',
      'text' => $this->text,
    );
  }

}


text:
IF EXISTS(SELECT * FROM [dbo].[sysobjects] WHERE ID=object_id(N'[Client].[Locations_SelectBy_ContentInspectionId]') AND OBJECTPROPERTY(id, N'IsProcedure')=1) DROP PROC [Client].[Locations_SelectBy_ContentInspectionId]
GO--
CREATE PROCEDURE [Client].[Locations_SelectBy_ContentInspectionId]
			@ContentInspectionId int
AS --Generated--
BEGIN
	SET NOCOUNT ON;

	SELECT
			[LocationId],
			[ContentInspectionId],
			[LocationName],
			[IsArchived],
			[IsBeingProposed],
			[ProposedByUserId],
			[ConfirmedByUserId],
			[FalseInfoCount],
			[TrueInfoCount],
			[AdminInpsected],
			[DateLastChecked],
			[SourceUrl]
	FROM	[Client].[Locations]
	WHERE	[ContentInspectionId] = @ContentInspectionId

END


text:
renderpolygon
=============

Render 3D polygon in browser


text:
namespace {

class MissingPluginPlaceholder : public blink::WebPluginPlaceholder {
 public:
  // blink::WebPluginPlaceholder overrides
  blink::WebString message() const override {
    // TODO(jbroman): IDS_PLUGIN_SEARCHING if ENABLE_PLUGIN_INSTALLATION
    return l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED);
  }
};

}  // namespace

bool ShadowDOMPluginPlaceholderEnabled() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnablePluginPlaceholderShadowDom);
}

scoped_ptr<blink::WebPluginPlaceholder> CreateShadowDOMPlaceholderForPluginInfo(
    content::RenderFrame* render_frame,
    blink::WebLocalFrame* frame,
    const blink::WebPluginParams& orig_params) {
  using Status = ChromeViewHostMsg_GetPluginInfo_Status;

  if (!ShadowDOMPluginPlaceholderEnabled())
    return nullptr;

  std::string orig_mime_type = orig_params.mimeType.utf8();
  // TODO(jbroman): Investigate whether browser plugin needs special handling.
  ChromeViewHostMsg_GetPluginInfo_Output output;
#if defined(ENABLE_PLUGINS)
  render_frame->Send(
      new ChromeViewHostMsg_GetPluginInfo(render_frame->GetRoutingID(),
                                          GURL(orig_params.url),
                                          frame->top()->document().url(),
                                          orig_mime_type,
                                          &output));
#else
  output.status.value = Status::kNotFound;
#endif

  if (output.status.value == Status::kNotFound) {
    // TODO(jbroman): Handle YouTube specially here, as in
    // ChromeContentRendererClient::CreatePlugin.
    PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type,
                                                          orig_params.url);
    return CreateShadowDOMPlaceholderForMissingPlugin();
  }

  return nullptr;
}

scoped_ptr<blink::WebPluginPlaceholder>
CreateShadowDOMPlaceholderForMissingPlugin() {
  return make_scoped_ptr(new MissingPluginPlaceholder);
}


text:
import os
import subprocess
import sys

def Main():
  # TODO(ncbray): figure out why this is failing on windows and enable.
  if (sys.platform in ['win32', 'cygwin'] and
      'xp-nacl-chrome' not in os.environ.get('PWD', '')): return
  # TODO(ncbray): figure out why this is failing on mac and re-enable.
  if (sys.platform == 'darwin' and
      'mac-nacl-chrome' not in os.environ.get('PWD', '')): return
  # TODO(ncbray): figure out why this is failing on some linux trybots.
  if (sys.platform in ['linux', 'linux2'] and
      'hardy64-nacl-chrome' not in os.environ.get('PWD', '')): return

  script_dir = os.path.dirname(os.path.abspath(__file__))
  test_dir = os.path.dirname(script_dir)
  chrome_dir = os.path.dirname(test_dir)
  src_dir = os.path.dirname(chrome_dir)
  nacl_integration_script = os.path.join(
      src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py')
  cmd = [sys.executable, nacl_integration_script] + sys.argv[1:]
  print cmd
  subprocess.check_call(cmd)

if __name__ == '__main__':
  Main()


text:
c do continuum subtraction or division by taking a high percentile
c value in a (large) moving window
c for example, take the 90%ile value.  we don't want to take the
c maximum because some pixels will be bad or emission lines.
c this was inspired by Karl's method of taking the biweight of
c the top 1/3rd of the data - if you take the median of the
c top 1/3rd, it's the 83%ile by def.

c can be more efficient, as Karl did, by only taking the
c %ile every Nsamp pixels and interpolating, rather than
c recomputing at every pixel.

c wrad is the radius of the subtraction window, in wavelength
c or log(1+z), dw is the x-spacing
c do the subtraction in place, or not
c      subroutine contsubmed(spec,nsp,dwlog,wrad,specout)
      subroutine contdivpctile(spec,nsp,serr,dw,wrad)

c divide or subtract?
      parameter(IFDIVIDE=1)
c how many pixels apart the places to compute the %ile are at
      parameter(NSAMP=200)
c how many pixels to use to compute median.  This is redundant
c with having wrad as an input param.
c      parameter(NWIND=201)
c nvals is the max number of places to compute the %ile at, so
c nmaxvals*nsamp must be greater than the dimension of the input array, nsp
      parameter(NMAXVALS=250)
      parameter(IFDEBUG=0)

      real spec(nsp)
      real serr(nsp)
c      real specout(nsp)
      real swork(nsp)
      real tplot(nsp)
      real cvals(NMAXVALS),rivals(NMAXVALS)
      integer ivals(NMAXVALS)

c      external function select
c      external function selip
      external select
      external selip

      include 'pcredshift.h'

      pctfrac = 0.9

      nrad = int(wrad/dw)
      if (nrad .lt. 1) nrad=1
      if (IFDEBUG .ge. 2) write(*,*) "contdivpct: nrad = ",nrad

c indexes of central locations of windows
      ivals(1) = nrad+1
      nvals = int( (nsp-ivals(1))/real(NSAMP) ) + 1
      do j=2,nvals
         ivals(j) = ivals(1) + (j-1)*NSAMP
         if (IFDEBUG .ge. 2) write(*,*) "cdp: ",j,ivals(j)
      end do

c loop over locations; load pixels into window using swork, compute the
c 90th or whatever %ile with select, save in cvals
      do j=1,nvals
         imin = max(ivals(j)-nrad,1)
         imax = min(ivals(j)+nrad,nsp)
c         ntodo = imax-imin+1
         np = 0
         do i=imin,imax
            if (spec(i) .gt. bad) then
               np = np+1
               swork(np) = spec(i)
            end if
         end do
         if (np .gt. 0) then
            itmp = int(pctfrac*np)
            cvals(j) = select(itmp,np,swork)
            if (IFDEBUG .ge. 2) then
               write(*,*) "cdp: ",j,ivals(j),np,itmp,cvals(j)
            end if
         else
            cvals(j) = badset
         end if
      end do
      if (IFDEBUG .ge. 2) then
         do j=1,nvals
            write(*,*) "contdivpctile: ",j,ivals(j),cvals(j)
         end do
      end if

c go through locations and fix any that are equal to badset by
c interpolating between good values.  This shouldn't really happen.
      if (cvals(1) .lt. bad) cvals(1) = 0.0
      if (cvals(nvals) .lt. bad) cvals(nvals) = 0.0
      do j=2,nvals-1
         if (cvals(j) .lt. bad) then
            jprev = j-1
            jnext = j+1
c loop up to find next good value
 110        continue
            if (cvals(jnext) .lt. bad) then
               jnext = jnext+1
               go to 110
            end if
            if (IFDEBUG .ge. 2) then
               write(*,*) "contdivpctile fix: ",j,ivals(j),cvals(j),
     $              jprev,jnext,cvals(jprev),cvals(jnext)
            end if
            cvals(j) = cvals(jprev) +
     $        (j-jprev)/real(jnext-jprev) * (cvals(jnext)-cvals(jprev))
         end if
      end do

c now use swork at the full length of the spec array; interpolate the
c cvals points onto it to create a continuum array.  Points lower than
c the first or higher than the last are special cases
      do i=1,ivals(1)-1
         swork(i) = cvals(1) +
     $        (i-ivals(1))/real(ivals(2)-ivals(1)) * (cvals(2)-cvals(1))
      end do
      do j=1,nvals-1
         swork(ivals(j)) = cvals(j)
         do i=ivals(j),ivals(j+1)-1
            swork(i) = cvals(j) +
     $    (i-ivals(j))/real(ivals(j+1)-ivals(j)) * (cvals(j+1)-cvals(j))
         end do
      end do
      do i=ivals(nvals),nsp
         swork(i) = cvals(nvals) +
     $        (i-ivals(nvals-1))/real(ivals(nvals)-ivals(nvals-1)) *
     $        (cvals(nvals)-cvals(nvals-1))
      end do

      if (IFDEBUG .ge. 1) then
         smax = -1.e6
         smin = 1.e6
         do i=1,nsp
            tplot(i) = real(i)
            if (spec(i) .gt. bad) then
               smax = max(smax,spec(i))
               smin = min(smin,spec(i))
            end if
         end do
         if (smin .gt. 0.0) smin=0.0
         call pgenv(0.,real(nsp),smin,smax,0,1)
         call pglabel("index","flux","spectrum and continuum")
         call pgline(nsp,tplot,spec)
         call pgqci(indexc)
         call pgsci(3)
         call pgline(nsp,tplot,swork)
         call pgsci(2)
         do j=1,nvals
            rivals(j) = real(ivals(j))
         end do
         call pgpt(nvals,rivals,cvals,17)
         call pgsci(indexc)
c         call showspec(nsp,tplot,spec)
c         call showspec(nsp,tplot,swork)
      end if

c now we either divide or subtract the continuum in place
c if we do division, also have to divide the error.
      if (IFDIVIDE .eq. 0) then
         do i=1,nsp
            if (spec(i) .gt. bad) spec(i) = spec(i) - swork(i)
         end do
      else
         do i=1,nsp
            if (spec(i) .gt. bad) then
               if (swork(i) .gt. 1.e-4) then
                  spec(i) = spec(i) / swork(i)
                  serr(i) = serr(i) / swork(i)
               else
                  spec(i) = spec(i) / 1.e-4
                  serr(i) = serr(i) / 1.e-4
               end if
            end if
         end do
      end if

      return
      end


text:
package vpc

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DescribeCustomerGateway invokes the vpc.DescribeCustomerGateway API synchronously
func (client *Client) DescribeCustomerGateway(request *DescribeCustomerGatewayRequest) (response *DescribeCustomerGatewayResponse, err error) {
	response = CreateDescribeCustomerGatewayResponse()
	err = client.DoAction(request, response)
	return
}

// DescribeCustomerGatewayWithChan invokes the vpc.DescribeCustomerGateway API asynchronously
func (client *Client) DescribeCustomerGatewayWithChan(request *DescribeCustomerGatewayRequest) (<-chan *DescribeCustomerGatewayResponse, <-chan error) {
	responseChan := make(chan *DescribeCustomerGatewayResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DescribeCustomerGateway(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DescribeCustomerGatewayWithCallback invokes the vpc.DescribeCustomerGateway API asynchronously
func (client *Client) DescribeCustomerGatewayWithCallback(request *DescribeCustomerGatewayRequest, callback func(response *DescribeCustomerGatewayResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DescribeCustomerGatewayResponse
		var err error
		defer close(result)
		response, err = client.DescribeCustomerGateway(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DescribeCustomerGatewayRequest is the request struct for api DescribeCustomerGateway
type DescribeCustomerGatewayRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	CustomerGatewayId    string           `position:"Query" name:"CustomerGatewayId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
}

// DescribeCustomerGatewayResponse is the response struct for api DescribeCustomerGateway
type DescribeCustomerGatewayResponse struct {
	*responses.BaseResponse
	Asn               int64  `json:"Asn" xml:"Asn"`
	RequestId         string `json:"RequestId" xml:"RequestId"`
	IpAddress         string `json:"IpAddress" xml:"IpAddress"`
	Description       string `json:"Description" xml:"Description"`
	CustomerGatewayId string `json:"CustomerGatewayId" xml:"CustomerGatewayId"`
	CreateTime        int64  `json:"CreateTime" xml:"CreateTime"`
	Name              string `json:"Name" xml:"Name"`
	AuthKey           string `json:"AuthKey" xml:"AuthKey"`
}

// CreateDescribeCustomerGatewayRequest creates a request to invoke DescribeCustomerGateway API
func CreateDescribeCustomerGatewayRequest() (request *DescribeCustomerGatewayRequest) {
	request = &DescribeCustomerGatewayRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Vpc", "2016-04-28", "DescribeCustomerGateway", "vpc", "openAPI")
	request.Method = requests.POST
	return
}

// CreateDescribeCustomerGatewayResponse creates a response to parse from DescribeCustomerGateway response
func CreateDescribeCustomerGatewayResponse() (response *DescribeCustomerGatewayResponse) {
	response = &DescribeCustomerGatewayResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}