text:
function [scene,parms] = sceneCreate(sceneName,varargin)
% Create a scene structure.
%
%  [scene,parms] = sceneCreate(sceneName,varargin)
%
% A scene describes the photons emitted from each visible point in the
% scene. Generally, we model planar objects, such as a screen display.  The
% scene is located at some distance from the center of the optics, has a
% field of view, and a spectral radiance distribution.  There are routines
% to handle depth as well that are partly implemented and under
% development.  We plan to integrate this aspect of the modeling with PBRT.
%
% A variety of scene types can be created automatically.  The routines that
% create these scenes, including this one, serve as a template for creating
% others you may wish to design.
%
% Scenes are represented as photons with 32 bits of precision by default.
% The spectral representation is 400:10:700 by default.  Both of these can
% be changed.
%
% To resample with respect to wavelength use the function
% sceneInterpolateW.
%
% The create a scene with 16 bits of precision, call sceneCreate with the
% full list of opticnal arguments and then append two arguments as in
%
%  sceneCreate(<complete list of optional arguments>,'bit depth',16)
%
% MACBETH COLOR AND LUMINANCE CHART
%
%   The default, scene = sceneCreate, is a Macbeth color checker illuminated
%   by a D65 light source with a mean luminance of 100 cd/m2.  The scene is
%   described only a small number of spatial 64x96 (row,col).  This can be
%   changed using the patchSize argument (default - 16 pixels).  The
%   wavelength  400:10:700 samples, making it efficient to use for experiments.
%
%   Example:
%    scene = sceneCreate('macbeth',32);
%
%    patchSize = 8;
%    spectrum.wave = (380:4:1068)';
%    scene = sceneCreate('macbethEE_IR',patchSize,spectrum);
%
%      {'macbethd65'}  - Create a Macbeth D65 image.  Optional
%         parameter of patch size (default = 16 pixels).
%      {'macbethd50'}         - D50 illuminant
%      {'macbethillc'}        - Illuminant C
%      {'macbethfluorescent'} - Fluorescent illuminant
%      {'macbethtungsten'}    - Tungsten illuminant
%      {'macbethEE_IR'}       - Equal energy extends out to the IR
%
%   You can use sceneAdjustIlluminant() to change the scene SPD.  This
%   function runs on MCC and any other scene with an illuminant.
%
%   The size of the individual patches and the wavelength sampling are both
%   parameters. They can be set using the calling procedure
%
%         patchSizePixels = 16;
%         spectrum.wave = [380:5:720];
%         scene = sceneCreate('macbethTungsten',patchSizePixels,spectrum);
%
%     {L*-steps} - Vertical bars spaced in equal L* steps (dark -> light)
%     scene = sceneCreate('LSteps',barWidth=20,nBars=10,deltaE=10);
%
% REFLECTANCE SAMPLE CHART
%
%   {'reflectance chart'}       - Specify random reflectance samples from
%                                 database. There is always a gray strip at
%                                 the right.   Uses sceneReflectanceChart
%
%       pSize = 24;          % Patch size in pixels
%       sSamples = [64 64];  % Surface samples from the files
%       sFiles{1} = fullfile(isetRootPath,'data','surfaces','reflectances','MunsellSamples_Vhrel.mat');
%       sFiles{2} = fullfile(isetRootPath,'data','surfaces','reflectances','Food_Vhrel.mat');
%       sceneCreate('reflectance chart',pSize,sSamples,sFiles);
%
% NARROWBAND COLOR PATCHES
%    wave = [600, 610];  sz = 64;
%    scene = sceneCreate('uniform monochromatic',wave,sz);
%
% SPATIAL TEST PATTERNS:
%
%      {'rings rays'}            - Resolution pattern
%      {'harmonic'}              - Harmonics (can be sums of harmonics)
%      {'sweep frequency'}       - Increasing frequency to the right,
%               increasing contrast upward
%      {'line d65'}              - Line with D65 energy spectrum
%      {'line ee'}               - Line with equal energy spectrum
%      {'bar ee'}                - Vertical bar, equal energy
%      {'point array'}           - Point array
%      {'gridlines'}             - Grid lines
%      {'checkerboard'}          - Checkerboard with equal photon spectrum
%      {'frequency orientation'} - Demosaicking test pattern, equal photon spectrum
%      {'slanted edge'} - Used for ISO spatial resolution, equal photon spectrum
%      {'moire orient'} - Circular Moire pattern
%      {'zone plate'}   - Circular zone plot, equal photon spectrum
%      {'star pattern'} - Radial lines used to test printers and displays
%
%  Additional parameters are available for several of the patterns.  For
%  example, the harmonic call can set the frequency, contrast, phase,
%  angle, row and col size of the harmonic.  The frequency unit in this
%  case is cycles/image.  To obtain cycles per degree, divide by the field
%  of view.
%
%        parms.freq = 1; parms.contrast = 1; parms.ph = 0;
%        parms.ang= 0; parms.row = 128; parms.col = 128;
%        parms.GaborFlag=0;
%        [scene,parms] = sceneCreate('harmonic',parms);
%
%  See the script s_sceneHarmonics for more examples.  In this example, the
%  illuminant is set so that the mean of the harmonic has a 20%
%  reflectance, like a typical gray card.
%
%  Many of the patterns can have an arbitrary image (row,col) size.  This
%  is possible for whitenoise, impulse1dee,lined65,
%
%         imSize = 128; lineOffset = 25;           % Plus is to the right
%         scene = sceneCreate('lined65',imSize);
%         scene = sceneCreate('line ee',imSize,lineOffset);
%         sceneCreate('bar',imageSize,width);
%
%  Other patterns have different parameters:
%
%         sceneCreate('slanted edge',imageSize,edgeSlope);
%         sceneCreate('checkerboard',pixelsPerCheck,numberOfChecks)
%         sceneCreate('grid lines',imageSize,pixelsBetweenLines);
%         sceneCreate('point array',imageSize,pixelsBetweenPoints);
%         sceneCreate('moire orient',imageSize,edgeSlope);
%         sceneCreate('vernier',imageSize,lineWidth,pixelOffset);
%
% NOISE ANALYSIS TEST PATTERNS
%
%      {'linearIntensityRamp'}  -
%      {'uniformEqualEnergy'}   - Equal energy
%      {'uniformEqualPhoton'}   - Equal photon density
%      {'uniformd65'}           -
%      {'whitenoise'}           - Noise pattern for testing
%
%    The uniform patterns are small by default (32,32).  If you would like
%    them at a higher density (not much point), you can use
%
%        sceneCreate('uniformD65',256)
%
%    where 256 is the image size in pixels.
%
% SCENES FROM IMAGE DATA
%   We also create scenes using data in image files.  It is also possible
%   to simply read a tiff or jpeg file and create a scene structure.  These
%   image-based scenes created by sceneFromFile.  See the comments there
%   for more information.
%
% See also:  sceneFromFile
%
% Copyright ImagEval Consultants, LLC, 2003.

if ieNotDefined('sceneName'), sceneName = 'default'; end
parms = [];  % Returned in some cases, not many.

% Identify the object type
scene.type = 'scene';
scene = sceneSet(scene,'bit depth',32);   % Single precision
if length(varargin) > 1 && ischar(varargin{end-1})
    str = ieParamFormat(varargin{end-1});
    if isequal(str,'bitdepth')
        scene = sceneSet(scene,'bit depth',varargin{end});
    end
end
sceneName = ieParamFormat(sceneName);

switch sceneName
    case 'default'
        % The user can make a Macbeth with different patch sizes and
        % wavelength sampling, by calling with additional arguments, such
        % as scene = sceneCreate('macbethd65',16,spectrum);
        scene = sceneDefault(scene,'d65');
    case {'macbeth','macbethd65'}
        % sceneCreate('macbethD65',24);
        scene = sceneDefault(scene,'d65',varargin);
    case {'macbethd50'}
        scene = sceneDefault(scene,'d50',varargin);
    case {'macbethc','macbethillc'}
        scene = sceneDefault(scene,'c',varargin);
    case {'macbethfluorescent','macbethfluor'}
        scene = sceneDefault(scene,'fluorescent',varargin);
    case {'macbethtungsten','macbethtung'}
        scene = sceneDefault(scene,'tungsten',varargin);
    case {'macbethee_ir','macbethequalenergyinfrared'}
        % Equal energy illumination into the IR
        % The way to call this would be
        % patchSize = 16;
        % spectrum.wave = 380:4:1068;
        % scene = sceneCreate('macbethEE_IR',patchSize,spectrum)
        scene = sceneDefault(scene,'ir',varargin);
    case {'reflectancechart'}
        % sceneCreate('reflectance chart',pSize,sSamples,sFiles);
        % There is always a gray strip at the right.

        % Patch size in pixels
        pSize = 24;
        % Default surface files
        sFiles{1} = fullfile(isetRootPath,'data','surfaces','reflectances','MunsellSamples_Vhrel.mat');
        sFiles{2} = fullfile(isetRootPath,'data','surfaces','reflectances','Food_Vhrel.mat');
        % Surface samples from the files
        sSamples = [64 64];

        if isempty(varargin)
        else
            pSize = varargin{1};
            if length(varargin) > 1, sSamples = varargin{2}; end
            if length(varargin) > 2, sFiles = varargin{3}; end
        end
        scene = sceneReflectanceChart(sFiles,sSamples,pSize);

    case {'lstar'}
        scene = sceneSet(scene,'name','L-star');
        bWidth = 20; nBars = 10; deltaE = 10;
        if ~isempty(varargin)
            bWidth = varargin{1};
            if length(varargin)>1, nBars  = varargin{2}; end
            if length(varargin)>2, deltaE = varargin{3}; end
        end
        scene = sceneLstarSteps(scene,bWidth,nBars,deltaE);

        % Monochrome,RGB and multispectral add only a little.  Mostly created in sceneFromFile
    case {'monochrome','unispectral'}
        % sceneMonochrome is used for images with only one spectral band.
        scene = sceneMonochrome(scene);
    case {'multispectral','hyperspectral'}
        scene = sceneMultispectral(scene);
    case 'rgb'
        if isempty(varargin), scene = sceneRGB(scene);
        else scene = sceneRGB(varargin{1});end

    case {'mackay','rayimage','ringsrays'}
        % Also called the Siemens star pattern
        % radF = 24; imSize = 512;
        % vcAddAndSelectObject(sceneCreate('mackay',radF,imSize));
        % sceneWindow();
        radFreq = 8; sz = 256;
        if length(varargin) >= 1, radFreq = varargin{1}; end
        if length(varargin) >= 2, sz = varargin{2}; end
        if length(varargin) >= 3
            wave  = varargin{3};
            scene = sceneSet(scene,'wave',wave);
        end
        scene = sceneMackay(scene,radFreq,sz);
    case {'harmonic','sinusoid'}
        if isempty(varargin),
            [scene,parms] = sceneHarmonic(scene);
        elseif length(varargin) == 1
            parms = varargin{1};
            [scene,parms] = sceneHarmonic(scene,parms);
        elseif length(varargin) == 2
            parms = varargin{1};
            wave = varargin{2};
            [scene,parms] = sceneHarmonic(scene,parms, wave);
        else
            error('Wrong number of parameters! Input params structure and optional wavelengths.')
        end
    case {'sweep','sweepfrequency'}
        % These are always equal photon type.  Could add a third argument
        % for spectral type.
        % sz = 512; maxF = sz/16; sceneCreate('sweepFrequency',sz,maxF);
        sz = 128; maxFreq = sz/16;
        if length(varargin) >= 1, sz = varargin{1}; end
        if length(varargin) >= 2, maxFreq = varargin{2}; end
        scene = sceneSweep(scene,sz,maxFreq);
    case {'ramp','linearintensityramp','rampequalphoton'}
        if isempty(varargin),  sz = 32;
        else                   sz = varargin{1};
        end
        scene = sceneRamp(scene,sz);
    case {'uniform','uniformee','uniformequalenergy'}   %Equal energy
        if isempty(varargin),  sz = 32;
        else                   sz = varargin{1};
        end
        scene = sceneUniform(scene,'equalenergy',sz);

    case {'uniformeespecify'}   % Equal energy, specify waveband
        % scene = sceneCreate('uniformEESpecify',sz,wavelength);
        sz = 32; wavelength = 400:10:700;
        if ~isempty(varargin), sz = varargin{1}; end
        if length(varargin) > 1, wavelength = varargin{2}; end
        scene = sceneSet(scene,'wave',wavelength(:));
        scene = sceneUniform(scene,'equalenergy',sz);
    case {'uniformequalphoton','uniformephoton'}        %Equal photon density
        % sceneCreate('uniformEqualPhoton',128);
        if isempty(varargin)
            sz = 32;
            scene = sceneUniform(scene,'equal photons',sz);
        elseif length(varargin) == 1
            sz = varargin{1};
            scene = sceneUniform(scene,'equal photons',sz);
        elseif length(varargin) == 2
            sz = varargin{1};
            wave = varargin{2};
            scene = sceneUniform(scene,'equal photons',sz, wave);
        else
            error('Wrong number of arguments : looking for size (optional), wavelengths (optional)');
        end
    case 'uniformd65'
        % sceneCreate('uniformEqualPhoton',64);
        % We should include an option for wavelength so that we extend into
        % the IR
        if isempty(varargin),  sz = 32;
        else                   sz = varargin{1};
        end
        scene = sceneUniform(scene,'D65',sz);
    case {'uniformbb'}
        % scene = sceneCreate('uniformBB',64,5000,400:700);
        if ~isempty(varargin)
            if length(varargin) >= 1, sz = varargin{1}; end
            if length(varargin) >= 2, cTemp = varargin{2}; end
            if length(varargin) >= 3, scene = sceneSet(scene,'wave',varargin{3}); end
        else
            sz = 32; cTemp = 5000;
        end
        scene = sceneUniform(scene,'BB',sz,cTemp);
    case {'uniformmonochromatic'}
        % scene = sceneCreate('uniform monochromatic',sz,wavelength);

        % Create a uniform, monochromatic image.  Used for color-matching
        % analyses.  Set the peak radiance in photons.
        sz = 128; wavelength = 500;
        if length(varargin) >= 1, wavelength = varargin{1}; end
        if length(varargin) >= 2, sz = varargin{2}; end

        scene = sceneSet(scene,'wave',wavelength);
        scene = sceneUniform(scene,'equalenergy',sz);
        scene = sceneSet(scene,'name','narrow band');

    case {'lined65','impulse1dd65'}
        if isempty(varargin), sz = 64;
        else sz = varargin{1};
        end
        scene = sceneLine(scene,'D65',sz);
    case {'lineee','impulse1dee'}
        % scene = sceneCreate('line ee',size,offset,wave);
        % size:   Image row/col
        % offset: Pixel offset from center (c + offset)
        % wave:   Wavelength samples
        % scene = sceneCreate('lineee',128,2);
        % scene = sceneCreate('lineee',128,2,380:4:1068);
        sz = 64; offset = 0;
        if length(varargin) >= 1, sz = varargin{1};     end
        if length(varargin) >= 2, offset = varargin{2}; end
        if length(varargin) == 3
            scene = sceneSet(scene,'wave',varargin{3});
        end
        scene = sceneLine(scene,'equalEnergy',sz,offset);
    case {'lineequalphoton','lineep'}
        % sceneCreate('line ep',sz,offset);
        sz = 64; offset = 0;
        if length(varargin) >= 1, sz = varargin{1};     end
        if length(varargin) >= 2, offset = varargin{2}; end
        scene = sceneLine(scene,'equalPhoton',sz,offset);
    case {'bar'}
        % sceneCreate('bar',sz,width)
        sz = 64; width = 3;
        if length(varargin) >=1, sz    = varargin{1};   end
        if length(varargin) >=2, width = varargin{2};   end
        scene = sceneBar(scene,sz,width);
    case {'vernier'}
        % sceneCreate('vernier',size,width,offset)
        sz = 65; width = 3; offset = 3;
        if length(varargin) >=1, sz     = varargin{1};   end
        if length(varargin) >=2, width  = varargin{2};   end
        if length(varargin) ==3, offset = varargin{3};   end

        scene = sceneVernier(scene,sz,width,offset);
    case {'whitenoise','noise'}
        % sceneCreate('noise',[128 128])
        sz = 128; contrast = 20;
        if length(varargin) >= 1, sz = varargin{1}; end
        if length(varargin) >= 2, contrast = varargin{2}; end

        scene = sceneNoise(scene,sz,contrast);
        scene = sceneSet(scene,'name','white noise');

    case {'pointarray','manypoints'}
        % sceneCreate('pointArray',sz,spacing,spectralType);
        sz = 128; spacing = 16; spectralType = 'ep';
        if length(varargin) >= 1, sz           = varargin{1}; end
        if length(varargin) >= 2, spacing      = varargin{2}; end
        if length(varargin) >= 3, spectralType = varargin{3}; end
        scene = scenePointArray(scene,sz,spacing,spectralType);

    case {'gridlines','distortiongrid'}
        % sceneCreate('gridlines',sz,spacing,spectralType);
        sz = 128; spacing = 16; spectralType = 'ep';
        if length(varargin) >= 1, sz           = varargin{1}; end
        if length(varargin) >= 2, spacing      = varargin{2}; end
        if length(varargin) >= 3, spectralType = varargin{3}; end
        scene = sceneGridLines(scene,sz,spacing,spectralType);

    case {'checkerboard'}
        period = 16; spacing = 8; spectralType = 'ep';
        if length(varargin) >= 1, period       = varargin{1}; end
        if length(varargin) >= 2, spacing      = varargin{2}; end
        if length(varargin) >= 3, spectralType = varargin{3}; end
        scene = sceneCheckerboard(scene,period,spacing,spectralType);

    case {'demosaictarget','freqorientpattern','frequencyorientation','freqorient'}
        %   parms.angles = linspace(0,pi/2,5);
        %   parms.freqs =  [1,2,4,8,16];
        %   parms.blockSize = 64;
        %   parms.contrast = .8;
        % scene = sceneCreate('freqorient',parms);
        if isempty(varargin), scene = sceneFOTarget(scene);
        else
            % First argument is parms structure
            scene = sceneFOTarget(scene,varargin{1});
        end

    case {'moireorient'}
        %% Moire pattern test
        %   parms.angles = linspace(0,pi/2,5);
        %   parms.freqs =  [1,2,4,8,16];
        %   parms.blockSize = 64;
        %   parms.contrast = .8;
        % scene = sceneCreate('moire orient',parms);
        if isempty(varargin), scene = sceneMOTarget(scene);
        else
            % First argument is parms structure
            scene = sceneMOTarget(scene,varargin{1});
        end
    case {'slantedbar','iso12233','slantededge'}
        % scene = sceneCreate('slantedEdge',sz, slope, fieldOfView, wave);
        % scene = sceneCreate('slantedEdge',128,1.33);  % size, slope
        % scene = sceneCreate('slantedEdge',128,1.33,[], (380:4:1064));  % size, slope, wave
        barSlope = []; fov = []; wave = []; imSize = [];
        if length(varargin) >= 1, imSize = varargin{1}; end
        if length(varargin) >= 2, barSlope = varargin{2};  end
        if length(varargin) >= 3, fov = varargin{3}; end
        if length(varargin) >= 4, wave = varargin{4}; end
        scene = sceneSlantedBar(scene,imSize,barSlope,fov,wave);

    case {'zoneplate'}
        scene = sceneZonePlate(scene,384);
    case {'starpattern','radiallines'}
        % Thin radial lines - Useful for testing oriented blur
        %
        % scene = sceneCreate('starPattern');
        % scene = sceneCreate('starPattern',384);
        imSize = 256; spectralType = 'ep'; nLines = 8;
        if length(varargin) >=1, imSize = varargin{1}; end
        if length(varargin) >=2, spectralType = varargin{2}; end
        if length(varargin) >=3, nLines = varargin{3}; end
        scene = sceneRadialLines(scene,imSize,spectralType,nLines);

    otherwise
        error('Unknown scene format.');
end

% Initialize scene geometry, spatial sampling
scene = sceneInitGeometry(scene);
scene = sceneInitSpatial(scene);

% Scenes are initialized to a mean luminance of 100 cd/m2.  The illuminant
% is adjusted so that dividing the radiance (in photons) by the illuminant
% (in photons) produces the appropriate peak reflectance (default = 1).
%
% Also, a best guess is made about one known reflectance.
if checkfields(scene,'data','photons') && ~isempty(scene.data.photons)

    if isempty(sceneGet(scene,'knownReflectance')) && checkfields(scene,'data','photons')

        % nWave = sceneGet(scene,'nWave');

        % If there is no illuminant yet, set the illuminant to equal
        % photons at 100 cd/m2.
        if isempty(sceneGet(scene,'illuminant'))
            il = illuminantCreate('equal photons',sceneGet(scene,'wave'),100);
            scene = sceneSet(scene,'illuminant',il);
        end

        % There is no knownReflectance, so we set the peak radiance to a
        % reflectance of 0.9.
        v = sceneGet(scene,'peakRadianceAndWave');
        wave = sceneGet(scene,'wave');
        idxWave = find(wave == v(2));
        p = sceneGet(scene,'photons',v(2));
        [tmp,ij] = max2(p); %#ok<ASGLU>
        v = [0.9 ij(1) ij(2) idxWave];
        scene = sceneSet(scene,'knownReflectance',v);
    end

    luminance = sceneCalculateLuminance(scene);
    scene = sceneSet(scene,'luminance',luminance);

    % This routine also adjusts the illumination level to be consistent
    % with the reflectance and scene photons.
    scene = sceneAdjustLuminance(scene,100);
end

return;

%---------------------------------------------------
function scene = sceneNoise(scene,sz,contrast)
%% Make a spatial white noise stimulus
% contrast is the standard deviation of the N(0,contrast) noise.
% The noise is shifted to a mean of 0.5, and the level is clipped to a
% minimum of 0.

if ieNotDefined('sz'), sz = [128,128]; end
if ieNotDefined('contrast'), contrast = 0.20;
elseif contrast > 1, contrast = contrast/100;
end

scene = initDefaultSpectrum(scene,'hyperspectral');
wave  = sceneGet(scene,'wave');
nWave = sceneGet(scene,'nwave');

% This is an image with reasonable dynamic range (10x).
d   = randn(sz)*contrast + 1; d = max(0,d);

% This is a D65 illuminant
il = illuminantCreate('d65',wave,100);
p  = illuminantGet(il,'photons');
scene = sceneSet(scene,'illuminant',il);

%
photons = zeros(sz(1),sz(2),nWave);
for ii=1:nWave, photons(:,:,ii) = d*p(ii); end

% Allocate space for the (compressed) photons
scene = sceneSet(scene,'photons',photons);

% By setting the fov here, we will not override the value in
% sceneInitSpatial() when this returns
scene = sceneSet(scene,'fov',1);

return;

%----------------------------------
function scene = sceneDefault(scene,illuminantType,args)
%% Default scene is a Macbeth chart with D65 illuminant and patchSize 16
% pixels.

if ieNotDefined('illuminantType'), illuminantType = 'd65'; end
if ieNotDefined('args'), args = []; end

if (isempty(args) || isempty(args{1})), patchSize = 16;
else patchSize = args{1};
end

% Create the scene variable
scene = sceneSet(scene,'type','scene');
if isempty(args) || length(args) < 2 || isempty(args{2})
    scene = initDefaultSpectrum(scene,'hyperspectral');
else    scene = sceneSet(scene,'spectrum',args{2});
end
wave = sceneGet(scene,'wave');

switch lower(illuminantType)
    case 'd65'
        scene = sceneSet(scene,'name','Macbeth (D65)');
        lightSource = illuminantCreate('D65',wave,100);
    case 'd50'
        scene = sceneSet(scene,'name','Macbeth (D50)');
        lightSource = illuminantCreate('D50',wave,100);
    case 'fluorescent'
        scene = sceneSet(scene,'name','Macbeth (Fluorescent)');
        lightSource = illuminantCreate('Fluorescent',wave,100);
    case 'c'
        scene = sceneSet(scene,'name','Macbeth (Ill C)');
        lightSource = illuminantCreate('illuminantC',wave,100);
    case 'tungsten'
        scene = sceneSet(scene,'name','Macbeth (Tungsten)');
        lightSource = illuminantCreate('tungsten',wave,100);
    case 'ir'
        scene = sceneSet(scene,'name','Macbeth (IR)');
        lightSource = illuminantCreate('equalEnergy',wave,100);
    otherwise
        error('Unknown illuminant type.');
end

% Default distance in meters.
scene = sceneSet(scene,'distance',1.2);

% Scene magnification is always 1.
% Optical images have other magnifications that depend on the optics.
scene = sceneSet(scene,'magnification',1.0);

% The default patch size is 16x16.
spectrum = sceneGet(scene,'spectrum');
macbethChartObject = macbethChartCreate(patchSize,(1:24),spectrum);
scene = sceneCreateMacbeth(macbethChartObject,lightSource,scene);

return;

%--------------------------------------------------
function scene = sceneMonochrome(scene)
%% Default monochrome - should probably be eliminated
scene = sceneSet(scene,'name','monochrome');

% Probably should be eliminated.

% We set a default spectrum, but this is usually over-ridden, see
% sceneFromFile.
scene = initDefaultSpectrum(scene,'monochrome');

return;

%--------------------------------------------------
function scene = sceneMultispectral(scene)
%% Default multispectral structure

scene = sceneSet(scene,'name','multispectral');
scene = initDefaultSpectrum(scene,'multispectral');

return;

%--------------------------------------------------
function scene = sceneRGB(scene)
%% Prepare a scene for RGB data.

if ieNotDefined('scene'), scene.type = 'scene'; end

scene = sceneSet(scene,'name','rgb');
scene = sceneSet(scene,'type','scene');
scene = initDefaultSpectrum(scene,'hyperspectral');

% Set up an illuminant - but it is not nicely scaled.  And we don't have a
% known reflectance.
wave = sceneGet(scene,'wave');
il = illuminantCreate('d65',wave,100);
scene = sceneSet(scene,'illuminant',il);

return;

%--------------------------------------------------
function scene = sceneMackay(scene,radFreq,sz)
%% Someone (I think Chris Tyler) told me the ring/ray pattern is also called
% the Mackay chart.
%   Reference from Joyce here:
%
% Some people call it the Siemens Star pattern (Wueller).
%
% We fill the central circle with a masking pattern.  The size of the
% central region is at the point when the rays would start to alias.  The
% the circumference of the central circle is 2*pi*r (with r in units of
% pixels).  When the radial frequency is f, we need a minimum of 2f pixels
% on the circumference.  So the circumference is 2*pi*r, so that we want
% the radius to be at least r = f/pi.  In practice that is too exact for
% the digital domain.  So we double the radius.
%

if ieNotDefined('radFreq'), radFreq = 8; end
if ieNotDefined('sz'),      sz = 256; end

scene = sceneSet(scene,'name','mackay');

if ~isfield(scene,'spectrum')
    scene = initDefaultSpectrum(scene,'hyperspectral');
end
nWave = sceneGet(scene,'nwave');

img = imgMackay(radFreq,sz);

% Insert central circle mask
r = round(2*radFreq/pi);  % Find the radius for the central circle

% Find the distance from the center of the image
[X,Y] = meshgrid(1:sz,1:sz); X = X - mean(X(:)); Y = Y - mean(Y(:));
d = sqrt(X.^2 + Y.^2);

% Everything with a distance less than 2r set to mean gray (128) for now.
l = (d < r);
img(l) = 128;  % figure; imagesc(img)

scene = sceneSet(scene,'cphotons',repmat(img,[1,1,nWave]));

% Set up an illuminant
wave = sceneGet(scene,'wave');
il = illuminantCreate('equal photons',wave,100);
scene = sceneSet(scene,'illuminant',il);

return;

%--------------------------------------------------
function scene = sceneSweep(scene,sz,maxFreq)
%%  These are always equal photon

if ieNotDefined('sz'), sz = 128; end
if ieNotDefined('maxFreq'), maxFreq = sz/16; end

scene = sceneSet(scene,'name','sweep');
scene = initDefaultSpectrum(scene,'hyperspectral');
nWave = sceneGet(scene,'nwave');

img = imgSweep(sz,maxFreq);
img = img/max(img(:));

wave  = sceneGet(scene,'wave');
il    = illuminantCreate('equal photons',wave,100);
scene = sceneSet(scene,'illuminant',il);

img       = repmat(img,[1,1,nWave]);
[img,r,c] = RGB2XWFormat(img);
illP      = illuminantGet(il,'photons');
img       = img*diag(illP);
img       = XW2RGBFormat(img,r,c);
scene     = sceneSet(scene,'photons',img);

return;

%--------------------------------------------------
function [scene,p] = sceneHarmonic(scene,parms, wave)
%% Create a scene of a (windowed) harmonic function.
%
% Harmonic parameters are: parms.freq, parms.row, parms.col, parms.ang
% parms.ph, parms.contrast
%
% Missing default parameters are supplied by imageHarmonic.
%
% The frequency is with respect to the image (cyces/image).  To determine
% cycles/deg, use cpd: freq/sceneGet(scene,'fov');
%

scene = sceneSet(scene,'name','harmonic');

if ieNotDefined('wave')
    scene = initDefaultSpectrum(scene,'hyperspectral');
else
    scene = initDefaultSpectrum(scene, 'custom',wave);
end

nWave = sceneGet(scene,'nwave');

% TODO: Adjust pass the parameters back from the imgHarmonic window. In
% other cases, they are simply attached to the global parameters in
% vcSESSION.  We can get them by a getappdata call in here, but not if we
% close the window as part of imageSetHarmonic
if ieNotDefined('parms')
    global parms; %#ok<REDEF>
    h   = imageSetHarmonic; waitfor(h);
    img = imageHarmonic(parms);
    p   = parms;
    clear parms;
else
    [img,p] = imageHarmonic(parms);
end

% To reduce rounding error problems for large dynamic range, we set the
% lowest value to something slightly more than zero.  This is due to the
% ieCompressData scheme.
img(img==0) = 1e-4;
img   = img/(2*max(img(:)));    % Forces mean reflectance to 25% gray

% Mean illuminant at 100 cd
wave = sceneGet(scene,'wave');
il = illuminantCreate('equal photons',wave,100);
scene = sceneSet(scene,'illuminant',il);

img = repmat(img,[1,1,nWave]);
[img,r,c] = RGB2XWFormat(img);
illP = illuminantGet(il,'photons');
img = img*diag(illP);
img = XW2RGBFormat(img,r,c);
scene = sceneSet(scene,'photons',img);

return;

%--------------------------------------------------
function scene = sceneRamp(scene,sz)
%% Intensity ramp (see L-star chart for L* steps)

if ieNotDefined('sz'), sz = 128; end

scene = sceneSet(scene,'name','ramp');
scene = initDefaultSpectrum(scene,'hyperspectral');
nWave = sceneGet(scene,'nwave');
wave = sceneGet(scene,'wave');

img = imgRamp(sz);
img = img/(max(img(:)));

il = illuminantCreate('equal photons',wave,100);
scene = sceneSet(scene,'illuminant',il);

img = repmat(img,[1,1,nWave]);
[img,r,c] = RGB2XWFormat(img);
illP = illuminantGet(il,'photons');
img = img*diag(illP);
img = XW2RGBFormat(img,r,c);
scene = sceneSet(scene,'photons',img);

return;

%--------------------------------------------------
function scene = sceneUniform(scene,spectralType,sz,varargin)
%% Create a spatially uniform scene.
%
% Various spd types are supported, including d65, blackbody, equal energy,
% equal photon
%

if ieNotDefined('scene'), error('Scene required.'); end
if ieNotDefined('spectralType'), spectralType = 'ep'; end
if ieNotDefined('sz'), sz = 32; end
scene = sceneSet(scene,'name',sprintf('uniform-%s',spectralType));

if isempty(varargin)
    if ~isfield(scene,'spectrum')
        scene = initDefaultSpectrum(scene,'hyperspectral');
    end
end
wave  = sceneGet(scene,'wave');
nWave = sceneGet(scene,'nwave');

% 100% reflectance
d = ones(sz,sz,nWave);

spectralType = ieParamFormat(spectralType);
switch lower(spectralType)
    case {'d65','equalenergy','equalphotons','ee'}
        il = illuminantCreate(spectralType,wave);
    case {'blackbody'}
        if isempty(varargin), cTemp = 5000;
        else                  cTemp = varargin{1};
        end
        il = illuminantCreate('blackbody',wave,cTemp);
    otherwise
        error('Unknown spectral type:%s\n',spectralType);
end

% Set illuminant
scene = sceneSet(scene,'illuminant',il);

% Create scene photons
illP = sceneGet(scene,'illuminant photons');
for ii=1:nWave, d(:,:,ii) = d(:,:,ii)*illP(ii); end

scene = sceneSet(scene,'cphotons',d);

return;

%--------------------------------------------------
function scene = sceneLine(scene,spectralType,sz,offset)
%% Create a single line scene.
% This is used for computing linespreads and OTFs.

if ieNotDefined('spectralType'), spectralType = 'ep'; end
if ieNotDefined('sz'),     sz = 64; end
if ieNotDefined('offset'), offset = 0; end

scene = sceneSet(scene,'name',sprintf('line-%s',spectralType));

if ~isfield(scene,'spectrum')
    scene = initDefaultSpectrum(scene,'hyperspectral');
end
wave    = sceneGet(scene,'wave');
nWave   = sceneGet(scene,'nwave');

% Black is more than zero to prevent HDR problem with ieCompressData
linePos = round(sz/2) + offset;
photons = ones(sz,sz,nWave)*1e-4;
photons(:,linePos,:) = 1;

spectralType = ieParamFormat(spectralType);
% Figure out a way to do this using sceneSet.
switch lower(spectralType)
    case {'ep','equalphotons','ephoton','equalphoton'}
        % Equal number of photons at every wavelength
        il = illuminantCreate('equal photons',wave);
    case {'ee','equalenergy','eenergy'}
        % Equal energy at every wavelength.  The large scale factor applied
        % to the number of photons is just to produce a reasonable energy
        % level.
        il = illuminantCreate('equal energy',wave);

    case 'd65'
        % D65 spectra for the line
        il = illuminantCreate('d65',wave);

    otherwise
        error('Unknown uniform field type %s.',spectralType);
end

scene = sceneSet(scene,'illuminant',il);
p     = sceneGet(scene,'illuminant photons');
for ii=1:nWave, photons(:,:,ii) = photons(:,:,ii)*p(ii); end

scene = sceneSet(scene,'photons',photons);

return;

%--------------------------------------------------
function scene = sceneBar(scene,sz,width)
%% Create a single bar scene.
% This is used for computing the effect of scene dot density, say for a
% display with varying dots per inch.

if ieNotDefined('sz'),     sz = 64; end
if ieNotDefined('width'), width = 5; end

scene = sceneSet(scene,'name',sprintf('bar-%d',width));

if ~isfield(scene,'spectrum')
    scene = initDefaultSpectrum(scene,'hyperspectral');
end
wave    = sceneGet(scene,'wave');
nWave   = sceneGet(scene,'nwave');

% Black is more than zero to prevent HDR problem with ieCompressData
barPos = (1:width) + round((sz - width)/2);
photons = ones(sz,sz,nWave)*1e-8;   % Very dark reflectance mostly
photons(:,barPos,:) = 1;            % White reflectance in bar region

il = illuminantCreate('equal photons',wave);
scene = sceneSet(scene,'illuminant',il);
p     = sceneGet(scene,'illuminant photons');

% Create the radiance that matches reflectance and illuminant
for ii=1:nWave, photons(:,:,ii) = photons(:,:,ii)*p(ii); end

% Attach the photons to the scene
scene = sceneSet(scene,'photons',photons);

return

%------------------------
function scene = sceneVernier(scene,sz,width,offset)
%% Equal photon vernier targets
%
% Need to allow changing color of top and bottom, perhaps other features.
% We will create params structure for parameters in the future, i.e.,
% params.sz, params.width, params.lineReflectance, ... and so forth
%
if ieNotDefined('sz'),     sz = 64;    end
if ieNotDefined('width'),  width = 0;  end
if ieNotDefined('offset'), offset = 1; end

% Line and background reflectance
lineReflectance = 0.6;
backReflectance = 0.3;

scene = sceneSet(scene,'name',sprintf('vernier-%d',offset));

%% We make the image square
r = sz; c = sz;

% Make the column number odd so we can really center the top line
if ~isodd(c), c = c+1; end

% Vernier line size and offset
% Top and bottom half rows and columns
% Columns containing top line, shifted offset/2
topCols = (1:width) + round((c - width)/2) - floor(offset/2);

% Columns containing bottom line, shifted offset from top columns
% With this algorithm, the width of the
botCols = topCols + offset;

% Split the rows, too
topHalf = round(r/2);
topRows = 1:topHalf; botRows = (topHalf+1):r;

%% Init spectrum

if ~isfield(scene,'spectrum')
    scene = initDefaultSpectrum(scene,'hyperspectral');
end
wave    = sceneGet(scene,'wave');
nWave   = sceneGet(scene,'nwave');

%% Make the photon data
il    = illuminantCreate('equal photons',wave);
scene = sceneSet(scene,'illuminant',il);
illP  = sceneGet(scene,'illuminant photons');

photons = ones(r,c,nWave);
for ii=1:nWave
    photons(:,:,ii)     = backReflectance*photons(:,:,ii)*illP(ii);
    photons(topRows,topCols,ii)  = (lineReflectance/backReflectance)*photons(topRows,topCols,ii);
    photons(botRows,botCols,ii)  = (lineReflectance/backReflectance)*photons(botRows,botCols,ii);
end

scene = sceneSet(scene,'photons',photons);

return

%------------------------
function scene = sceneRadialLines(scene,imSize,spectralType,nLines)
%% sceneCreate('star pattern')
%  Create a Siemens Star (radial line) scene.
%
%   scene = sceneRadialLines(scene,imSize,spectralType,nLines)
%
% In this test chart the intensities along lines from the center are
% constant. Measuring on a circle around the center the intensity is a
% harmonic. Hence, frequency varies as a function of radial distance.
%
% Reference:
%   Dieter Wueller thinks this pattern is cool.
%   Digital camera resolution measurement using sinusoidal Siemens stars
%   Proc. SPIE, Vol. 6502, 65020N (2007); doi:10.1117/12.703817
%
% Examples:
%  scene = sceneCreate('radialLines');
%

if ieNotDefined('scene'), error('Scene must be defined'); end
if ieNotDefined('spectralType'), spectralType = 'ep'; end
if ieNotDefined('imSize'), imSize = 256; end
if ieNotDefined('nLines'), nLines = 8; end

scene = sceneSet(scene,'name',sprintf('radialLine-%s',spectralType));
scene = initDefaultSpectrum(scene,'hyperspectral');

% Determine the line angles
radians = pi*(0:(nLines-1))/nLines;
endPoints = zeros(nLines,2);
for ii=1:nLines
    endPoints(ii,:) = round([cos(radians(ii)),sin(radians(ii))]*imSize/2);
end
% plot(endPoints(:,1),endPoints(:,2),'o')

img = zeros(imSize,imSize);

% The routine for drawing lines could be better.
for ii=1:nLines
    x = endPoints(ii,1); y = endPoints(ii,2);
    u = -x; v = -y;
    % Flip so x is the lower one
    if x > 0,
        tmp = [x,y]; x = u; y = v; u = tmp(1); v = tmp(2);
    end

    if ~isequal(u,x), slope = (y - v) / (u - x);
        for jj=x:0.2:u,
            kk = round(jj*slope);
            img(round(kk + (imSize/2)) + 1, round(jj + (imSize/2)) + 1) = 1;
        end
    else img(:, (imSize/2) + 1) = 1;
    end
end

img = img(1:imSize,1:imSize);
% To reduce rounding error problems for large dynamic range, we set the
% lowest value to something slightly more than zero.  This is due to the
% ieCompressData scheme.
img(img==0) = 1e-4;
img = img/max(img(:));
% figure; imagesc(img)

% Create the photon image
wave    = sceneGet(scene,'wave');
nWave   = sceneGet(scene,'nwave');
photons = zeros(imSize,imSize,nWave);

% Figure out a way to do this using sceneSet.
spectralType = ieParamFormat(spectralType);
switch spectralType
    case {'ep','equalphoton','ephoton'}
        % Equal number of photons at every wavelength
        il = illuminantCreate('equal photons',wave);
    case {'ee','equalenergy','eenergy'}
        il = illuminantCreate('equal energy',wave);
    case 'd65'
        % D65 spectra for the line
        il = illuminantCreate('d65',wave);
    otherwise
        error('Unknown uniform field type %s.\n',spectralType);
end

scene = sceneSet(scene,'illuminant',il);
p     = sceneGet(scene,'illuminant photons');
for ii=1:nWave, photons(:,:,ii) = img(:,:)*p(ii); end

scene = sceneSet(scene,'photons',photons);

return;

%-----------------------
function scene = sceneFOTarget(scene,parms)
%% Frequency/Orientation target

if ieNotDefined('parms'), parms = []; end

scene = sceneSet(scene,'name','FOTarget');
scene = initDefaultSpectrum(scene,'hyperspectral');
nWave = sceneGet(scene,'nwave');

img = FOTarget('sine',parms);

% Prevent dynamic range problem with ieCompressData
img = ieClip(img,1e-4,1);
img = img/max(img(:));

% Create the illuminant
il = illuminantCreate('equal photons',sceneGet(scene,'wave'));
scene = sceneSet(scene,'illuminant',il);

% This routine returns an RGB image.  We base the final image on just the
% green channel
img = repmat(img(:,:,2),[1,1,nWave]);
[img,r,c] = RGB2XWFormat(img);
illP = illuminantGet(il,'photons');
img = img*diag(illP);
img = XW2RGBFormat(img,r,c);
scene = sceneSet(scene,'photons',img);

return;

%-----------------------
function scene = sceneMOTarget(scene,parms)
%% Moire/Orientation target

if ieNotDefined('parms'), parms = []; end

scene = sceneSet(scene,'name','MOTarget');
scene = initDefaultSpectrum(scene,'hyperspectral');
nWave = sceneGet(scene,'nwave');

% Select one among sinusoidalim, squareim, sinusoidalim_line, squareim_line, flat
% img = MOTarget('squareim',parms);
img = MOTarget('sinusoidalim',parms);

% Prevent dynamic range problem with ieCompressData
img = ieClip(img,1e-4,1);

% This routine returns an RGB image.  We take the green channel and expand
% it
scene = sceneSet(scene,'cphotons',repmat(img(:,:,2),[1,1,nWave]));

%
wave = sceneGet(scene,'wave');
illPhotons = ones(size(wave))*sceneGet(scene,'data max');
scene = sceneSet(scene,'illuminantPhotons',illPhotons);

return;

%-------------------
function scene = sceneCheckerboard(scene,checkPeriod,nCheckPairs,spectralType)
%% Checkerboard

if ieNotDefined('scene'), error('Scene required'); end
if ieNotDefined('checkPeriod'), checkPeriod = 16; end
if ieNotDefined('nCheckPairs'), nCheckPairs = 8; end
if ieNotDefined('spectralType'), spectralType = 'ep'; end

scene = sceneSet(scene,'name',sprintf('Checker-%s',spectralType));
scene = initDefaultSpectrum(scene,'hyperspectral');
wave  = sceneGet(scene,'wave');
nWave = sceneGet(scene,'nwave');

% The dynamic range of the checkerboard is kept to < 10^4 to prevent
% problems with the rounding error
d = checkerboard(checkPeriod,nCheckPairs);
d = d/max(d(:));

% Prevent ieCompressData problem.
d = ieClip(d,1e-6,1);
spectralType = ieParamFormat(spectralType);
switch spectralType
    case {'d65'}
        il = illuminantCreate('d65',wave);
    case {'ee','equalenergy'}
        il = illuminantCreate('equalenergy',wave);
    case {'ep','equalphoton','equalphotons'}
        il = illuminantCreate('equal photons',wave);
    otherwise
        error('Unknown spectral type:%s\n',spectralType);
end

img = zeros(size(d,1),size(d,2),nWave);
illP = illuminantGet(il,'photons');
for ii=1:nWave, img(:,:,ii) = d*illP(ii); end
scene = sceneSet(scene,'photons',img);

return

%---------------------------------------------------------------
function scene = sceneSlantedBar(scene,imSize,barSlope,fieldOfView,wave)
%%
%  Slanted bar, 2 deg field of view
%  Slope 2.6 (upper left to lower right)
%  Default size:  384
%
% The scene is set to equal photons across wavelength.

if ieNotDefined('imSize'),      imSize = 384; end
if ieNotDefined('barSlope'),    barSlope = 2.6; end
if ieNotDefined('fieldOfView'), fieldOfView = 2; end
if ieNotDefined('wave'),        wave = 400:10:700; end
scene = sceneSet(scene,'name','slantedBar');

scene = sceneSet(scene,'wave',wave);

wave = sceneGet(scene,'wave');
nWave  = sceneGet(scene,'nwave');

% Make the image
imSize = round(imSize/2);
[X,Y] = meshgrid(-imSize:imSize,-imSize:imSize);
img = zeros(size(X));

%  y = barSlope*x defines the line.  We find all the Y values that are
%  above the line
list = (Y > barSlope*X );

% We assume target is perfectly reflective (white), so the illuminant is
% the equal energy illuminant; that is, the SPD is all due to the
% illuminant
img( list ) = 1;

% Prevent dynamic range problem with ieCompressData
img = ieClip(img,1e-6,1);

% Now, create the illuminant
il = illuminantCreate('equal energy',wave);
scene = sceneSet(scene,'illuminant',il);
illP = illuminantGet(il,'photons');

% Create the scene photons
photons = zeros(size(img,1),size(img,2),nWave);
for ii=1:nWave, photons(:,:,ii) = img*illP(ii); end
scene = sceneSet(scene,'photons',photons);

% Set the field of view
scene = sceneSet(scene,'horizontalfieldofview',fieldOfView);

return;

%-----------------------
function scene = sceneZonePlate(scene,imSize,fieldOfView)
%% Circular zone plate image
%

if ieNotDefined('imSize'), imSize = 256; end
if ieNotDefined('fieldOfView'), fieldOfView = 4; end

scene = sceneSet(scene,'name','zonePlate');
scene = initDefaultSpectrum(scene,'hyperspectral');
nWave = sceneGet(scene,'nwave');

img = imgZonePlate(imSize);
% Prevent dynamic range problem with ieCompressData
img = ieClip(img,1e-4,1);

scene = sceneSet(scene,'cphotons',repmat(img,[1,1,nWave]));
scene = sceneSet(scene,'horizontalfieldofview',fieldOfView);

return

%-----------------------
function scene = sceneLstarSteps(scene,barWidth,nBars,deltaE)
%% Scene with vertical bars in equal L* steps
%
% scene = sceneCreate('lstar',50,5,10);
% vcAddAndSelectObject(scene); sceneWindow;

scene = initDefaultSpectrum(scene,'hyperspectral');

% Create the Y values that will define the intensities of the spd.  First,
% equal spaced L* values
L = (0:(nBars-1))*deltaE;
LAB = zeros(nBars,3);
LAB(:,1) = L(:);

% Transform them to Y values
C = makecform('lab2xyz');
XYZ = applyCform(LAB,C);
Y = XYZ(:,2); Y = Y/max(Y(:));
% vcNewGraphWin; plot(Y)

% Create equal photons illuminant
il = illuminantCreate('equal photons',sceneGet(scene,'nwave'),100);
scene = sceneSet(scene,'illuminant',il);

% Now, make the photon image
photons = ones(128,barWidth*nBars,nWave);
for ii=1:nBars
    start = barWidth*(ii-1) + 1; stop = barWidth*ii;
    for jj=1:nWave
        photons(:,start:stop,jj) = Y(ii)*illPhotons(jj);
    end
end

% The level is scaled on return to a mean of 100 cd/m2.
scene = sceneSet(scene,'photons',photons);

return


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

namespace EPS\PhpUri\Tests\Validator;

use EPS\PhpUri\Exception\ValidatorException;
use EPS\PhpUri\Validator\QueryValidator;
use PHPUnit\Framework\TestCase;

class QueryValidatorTest extends TestCase
{
    /**
     * @var QueryValidator
     */
    private $validator;

    protected function setUp()
    {
        parent::setUp();

        $this->validator = new QueryValidator();
    }

    /**
     * @test
     */
    public function itShouldReturnTrueForValidQuery()
    {
        $query = 'http://example.com/some/path?q=1&q=2';
        $actualResult = $this->validator->validate($query);

        static::assertTrue($actualResult);
    }

    /**
     * @test
     */
    public function itShouldThrowOnInvalidQuery()
    {
        $this->expectException(ValidatorException::class);
        $this->expectExceptionMessageRegExp('/Invalid query/');

        $query = 'http://example.com/some/path?q[0]=3';
        $this->validator->validate($query);
    }

    /**
     * @test
     */
    public function itShouldBeValidForEmptyQuery()
    {
        $validUri = 'http://example.com/some/path#Fragment';
        $actualResult = $this->validator->validate($validUri);

        static::assertTrue($actualResult);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

describe "articles/feedback_rss_feed.rss.builder", :type => :view do
  let!(:blog) { build_stubbed :blog }

  describe "with feedback consisting of one trackback and one comment" do
    let(:article) { stub_full_article }
    let(:trackback) { build(:trackback, :article => article) }
    let(:comment) { build(:comment, :article => article, :body => "Comment body") }

    before(:each) do
      assign(:feedback, [trackback, comment])
      render
    end

    it "renders a valid feed" do
      assert_feedvalidator rendered
    end

    it "renders an RSS feed with two items" do
      assert_rss20 rendered, 2
    end

    it "renders the trackback RSS partial once" do
      expect(view).to render_template(:partial => "shared/_rss_item_trackback", :count => 1)
    end

    it "renders the comment RSS partial once" do
      expect(view).to render_template(:partial => "shared/_rss_item_comment", :count => 1)
    end
  end
end


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Senecio jailicola Juz.

### Remarks
null


text:
package com.nexuslink.cyclenavi.Presenter.Interface;

import android.hardware.SensorEvent;

/**
 * Created by Rye on 2017/3/29.
 */

public interface IHorizentalPresenter{
    void caculateDegree(SensorEvent sensorEvent);

    void caculatePress(SensorEvent sensorEvent);
}


text:
package com.github.kimmokarlsson.somvis.som.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import com.github.kimmokarlsson.somvis.som.CellWeightVariable;
import com.github.kimmokarlsson.somvis.som.SelfOrganizingMap;
import com.github.kimmokarlsson.somvis.som.SomFileIO;

/**
 * Main window of the GUI.
 */
public class SomVisualizer implements MenuItemSelectionListener
{
    private SomFileIO somio;
    private JFrame frame;
    private File currentDirectory;
    private ClusterInfoPanel clusterPanel;
    private HexCanvas canvas;
    private ColorizationPanel colorizationPanel;

    public SomVisualizer(File configFile, File dataFile) throws IOException
    {
        somio = new SomFileIO();
        if (configFile != null)
        {
            somio.config(configFile);
        }
        if (dataFile != null && somio != null)
        {
            somio.loadMap(dataFile);
        }
        if (configFile != null)
        {
            currentDirectory = configFile.getParentFile();
        }
        else
        {
            currentDirectory = new File(".");
        }
    }

    public void openDialog()
    {
        frame = new JFrame("SOM Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 900, 800);
        Container root = frame.getContentPane();
        root.setLayout(new BorderLayout());

        SelfOrganizingMap som = somio.getSom();
        CellInfoPanel infoPanel = new CellInfoPanel(somio);
        infoPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        CellWeightVariable.INSTANCE.setMaxValue(som == null ? 1 : som.getMaxCellWeight());

        canvas = new HexCanvas( somio );
        createMenu();

        colorizationPanel = new ColorizationPanel(frame, canvas, somio);
        clusterPanel = new ClusterInfoPanel(somio);
        canvas.addCellSelectionListener(clusterPanel);
        canvas.addCellSelectionListener(infoPanel);
        JSplitPane bottomPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(clusterPanel), new JPanel());
        JSplitPane midPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(colorizationPanel), bottomPane);
        JSplitPane leftPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(infoPanel), midPane);
        JSplitPane main = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, new JScrollPane(canvas));
        main.setOneTouchExpandable(true);

        root.add(main, BorderLayout.CENTER);
        frame.getRootPane().setDoubleBuffered(true);

        frame.setVisible(true);
        main.setDividerLocation(0.33);
        leftPane.setDividerLocation(0.25);
        midPane.setDividerLocation(0.35);
        bottomPane.setDividerLocation(0.80);
        canvas.init();
        clustering();

        SwingUtilities.invokeLater(new Runnable() {
            @Override public void run() {
                canvas.zoomToFit();
                canvas.getParent().repaint();
            }});
    }

    private void createMenu()
    {
        JMenuBar mb = new JMenuBar();
        frame.setJMenuBar(mb);

        JMenu fileMenu = mb.add(new JMenu("File"));
        JMenu viewMenu = mb.add(new JMenu("View"));
        fileMenu.add(createMenuItem("Open...", KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK, this, SomVisualizerMenuItems.ITEM_CODE_OPEN));
        fileMenu.add(createMenuItem("Exit", KeyEvent.VK_Q, KeyEvent.CTRL_DOWN_MASK, this, SomVisualizerMenuItems.ITEM_CODE_EXIT));
        viewMenu.add(createMenuItem("Zoom In", KeyEvent.VK_PLUS, KeyEvent.CTRL_DOWN_MASK, canvas, HexCanvasMenuItems.ITEM_CODE_ZOOM_IN));
        viewMenu.add(createMenuItem("Zoom Out", KeyEvent.VK_MINUS, KeyEvent.CTRL_DOWN_MASK, canvas, HexCanvasMenuItems.ITEM_CODE_ZOOM_OUT));
        viewMenu.add(createMenuItem("Reset Zoom", KeyEvent.VK_0, KeyEvent.CTRL_DOWN_MASK, canvas, HexCanvasMenuItems.ITEM_CODE_ZOOM_RESET));
        viewMenu.add(createMenuItem("Zoom To Fit", KeyEvent.VK_EQUALS, KeyEvent.CTRL_DOWN_MASK, canvas, HexCanvasMenuItems.ITEM_CODE_ZOOM_FIT));
    }

    private JMenuItem createMenuItem(String title, int keyCode, int modifiers, final MenuItemSelectionListener lis, final int itemCode)
    {
        JMenuItem item = new JMenuItem(new AbstractAction(title) {
            @Override
            public void actionPerformed(ActionEvent evt) {
                lis.itemSelected(itemCode);
            }});
        item.setAccelerator(KeyStroke.getKeyStroke(keyCode, modifiers));
        return item;
    }

    @Override
    public void itemSelected(int itemCode)
    {
        if (itemCode == SomVisualizerMenuItems.ITEM_CODE_EXIT)
        {
            System.exit(0);
        }
        else if (itemCode == SomVisualizerMenuItems.ITEM_CODE_OPEN)
        {
            JFileChooser dialog = new JFileChooser(currentDirectory);
            dialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
            File configFile = null;
            if (dialog.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
            {
                configFile = dialog.getSelectedFile();
            }
            if (configFile != null)
            {
                loadMap(configFile);
            }
        }
    }

    private void loadMap(File configFile)
    {
        File dataFile = new File(configFile.getParentFile(), configFile.getName().replace("config.json", "data.jsonrows"));
        try
        {
            somio.config(configFile).loadMap(dataFile);
            setSom(somio.getSom());
        }
        catch (IOException e)
        {
            System.out.println("Error loading map: "+ configFile.getAbsolutePath() + ", data: "+ dataFile.getAbsolutePath());
            e.printStackTrace();
        }
    }

    private void setSom(SelfOrganizingMap som)
    {
        CellWeightVariable.INSTANCE.setMaxValue(som.getMaxCellWeight());
        canvas.repaint();
        colorizationPanel.reset();
        clusterPanel.reset();
        clustering();
        canvas.zoomToFit();
    }

    private void clustering()
    {
        if (somio.getSom() != null)
        {
            System.out.println("Clustering start.");
            long startTime = System.currentTimeMillis();
            somio.getSom().getUnifiedDistanceMatrix(true, true);
            System.out.println("Clustering done in " + (System.currentTimeMillis()-startTime) + " ms.");
        }
    }

    public static void main(String[] args)
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        try
        {
            File configFile = null;
            File dataFile = null;
            if (args.length >= 2)
            {
                configFile = new File(args[0]);
                dataFile = new File(args[1]);
                if (!configFile.exists())
                {
                    throw new FileNotFoundException(configFile.getAbsolutePath());
                }
                if (!dataFile.exists())
                {
                    throw new FileNotFoundException(dataFile.getAbsolutePath());
                }
            }
            new SomVisualizer(configFile, dataFile).openDialog();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}


text:
export {default as LightCinematic} from './lib/LightCinematic';
export {default as LightManager} from './lib/LightManager';

export {default as ICinematic} from './lib/ICinematic';
export {default as ISpritesheet} from './lib/ISpritesheet';
export {default as IStage} from './lib/IStage';


text:
/**
 * Created by jaaha on 2017-08-27.
 */
@ParametersAreNonnullByDefault
package com.tempestas.dependency.util.concurrent;

import javax.annotation.ParametersAreNonnullByDefault;


text:
namespace base {
class Thread;
class TickClock;
class TimeTicks;
}

namespace mojo {
namespace common {
namespace test {
class HandleWatcherTest;
}

// HandleWatcher is used to asynchronously wait on a handle and notify a Closure
// when the handle is ready, or the deadline has expired.
class MOJO_COMMON_EXPORT HandleWatcher {
 public:
  HandleWatcher();
  ~HandleWatcher();

  // Starts listening for |handle|. This implicitly invokes Stop(). In other
  // words, Start() performs one asynchronous watch at a time. It is ok to call
  // Start() multiple times, but it cancels any existing watches. |callback| is
  // notified when the handle is ready, invalid or deadline has passed and is
  // notified on the thread Start() was invoked on.
  void Start(const Handle& handle,
             MojoWaitFlags wait_flags,
             MojoDeadline deadline,
             const base::Callback<void(MojoResult)>& callback);

  // Stops listening. Does nothing if not in the process of listening.
  void Stop();

  // Returns now. Used internally; generally not useful.
  static base::TimeTicks NowTicks();

  // Converts a MojoDeadline into a TimeTicks.
  static base::TimeTicks MojoDeadlineToTimeTicks(MojoDeadline deadline);

 private:
  friend class test::HandleWatcherTest;
  struct StartState;

  // See description of |StartState::weak_factory| for details.
  void OnHandleReady(MojoResult result);

  // If non-NULL Start() has been invoked.
  scoped_ptr<StartState> start_state_;

  // Used for getting the time. Only set by tests.
  static base::TickClock* tick_clock_;

  DISALLOW_COPY_AND_ASSIGN(HandleWatcher);
};

}  // namespace common
}  // namespace mojo

#endif  // MOJO_COMMON_HANDLE_WATCHER_H_


text:
@REM don't watch the sausage being made
@ECHO OFF

REM the folder this script is in (*/bootplate/tools)
SET TOOLS=%~DP0

REM enyo location
SET ENYO=%TOOLS%\..\enyo

REM deploy script location
SET DEPLOY=%ENYO%\tools\deploy.js

REM node location
SET NODE=node.exe

REM use node to invoke deploy.js with imported parameters
%NODE% "%DEPLOY%" %*

SET BIN=%TOOLS%\..\bin
mkdir %BIN%

copy appinfo.json deploy\org.webosports.app.calculator
call palm-package deploy\org.webosports.app.calculator -o %BIN%


text:
This solution contains a simple project illustrating the following elements of a **Licensed** application in a **Desktop** environment:

* an Online Activation page
* expired subscription license(s) notification(s)
* manual renewal of expired subscription license(s)

The application uses WPF without any dependency on third party packages (e.g. MVVM frameworks).

# Configuring The Sample
## Create the product

* Navigate to the [Software Potential service product page](https://srv.softwarepotential.com/Products.aspx)
* Create a product entitled `Demo` with version `1.0` (case-sensitive) in a non-production account
  * Add two Features (`Feature1`,`Feature2`)

## Install the NuGet packages
* Add the SoftwarePotential NuGet feed (`https://srv.softwarepotential.com/NuGet/nuget/`) in your Package Manager settings
* Add the following package references:
 * `SoftwarePotential.Protection-<PermutationShortCode>`
 * `SoftwarePotential.Configuration.Local.SingleUser-<PermutationShortCode>`
 * `SoftwarePotential.Licensing-Demo_10`

# Using The Sample
## Activating a license

* Generate a license for the Product `Demo` and Version `1.0` via the [Software Potential service](https://srv.softwarepotential.com/Issue.aspx?IssueType=new)
 * Create a license for product `Demo 1.0` (**Manage Licenses|Issue New Licenses** on the site)
  * Add a Feature (e.g., `Feature1`)
* Paste the license key into the activation form (**Licenses|Activate** on the sample's menu)

## Renewing licenses

* Select **Licenses|Manage Licenses** on the menu
* Expired Subscription Licenses are displayed
* Click renew

# Troubleshooting

The most common problems reported with the sample are:

## Sample won't compile

* Ensure you have added the following NuGet packages to the `DemoApp` project:
 * `SoftwarePotential.Protection-<PermutationShortCode>`
 * `SoftwarePotential.Configuration.Local.SingleUser-<PermutationShortCode>`
 * `SoftwarePotential.Licensing-Demo_10`

## License will not activate

* Ensure _Locking_ is set to **Machine** (the `Sp.Agent` runtime does not support other binding styles)

## Packages Not Displaying in NuGet feed

* Your permutation may be too old to have packages associated with it.
 * Update your permutation on the [Software Potential service's permutations section in the account page](https://srv.softwarepotential.com/Permutations.aspx)
* You have not created the `Demo` product

## Documentation

Please see below for a list of recommended reading, ranging from Getting Started guides to more detailed technical documentation:

* [Getting Started with Subscription Licenses](https://support.softwarepotential.com/hc/en-us/articles/115001367349-Getting-Started-Subscription-Licenses)
* [Getting Started - Licensing with Software Potential](https://support.softwarepotential.com/hc/en-us/articles/115001354529-Getting-Started-Licensing-with-Software-Potential)
* [Licensing-README](https://support.softwarepotential.com/hc/en-us/articles/115001358849-Licensing-README)
* [SoftwarePotential.Configuration.Local.SingleUser-README](https://support.softwarepotential.com/hc/en-us/articles/115001365849--SingleUser-Configuration-README)
* [Software Potential NuGet Feed](https://support.softwarepotential.com/hc/en-us/articles/115001371425-Getting-Started-Software-Potential-NuGet-Feed)
* [Software Potential APIs](http://api.softwarepotential.com/index.html)

## Support
If you run into any issues visit the [Software Potential support page](https://support.softwarepotential.com) for more detailed information or to submit a help request.

Good luck!


text:
<?php

namespace cahis\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use cahis\ParametrizarBundle\Entity\Cliente;
use cahis\ParametrizarBundle\Entity\Paciente;
use cahis\ParametrizarBundle\Entity\Afiliacion;
use cahis\AdminBundle\Form\AfiliacionType;

class AfiliacionController extends Controller
{

    public function saveAction($paciente)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $paciente = $em->getRepository('ParametrizarBundle:Paciente')->find($paciente);

        if (!$paciente) {
            throw $this->createNotFoundException('El paciente solicitado no existe.');
        }

        $entity  = new Afiliacion();
        $request = $this->getRequest();
        $form    = $this->createForm(new AfiliacionType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {

            $afiliacion = $em->getRepository('ParametrizarBundle:Afiliacion')->findBy(array('cliente' => $entity->getCliente()->getId(), 'paciente' => $paciente->getId()));

            if($afiliacion){
                $this->get('session')->setFlash('info', 'La asociación ya existe.');

                return $this->redirect($this->generateUrl('paciente_show', array("id" => $paciente->getId())));
            }

            $entity->setPaciente($paciente);
            $em->persist($entity);
            $em->flush();

            $this->get('session')->setFlash('info', 'La asociación ha sido registrada éxitosamente.');

            return $this->redirect($this->generateUrl('paciente_show', array("id" => $paciente->getId())));

        }

        return $this->render('AdminBundle:Paciente:show.html.twig', array(
                'paciente' => $paciente,
                'form'   => $form->createView()
        ));

    }

    public function deleteAction($paciente, $cliente)
    {

            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('ParametrizarBundle:Afiliacion')->find(array('cliente' => $cliente, 'paciente' => $paciente));

            if (!$entity) {
                throw $this->createNotFoundException('La asociación a eliminar no existe.');
            }

            $em->remove($entity);
            $em->flush();

            $this->get('session')->setFlash('info', 'La asociación ha sido eliminada éxitosamente.');

            return $this->redirect($this->generateUrl('paciente_show', array("id" => $paciente)));
    }

    public function ajaxSaveAction()
    {
    	$request = $this->get('request');

    	$paciente = $request->request->get('paciente');
    	$cliente = $request->request->get('cliente');

    	if($paciente && $cliente){
    		$em = $this->getDoctrine()->getEntityManager();

    		$paciente = $em->getRepository('ParametrizarBundle:Paciente')->findOneBy(array('identificacion' => $paciente));
    		$cliente = $em->getRepository('ParametrizarBundle:Cliente')->find($cliente);

    		if($paciente && $cliente){

    			$afiliacion = $em->getRepository('ParametrizarBundle:Afiliacion')->findBy(array('cliente' => $cliente->getId(), 'paciente' => $paciente->getId()));

    			if($afiliacion){
    				$response=array("responseCode"=>400, "msg"=>"El cliente ya se encuentra asociado al paciente.");
    			}else{
    				$entity  = new Afiliacion();

    				$entity->setPaciente($paciente);
    				$entity->setCliente($cliente);
    				$em->persist($entity);
    				$em->flush();

    				$response=array("responseCode"=>200, "msg"=>"El cliente ha sido agregado correctamente.");

    				$response['id']= $entity->getCliente()->getId();
    				$response['nombre']= $entity->getCliente()->getNombre();
    			}
    		}else{
    			$response=array("responseCode"=>400, "msg"=>"El cliente ingresado aun no existe en el sistema.");
    		}
    	}

    	$return=json_encode($response);
    	return new Response($return,200,array('Content-Type'=>'application/json'));
    }

}


text:
package io.pravega.segmentstore.server.host;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.pravega.common.Exceptions;
import io.pravega.common.LoggerHelpers;
import io.pravega.common.cluster.Host;
import io.pravega.common.cluster.HostContainerMap;
import io.pravega.common.concurrent.AsyncSemaphore;
import io.pravega.common.concurrent.Futures;
import io.pravega.common.util.CollectionHelpers;
import io.pravega.segmentstore.server.ContainerHandle;
import io.pravega.segmentstore.server.SegmentContainerRegistry;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.utils.ZKPaths;

/**
 * Monitors the current set of running segment containers and ensure it matches the ownership assignment for this host.
 * This monitor watches the shared zk entry that contains the segment container ownership information
 * and starts or stops appropriate segment containers locally. Any start failures are periodically retried until
 * the desired ownership state is achieved.
 */
@SuppressWarnings("deprecation")
@Slf4j
public class ZKSegmentContainerMonitor implements AutoCloseable {

    private static final Duration INIT_TIMEOUT_PER_CONTAINER = Duration.ofSeconds(30L);
    private static final Duration CLOSE_TIMEOUT_PER_CONTAINER = Duration.ofSeconds(30L);
    private static final Duration MONITOR_INTERVAL = Duration.ofSeconds(10);
    private static final long REPORT_INTERVAL_MILLIS = Duration.ofMinutes(10).toMillis();
    private static final Supplier<Long> CURRENT_TIME_MILLIS = System::currentTimeMillis;

    // The host entry for which we are monitoring the container assignments.
    private final Host host;
    private final AtomicBoolean closed = new AtomicBoolean(false);

    // The zkNode which contains the segment container to host assignment.
    private final NodeCache hostContainerMapNode;
    private final SegmentContainerRegistry registry;

    // The list of container handles which are currently running in this node.
    private final Map<Integer, ContainerHandle> handles;

    // The list of containers which have ongoing start/stop tasks pending. This list is needed to ensure
    // we don't initiate conflicting tasks for the same containerId.
    private final Set<Integer> pendingTasks;
    private final ScheduledExecutorService executor;
    private AtomicReference<ScheduledFuture<?>> assignmentTask;
    private final AtomicLong lastReportTime;

    // Throttle the max number of parallel container starts/recoveries.
    private final AsyncSemaphore parallelContainerStartsSemaphore;

    /**
     * Creates an instance of ZKSegmentContainerMonitor.
     *
     * @param containerRegistry      The registry used to control the container state.
     * @param zkClient               The curator client.
     * @param pravegaServiceEndpoint The pravega endpoint for which we need to fetch the container assignment.
     */
    ZKSegmentContainerMonitor(SegmentContainerRegistry containerRegistry, CuratorFramework zkClient,
                              Host pravegaServiceEndpoint, int parallelContainerStarts, ScheduledExecutorService executor) {
        Preconditions.checkNotNull(zkClient, "zkClient");
        Preconditions.checkArgument(parallelContainerStarts > 0, "parallelContainerStarts");

        this.registry = Preconditions.checkNotNull(containerRegistry, "containerRegistry");
        this.host = Preconditions.checkNotNull(pravegaServiceEndpoint, "pravegaServiceEndpoint");
        this.executor = Preconditions.checkNotNull(executor, "executor");
        this.handles = new ConcurrentHashMap<>();
        this.pendingTasks = new ConcurrentSkipListSet<>();
        String clusterPath = ZKPaths.makePath("cluster", "segmentContainerHostMapping");
        this.hostContainerMapNode = new NodeCache(zkClient, clusterPath);
        this.assignmentTask = new AtomicReference<>();
        this.lastReportTime = new AtomicLong(CURRENT_TIME_MILLIS.get());
        this.parallelContainerStartsSemaphore = new AsyncSemaphore(parallelContainerStarts, 0, this.getClass().getName());
    }

    /**
     * Initialize the monitor. This will start the monitor thread which will process the start/stop container events.
     */
    public void initialize() {
        initialize(MONITOR_INTERVAL);
    }

    @VisibleForTesting
    @SneakyThrows(Exception.class)
    public void initialize(Duration monitorInterval) {
        Exceptions.checkNotClosed(closed.get(), this);

        // Start loading the segment container to node assignment map from zookeeper.
        this.hostContainerMapNode.start();

        // There are two triggers for the segment container monitor.
        // 1. On any segment container ownership changes notified via zookeeper. We will ensure the local containers
        //      are stopped/started according to the new ownership mapping.
        // 2. At scheduled intervals to perform retries on local segment container start failures.
        this.assignmentTask.set(this.executor.scheduleWithFixedDelay(
                this::checkAssignment, 0L, monitorInterval.getSeconds(), TimeUnit.SECONDS));
        this.hostContainerMapNode.getListenable().addListener(this::checkAssignment, this.executor);
    }

    @Override
    public void close() {
        Preconditions.checkState(closed.compareAndSet(false, true));
        try {
            this.hostContainerMapNode.close();
        } catch (IOException e) {
            // Ignoring exception on shutdown.
            log.warn("Failed to close hostContainerMapNode", e);
        }

        val task = this.assignmentTask.getAndSet(null);
        if (task != null) {
            task.cancel(true);
        }

        ArrayList<ContainerHandle> toClose = new ArrayList<>(this.handles.values());
        ArrayList<CompletableFuture<Void>> results = new ArrayList<>();
        for (ContainerHandle handle : toClose) {
            results.add(this.registry.stopContainer(handle, CLOSE_TIMEOUT_PER_CONTAINER)
                                     .thenAccept(v -> unregisterHandle(handle.getContainerId())));
        }

        // Wait for all the containers to be closed.
        Futures.await(Futures.allOf(results), CLOSE_TIMEOUT_PER_CONTAINER.toMillis());
    }

    @VisibleForTesting
    Collection<Integer> getRegisteredContainers() {
        return this.handles.keySet();
    }

    /**
     * The container assignment monitor.
     * This method will fetch the current owned containers for this host and ensures that the local containers' state
     * reflects this.
     */
    @Synchronized
    private void checkAssignment() {
        long traceId = LoggerHelpers.traceEnter(log, "checkAssignment");
        try {
            Exceptions.checkNotClosed(closed.get(), this);

            // Fetch the list of containers that is supposed to be owned by this host.
            Set<Integer> desiredList = getDesiredContainerList();
            if (desiredList != null) {
                Collection<Integer> runningContainers = new HashSet<>(this.handles.keySet());
                Collection<Integer> containersPendingTasks = new HashSet<>(this.pendingTasks);

                // Filter out containers which have pending tasks so we don't initiate conflicting events on the same
                // containers. Events for these containers will be tried on subsequent runs of this executor.
                Collection<Integer> containersToBeStarted = CollectionHelpers.filterOut(desiredList, runningContainers);
                containersToBeStarted = CollectionHelpers.filterOut(containersToBeStarted, containersPendingTasks);

                Collection<Integer> containersToBeStopped = CollectionHelpers.filterOut(runningContainers, desiredList);
                containersToBeStopped = CollectionHelpers.filterOut(containersToBeStopped, containersPendingTasks);

                // Only report if we have any changes or if sufficient time has elapsed since the last report.
                boolean logReport = !(containersPendingTasks.isEmpty() && containersToBeStarted.isEmpty() && containersToBeStopped.isEmpty());
                if (logReport || (CURRENT_TIME_MILLIS.get() - this.lastReportTime.get() >= REPORT_INTERVAL_MILLIS)) {
                    log.info("Container Changes: Desired = {}, Current = {}, PendingTasks = {}, ToStart = {}, ToStop = {}.",
                            desiredList, runningContainers, containersPendingTasks, containersToBeStarted,
                            containersToBeStopped);
                    this.lastReportTime.set(CURRENT_TIME_MILLIS.get());
                }

                // Initiate the start and stop tasks asynchronously.
                containersToBeStarted.forEach(this::startContainer);
                containersToBeStopped.forEach(this::stopContainer);
            } else {
                log.warn("No segment container assignments found");
            }
        } catch (Throwable e) {
            // Need to catch all exceptions here since throwing any exception here will halt this scheduled job.
            log.warn("Failed to monitor the segmentcontainer assignment: ", e);
        } finally {
            LoggerHelpers.traceLeave(log, "checkAssignment", traceId);
        }
    }

    // Stop the container given its id.
    private CompletableFuture<Void> stopContainer(int containerId) {
        log.info("Stopping Container {}.", containerId);
        ContainerHandle handle = handles.get(containerId);
        if (handle == null) {
            log.warn("Container {} handle is null, container is pending start or already unregistered.", containerId);
            return null;
        } else {
            this.pendingTasks.add(containerId);
            try {
                return registry
                        .stopContainer(handle, CLOSE_TIMEOUT_PER_CONTAINER)
                        .whenComplete((aVoid, throwable) -> {
                            if (throwable != null) {
                                log.warn("Stopping container {} failed: {}", containerId, throwable);
                            }
                            try {
                                // We remove the handle and don't attempt retry on stop container failures.
                                unregisterHandle(containerId);
                            } finally {
                                // The pending task has to be removed after the handle is removed to avoid inconsistencies
                                // with the container state.
                                // Using finally block to ensure this is always called, otherwise this will prevent other
                                // tasks from being attempted for this container id.
                                this.pendingTasks.remove(containerId);
                            }
                        });
            } catch (Throwable e) {
                // The pending task has to be removed on all failures to enable retries.
                this.pendingTasks.remove(containerId);
                throw e;
            }
        }
    }

    private CompletableFuture<ContainerHandle> startContainer(int containerId) {
        log.info("Starting Container {}.", containerId);
        this.pendingTasks.add(containerId);
        try {
            return this.parallelContainerStartsSemaphore.run(() -> this.registry.startContainer(containerId, INIT_TIMEOUT_PER_CONTAINER), 1, false)
                    .whenComplete((handle, ex) -> {
                        try {
                            if (ex == null) {
                                if (this.handles.putIfAbsent(handle.getContainerId(), handle) != null) {
                                    log.warn("Starting container {} succeeded but handle is already registered.",
                                            handle.getContainerId());
                                } else {
                                    handle.setContainerStoppedListener(this::unregisterHandle);
                                    log.info("Container {} has been registered.", handle.getContainerId());
                                }
                            } else {
                                log.warn("Starting container {} failed: {}", containerId, ex);
                            }
                        } finally {
                            // The pending task has to be removed in the end to avoid inconsistencies since containerhandle
                            // should be available immediately after the task is complete.
                            // Also need to ensure this is always called, hence doing this in a finally block.
                            this.pendingTasks.remove(containerId);
                            this.parallelContainerStartsSemaphore.release(1);
                            log.info("Current ongoing Segment Container starts {}.", this.parallelContainerStartsSemaphore.getUsedCredits());
                        }
                    });
        } catch (Throwable e) {
            // The pending task has to be removed on all failures to enable retries.
            this.pendingTasks.remove(containerId);
            throw e;
        }
    }

    private void unregisterHandle(int containerId) {
        if (this.handles.remove(containerId) == null) {
            log.warn("Attempted to unregister non-registered container {}.", containerId);
        } else {
            log.info("Container {} has been unregistered.", containerId);
        }
    }

    private Set<Integer> getDesiredContainerList() {
        log.debug("Fetching the latest container assignment from ZooKeeper.");
        if (hostContainerMapNode.getCurrentData() != null) { //Check if path exists.
            //read data from zk.
            byte[] containerToHostMapSer = hostContainerMapNode.getCurrentData().getData();
            if (containerToHostMapSer != null) {
                @SuppressWarnings("unchecked")
                val controlMapping = HostContainerMap.fromBytes(containerToHostMapSer);
                return controlMapping.getHostContainerMap().entrySet().stream()
                                     .filter(ep -> ep.getKey().equals(this.host))
                                     .map(Map.Entry::getValue)
                                     .findFirst().orElse(Collections.emptySet());
            }
        }

        return null;
    }
}


text:
/**
 *
 */
package pt.ul.fc.di.lasige.simhs.core.domain.scheduling;

import java.util.Observer;

import pt.ul.fc.di.lasige.simhs.core.domain.workload.Workload;
import pt.ul.fc.di.lasige.simhs.core.platform.IPlatform;
import pt.ul.fc.di.lasige.simhs.core.platform.IProcessor;
import pt.ul.fc.di.lasige.simhs.core.simulation.ILogger;

/**
 * Interface representing a scheduler. This interface defines the methods that
 * all scheduler must implement.
 *
 * @author jcraveiro
 */
public interface IScheduler extends Observer {

	/**
	 * Adds a logger, so that it will be notified of events broadcast
	 * by this scheduler.
	 * @param l The logger to be added
	 */
	public void addLogger(ILogger<?> l);

	/**
	 * Advances
	 */
	public void tick();

	/**
	 *
	 */
	public void tickle();

	/**
	 *
	 * @param t
	 */
	public void setTaskSet(Workload t);

	/**
	 *
	 * @param p
	 */
	public void setPlatform(IPlatform p);

	/**
	 *
	 * @param o
	 */
	public void addObserver(Observer o);

	/**
	 * Binds a processor to this scheduler's platform.
	 * @param proc The processor to bind
	 */
	public void bindProcessor(IProcessor proc);

	/**
	 * Unbinds a processor from this scheduler's platform.
	 * @param proc The processor to unbind
	 */
	public void unbindProcessor(IProcessor proc);

}


text:
require "uri"

require "log4r"
require "digest/md5"
require "digest/sha1"
require "vagrant/util/busy"
require "vagrant/util/platform"
require "vagrant/util/subprocess"

module Vagrant
  module Util
    # This class downloads files using various protocols by subprocessing
    # to cURL. cURL is a much more capable and complete download tool than
    # a hand-rolled Ruby library, so we defer to its expertise.
    class Downloader
      # Custom user agent provided to cURL so that requests to URL shorteners
      # are properly tracked.
      #
      #     Vagrant/1.7.4 (+https://www.vagrantup.com; ruby2.1.0)
      USER_AGENT = "Vagrant/#{VERSION} (+https://www.vagrantup.com; #{RUBY_ENGINE}#{RUBY_VERSION})".freeze

      # Supported file checksum
      CHECKSUM_MAP = {
        :md5 => Digest::MD5,
        :sha1 => Digest::SHA1
      }.freeze

      # Hosts that do not require notification on redirect
      SILENCED_HOSTS = [
        "vagrantcloud.com".freeze,
        "vagrantup.com".freeze
      ].freeze

      attr_reader :source
      attr_reader :destination

      def initialize(source, destination, options=nil)
        options     ||= {}

        @logger      = Log4r::Logger.new("vagrant::util::downloader")
        @source      = source.to_s
        @destination = destination.to_s

        begin
          url = URI.parse(@source)
          if url.scheme && url.scheme.start_with?("http") && url.user
            auth = "#{URI.unescape(url.user)}"
            auth += ":#{URI.unescape(url.password)}" if url.password
            url.user = nil
            url.password = nil
            options[:auth] ||= auth
            @source = url.to_s
          end
        rescue URI::InvalidURIError
          # Ignore, since its clearly not HTTP
        end

        # Get the various optional values
        @auth        = options[:auth]
        @ca_cert     = options[:ca_cert]
        @ca_path     = options[:ca_path]
        @continue    = options[:continue]
        @headers     = options[:headers]
        @insecure    = options[:insecure]
        @ui          = options[:ui]
        @client_cert = options[:client_cert]
        @location_trusted = options[:location_trusted]
        @checksums   = {
          :md5 => options[:md5],
          :sha1 => options[:sha1]
        }
      end

      # This executes the actual download, downloading the source file
      # to the destination with the given options used to initialize this
      # class.
      #
      # If this method returns without an exception, the download
      # succeeded. An exception will be raised if the download failed.
      def download!
        # This variable can contain the proc that'll be sent to
        # the subprocess execute.
        data_proc = nil

        extra_subprocess_opts = {}
        if @ui
          # If we're outputting progress, then setup the subprocess to
          # tell us output so we can parse it out.
          extra_subprocess_opts[:notify] = :stderr

          progress_data = ""
          progress_regexp = /^\r\s*(\d.+?)\r/m

          # Setup the proc that'll receive the real-time data from
          # the downloader.
          data_proc = Proc.new do |type, data|
            # Type will always be "stderr" because that is the only
            # type of data we're subscribed for notifications.

            # Accumulate progress_data
            progress_data << data

            while true
              # If the download has been redirected and we are no longer downloading
              # from the original host, notify the user that the target host has
              # changed from the source.
              if progress_data.include?("Location")
                location = progress_data.scan(/Location: (.+?)$/m).flatten.compact.first.to_s.strip
                if !location.empty?
                  @logger.info("download redirected to #{location}")
                  location_uri = URI.parse(location)
                  source_uri = URI.parse(source)
                  source_host = source_uri.host.split(".", 2).last
                  location_host = location_uri.host.split(".", 2).last
                  if !@redirect_notify && location_host != source_host && !SILENCED_HOSTS.include?(location_host)
                    @ui.clear_line
                    @ui.detail "Download redirected to host: #{location_uri.host}"
                  end
                  @redirect_notify = true
                end
                progress_data.replace("")
                break
              end

              # If we have a full amount of column data (two "\r") then
              # we report new progress reports. Otherwise, just keep
              # accumulating.
              match = nil
              check_match = true

              while check_match
                check_match = progress_regexp.match(progress_data)
                if check_match
                  data = check_match[1].to_s
                  stop = progress_data.index(data) + data.length
                  progress_data.slice!(0, stop)

                  match = check_match
                end
              end

              break if !match

              # Ignore the first \r and split by whitespace to grab the columns
              columns = data.strip.split(/\s+/)

              # COLUMN DATA:
              #
              # 0 - % total
              # 1 - Total size
              # 2 - % received
              # 3 - Received size
              # 4 - % transferred
              # 5 - Transferred size
              # 6 - Average download speed
              # 7 - Average upload speed
              # 9 - Total time
              # 9 - Time spent
              # 10 - Time left
              # 11 - Current speed

              output = "Progress: #{columns[0]}% (Rate: #{columns[11]}/s, Estimated time remaining: #{columns[10]})"
              @ui.clear_line
              @ui.detail(output, new_line: false)
            end
          end
        end

        @logger.info("Downloader starting download: ")
        @logger.info("  -- Source: #{@source}")
        @logger.info("  -- Destination: #{@destination}")

        retried = false
        begin
          # Get the command line args and the subprocess opts based
          # on our downloader settings.
          options, subprocess_options = self.options
          options += ["--output", @destination]
          options << @source

          # Merge in any extra options we set
          subprocess_options.merge!(extra_subprocess_opts)

          # Go!
          execute_curl(options, subprocess_options, &data_proc)
        rescue Errors::DownloaderError => e
          # If we already retried, raise it.
          raise if retried

          @logger.error("Exit code: #{e.extra_data[:code]}")

          # If its any error other than 33, it is an error.
          raise if e.extra_data[:code].to_i != 33

          # Exit code 33 means that the server doesn't support ranges.
          # In this case, try again without resume.
          @logger.error("Error is server doesn't support byte ranges. Retrying from scratch.")
          @continue = false
          retried = true
          retry
        ensure
          # If we're outputting to the UI, clear the output to
          # avoid lingering progress meters.
          if @ui
            @ui.clear_line

            # Windows doesn't clear properly for some reason, so we just
            # output one more newline.
            @ui.detail("") if Platform.windows?
          end
        end

        validate_download!(@source, @destination, @checksums)

        # Everything succeeded
        true
      end

      # Does a HEAD request of the URL and returns the output.
      def head
        options, subprocess_options = self.options
        options.unshift("-I")
        options << @source

        @logger.info("HEAD: #{@source}")
        result = execute_curl(options, subprocess_options)
        result.stdout
      end

      protected

      # Apply any checksum validations based on provided
      # options content
      #
      # @param source [String] Source of file
      # @param path [String, Pathname] local file path
      # @param checksums [Hash] User provided options
      # @option checksums [String] :md5 Compare MD5 checksum
      # @option checksums [String] :sha1 Compare SHA1 checksum
      # @return [Boolean]
      def validate_download!(source, path, checksums)
        CHECKSUM_MAP.each do |type, klass|
          if checksums[type]
            result = checksum_file(klass, path)
            @logger.debug("Validating checksum (#{type}) for #{source}. " \
              "expected: #{checksums[type]} actual: #{result}")
            if checksums[type] != result
              raise Errors::DownloaderChecksumError.new(
                source: source,
                path: path,
                type: type,
                expected_checksum: checksums[type],
                actual_checksum: result
              )
            end
          end
        end
        true
      end

      # Generate checksum on given file
      #
      # @param digest_class [Class] Digest class to use for generating checksum
      # @param path [String, Pathname] Path to file
      # @return [String] hexdigest result
      def checksum_file(digest_class, path)
        digester = digest_class.new
        digester.file(path)
        digester.hexdigest
      end

      def execute_curl(options, subprocess_options, &data_proc)
        options = options.dup
        options << subprocess_options

        # Create the callback that is called if we are interrupted
        interrupted  = false
        int_callback = Proc.new do
          @logger.info("Downloader interrupted!")
          interrupted = true
        end

        # Execute!
        result = Busy.busy(int_callback) do
          Subprocess.execute("curl", *options, &data_proc)
        end

        # If the download was interrupted, then raise a specific error
        raise Errors::DownloaderInterrupted if interrupted

        # If it didn't exit successfully, we need to parse the data and
        # show an error message.
        if result.exit_code != 0
          @logger.warn("Downloader exit code: #{result.exit_code}")
          check = result.stderr.match(/\n*curl:\s+\((?<code>\d+)\)\s*(?<error>.*)$/)
          if check && check[:code] == "416"
            # All good actually. 416 means there is no more bytes to download
            @logger.warn("Downloader got a 416, but is likely fine. Continuing on...")
          else
            if !check
              err_msg = result.stderr
            else
              err_msg = check[:error]
            end

            raise Errors::DownloaderError,
              code: result.exit_code,
              message: err_msg
          end
        end

        result
      end

      # Returns the various cURL and subprocess options.
      #
      # @return [Array<Array, Hash>]
      def options
        # Build the list of parameters to execute with cURL
        options = [
          "-q",
          "--fail",
          "--location",
          "--max-redirs", "10", "--verbose",
          "--user-agent", USER_AGENT,
        ]

        options += ["--cacert", @ca_cert] if @ca_cert
        options += ["--capath", @ca_path] if @ca_path
        options += ["--continue-at", "-"] if @continue
        options << "--insecure" if @insecure
        options << "--cert" << @client_cert if @client_cert
        options << "-u" << @auth if @auth
        options << "--location-trusted" if @location_trusted

        if @headers
          Array(@headers).each do |header|
            options << "-H" << header
          end
        end

        # Specify some options for the subprocess
        subprocess_options = {}

        # If we're in Vagrant, then we use the packaged CA bundle
        if Vagrant.in_installer?
          subprocess_options[:env] ||= {}
          subprocess_options[:env]["CURL_CA_BUNDLE"] = ENV["CURL_CA_BUNDLE"]
        end

        return [options, subprocess_options]
      end
    end
  end
end


text:
package org.wso2.carbon.identity.sso.saml.dto;

import java.io.Serializable;

public class SingleLogoutRequestDTO implements Serializable {

    private static final long serialVersionUID = -5086237688925774301L;

    private String assertionConsumerURL;
    private String logoutResponse;
    private String rpSessionId;
    private String certificateAlias;
    private String tenantDomain;

    public String getAssertionConsumerURL() {
        return assertionConsumerURL;
    }

    public void setAssertionConsumerURL(String assertionConsumerURL) {
        this.assertionConsumerURL = assertionConsumerURL;
    }

    public String getLogoutResponse() {
        return logoutResponse;
    }

    public void setLogoutResponse(String logoutResponse) {
        this.logoutResponse = logoutResponse;
    }

    public String getRpSessionId() {
        return rpSessionId;
    }

    public void setRpSessionId(String rpSessionId) {
        this.rpSessionId = rpSessionId;
    }

    public String getCertificateAlias() {
        return certificateAlias;
    }

    public void setCertificateAlias(String certificateAlias) {
        this.certificateAlias = certificateAlias;
    }

    public String getTenantDomain() {
        return tenantDomain;
    }

    public void setTenantDomain(String tenantDomain) {
        this.tenantDomain = tenantDomain;
    }
}


text:
Box::Box(Lag::Scene &scene, Lag::SceneNode &parentNode, const std::string &name,
             const glm::vec3 &position, const glm::vec3 &scale,
             const Lag::Color &color1, const Lag::Color &color2,
             float trisPerLength, const glm::vec2 &maxPointSizeLimits, const glm::vec2 displacementStrengthLimits) :
    Entity("cube", "pointMaterial"),
    trisPerLength (trisPerLength),
    maxPointSizeLimits(maxPointSizeLimits),
    displacementStrengthLimits(displacementStrengthLimits),
    maxPointSize(maxPointSizeLimits.x),
    displacementStrength(displacementStrengthLimits.x) {

    setAsCollider("wall");

    originalColor1 = color1;
    originalColor2 = color2;
    this->color1 = originalColor1;
    this->color2 = originalColor2;

    Lag::SceneNode &planeNode = parentNode.createChildSceneNode(name);
    planeNode.setPosition(position);
    planeNode.setScale(scale);

    scene.addEntity(this);
    attachToSceneNode(planeNode);
}

void Box::onCollision(Entity &other, const Lag::IntersectionResult &result) {
    if(other.getColliderName() == "ball") {
        timeToAnimate = TIME_TO_ANIMATE;
        Ball &ball = static_cast<Ball&>(other);
        colorPassedByBall = ball.getColor();
    }
}

void Box::onFrameStart(float timePassed) {
    if(timeToAnimate > 0.0f) {
        timeToAnimate = glm::max(0.0f, timeToAnimate - timePassed);
        float ratio = timeToAnimate / TIME_TO_ANIMATE;

        displacementStrength = glm::mix(displacementStrengthLimits.x, displacementStrengthLimits.y, ratio);
        maxPointSize = glm::mix(maxPointSizeLimits.x, maxPointSizeLimits.y, ratio);

        color1 = glm::mix(originalColor1.toVec3(), colorPassedByBall.toVec3(), ratio);
        color2 = glm::mix(originalColor2.toVec3(), colorPassedByBall.toVec3(), ratio);

        maxPointSize = glm::mix(maxPointSizeLimits.x, maxPointSizeLimits.y, ratio);
    }

    Entity::onFrameStart(timePassed);
}

void Box::onSubEntityPreRender(Lag::SubEntity &subEntity, Lag::Renderer &renderer, const Lag::RenderOperation &renderOperation) {
    Entity::onSubEntityPreRender(subEntity, renderer, renderOperation);

    Lag::uint32 color1 = this->color1.toIntABGR();
    Lag::uint32 color2 = this->color2.toIntABGR();

    material->getGpuProgram().getUniformByName("color1")->setValue(reinterpret_cast<const void*>(&color1));
    material->getGpuProgram().getUniformByName("color2")->setValue(reinterpret_cast<const void*>(&color2));

    material->getGpuProgram().getUniformByName("trisPerLength")->setValue(reinterpret_cast<const void*>(&trisPerLength));
    material->getGpuProgram().getUniformByName("maxPointSize")->setValue(reinterpret_cast<const void*>(&maxPointSize));
    material->getGpuProgram().getUniformByName("displacementStrength")->setValue(reinterpret_cast<const void*>(&displacementStrength));
}