text:
%KINECTSIMULATOR_IR  Simulate Kinect IR images.
%   KINECTSIMULATOR_IR is a program developed to simulate high fidelity
%   Kinect IR images by closely following the Microsoft Kinect's mechanics.
%   For a detailed description of how this simulator was developed, please
%   refer to [1]. If this simulator is used for publication, please cite
%   [1] in your references.
%
%   IRimg = KinectSimulator_IR(vertex,face) returns the simulated padded IR
%   image 'IRimg' used for depth image estimation, given a correlation
%   window size. The parameters 'vertex' and 'face' define the CAD model of
%   the 3D scene used to generate an image.
%
%       vertex  - 3xn, n vertices of each 3D coordinate that defines the
%                 CAD model.
%       face    - 3xm, m facets, each represented by 3 vertices that
%                 defines the CAD model.
%       normalf - 3xm, m facets, representing the normal direction of each
%                 facet.
%
%   This program utilizes a Matlab wrapper written by Vipin Vijayan [2] of
%   the ray casting program OPCODE. The Original OPCODE program was written
%   by Pierre Terdiman [3].
%
%   [IRimg,IRimg_disp] = KinectSimulator_IR(vertex,face) returns the
%   simulated IR image IRimg_disp that is the same size and resolution of
%   the real outputted Kinect IR image (480 rows x 640 columns).
%
%   [IRimg,IRimg_disp,IRimg_full] = KinectSimulator_IR(vertex,face) returns
%   the simulated image of the fully projected IR dot pattern IRimg_full
%   that falls outside the bounds of the padded IR image.
%
%   IRimg = KinectSimulator_IR(vertex,face,IR_intensity,IR_noise) allows
%   the user to specify a different IR intensity and noise model.
%
%       IR_intensity Options
%           'default' - IR intensity model determined empirically from data
%                       collected from IR images recorded by the Kinect
%                       positioned in front of a flat wall at various
%                       depths. The model follows an alpha*dot(-n,l)/r^2
%                       intensity model, where r is the range between the
%                       sensor and the surface point, n is the surface
%                       normal, and l is the IR lighting direction. Alpha
%                       accounts for a constant illumination, surface
%                       properties, etc. The actual intensity model is
%
%                           I = Iu.*5.90x10^8*dot(-n,l)/r^2
%
%                       Iu is the fractional intensity contributed by a
%                       sub-ray of a transmitted dot. r is the distance
%                       between the center of the transmitter coordinate
%                       system, and the 3D location of where the sub-ray
%                       intersected the CAD model (range).
%
%           'simple'  - Additional IR intensity model determined
%                       empirically from data collected from Kinect IR
%                       images.
%
%                           I = Iu.*5.96x10^8/r^2
%
%                       This model is a simplified version of the 'default'
%                       model, which excluded the surface normal and IR
%                       lighting direction to fit to the data.
%
%           'none'    - No model is used to compute an IR intensity. This
%                       is modeled by
%
%                           I = Iu
%
%                       This option is used when generating reference
%                       images for depth estimation.
%
%           @(Iu,r)fn - User defined IR intensity model given the
%                       fractional intensity and the range of the
%                       transmitted sub-ray.
%
%       IR_noise Options
%           'default' - IR noise model determined empirically from data
%                       collected from IR images recorded by the Kinect
%                       positioned in front of a flat wall at various
%                       depths. The model has multiplicative speckle noise
%                       that fits a gamma distribution with shape value
%                       4.54 and scale value 0.196. The model also has
%                       additive detector noise that fits a normal
%                       distribution with mean -0.126 and standard
%                       deviation 10.4, with units of 10-bit intensity. The
%                       actual noise model is
%
%                           Z = I + n_I + n
%                             = I*Gamma + n
%                             = I*gamrnd(4.54,0.196) - 0.126+10.4*randn()
%
%           'none'    - No model is used to compute an IR noise. This is
%                       modeled by
%
%                           Z = I = Iu
%
%                       This option is used when generating reference
%                       images for depth estimation. Note, this option must
%                       be set if the IR_intensity model is set to 'none'.
%
%           @(I)fn    - User defined IR noise model given the intensity of
%                       the sub-ray representing a part of the transmitted
%                       IR dot.
%
%   IRimg = KinectSimulator_IR(vertex,face,IR_intensity,IR_noise,options)
%   gives the user the option to change default Kinect input parameters and
%   the default IR simulator parameters. The options are listed as follows:
%
%       IR Simulator Parameters
%           'window'  - Size of correlation window used to process IR image
%                       images for depth estimation. The default is set to
%                       9x9 rows and columns, i.e. [9 9] pixels. Note,
%                       these values must be greater than zero, and must be
%                       odd to allow the pixel being processed to be at the
%                       center of the window. Also, given the limited size
%                       of the idealized dot pattern used to simulate IR
%                       images, the number of rows in the window cannot
%                       exceed 15 pixels.
%
%           'subray'  - Size of sub-ray grid used to simulate the physical
%                       cross-sectional area of a transmitted IR dot. The
%                       default is set to 7x17 rows and cols, i.e. [7 17].
%                       Note, it is preferable to set each value to an odd
%                       number as to allow the center of the pixel to be
%                       represented by a sub-ray. Also, since Kinect
%                       performs an interpolation to achieve a sub-pixel
%                       disparity accuracy of 1/8th of a pixel, there
%                       should be at least 8 columns of sub-rays.
%
%           'pattern' - The dot pattern used to simulate the IR image. The
%                       default is adapted from the work done by Andreas
%                       Reichinger, in his blog post entitled 'Kinect
%                       Pattern Uncovered' [4]. Note, this idealized binary
%                       representation of Kinect's dot pattern does not
%                       include the pincushion distortion observed in real
%                       Kinect IR images.
%
%           'quant10' - The option to quantize IR intensity into a 10-bit
%                       value. The default is set to 'on', but can be
%                       turned to 'off'. Note, keeping the IR image
%                       quantization option set to 'on' will result in
%                       introducing more noise to the output IR values on
%                       the order of  10*log10(2^10) = 30.1 dB, which
%                       impacts depth estimation in the depth image
%                       simulator. Depending on the inputted IR intensity
%                       and noise models, this may introduce erroneous
%                       depth error, so the user can opt to set this option
%                       to 'off' to avoid this, or at the very least remove
%                       the option to saturate values below 0 and above
%                       2^10 on lines 543, 545, 617, and 619.
%
%           'display' - The option to display the output IR images. The
%                       default is set to 'on', but can be turned to 'off'.
%                       Note, the dotted line on the padded image IRimg
%                       represents the original IR image resolution from
%                       IRimg_disp. If the full IR image is displayed, the
%                       dotted line represents the padded image IRimg, and
%                       the blue stars represent where the dot pattern had
%                       to be extended. Also, the yellow stars represent
%                       the bright center dot locations that represent the
%                       center of each repeated pattern in the 3x3 final
%                       grid.
%
%       Kinect Parameters
%           'imgfov'  - The field of view of Kinect's transmitter/receiver.
%                       The default is set to 45.6 x 58.5 degrees for the
%                       verticle and horizontal FOVs, respectively, i.e.
%                       [45.6 58.5].
%
%           'imgrng'  - The minimum and maximum operational depths of the
%                       Kinect sensor. Dots with depths that fall outside
%                       of this range are filtered out from the IRimg and
%                       IRimg_disp images. This is important for the depth
%                       image simulator because reference images generated
%                       at the min and max depths with only be able to find
%                       matches in the simulated measured IR image between
%                       the set operational depth range. The default is set
%                       to 800 mm for the minimum depth, and 4000 mm for
%                       the maximum depth, i.e. [800 4000].
%
% References:
%   [1] M. J. Landau, B. Y. Choo, P. A. Beling, "Simulating Kinect Infrared
%       and Depth Images," 2015 (under submission).
%
%   [2] V. Vijayan, "Ray casting for deformable triangular 3d meshes -
%       file exchange - MATLAB central," Apr. 2013.
%       http://www.mathworks.com/matlabcentral/fileexchange/41504-ray-casting-for-deformable-triangular-3d-meshes/content/opcodemesh/matlab/opcodemesh.m
%
%	[3] P. Terdiman, "OPCODE," Aug. 2002.
%       http://www.codercorner.com/Opcode.htm
%
%	[4] A. Reichinger, "Kinect pattern uncovered | azt.tm's blog," Mar. 2011.
%       https://azttm.wordpress.com/2011/04/03/kinect-pattern-uncovered/

function varargout = KinectSimulator_IR(vertex,face,normalf,varargin)

% DEFAULT PARAMETERS ======================================================
% Depth simulator parameters ----------------------------------------------
% Option to plot IR image from depth image simulator
isPlotIR = 0;

% IR simulator parameters -------------------------------------------------
% IR intensity and noise models
model_Intensity = @(i,r,n,l) i.*5.90e+08.*dot(-n,l)'./r.^2;
model_Noise     = @(i) i.*gamrnd(4.54,0.196,size(i))-0.126+10.4.*randn(size(i));
% Size of correlation window used for depth estimation
corrWind = [9 9];
% Size of sub-ray grid to simulate phyiscal dot cross-sectional area
nsub = [7 17];
% Option to plot IR images
isPlot = 1;
% Option to load idealized binary replication of the Kinect dot pattern
isLoad = 1;
% Option to quantize the IR image to 10-bit value
isQuant10 = 1;
% Option to be able to quantize if not fractional intensities
isQuantOK = 1;

% Kinect parameters -------------------------------------------------------
% Resolution of real outputted Kinect IR image (rows x cols)
ImgRes = [480 640];   % pix
% Field of view of transmitter/receiver (vertFOV x horzFOV)
ImgFOV = [45.6 58.5]; % deg
% Minimum and maximum operational depths of the Kinect sensor (min x max)
ImgRng = [800 4000];  % mm
% Distance between IR transmitter and receiver
baseRT = 75; % mm

% ERROR MESSAGES ==========================================================
narginchk(3, inf)
nargoutchk(0, 3)
if size(vertex,1) ~= 3 || size(vertex,2) < 4 || length(size(vertex)) > 2
    error('Input ''vertex'' must have the form 3xn, and must have at least 3 values.')
end
if size(face,1) ~= 3 || length(size(face)) > 2
    error('Input ''face'' must have the form 3xm, and must have at least 3 values.')
end
if size(normalf,1) ~= 3 || length(size(normalf)) ~= length(size(face))
    error('Input ''normalf'' must have the form 3xm, and must equal the number of face values.')
end
if min(vertex(3,:)) < 0
    error('CAD model must have only positive depth (i.e. must be in front of the camera).')
end

% SET INPUT PARAMETERS ====================================================
if nargin == 4
    error('The IR intensity and noise models need to be specified.')
end
if nargin > 4
    if strcmp(varargin{1},'none') && ~strcmp(varargin{2},'none')
        error('Noise model must be set to ''none'' if intensity model is set to ''none''.');
    else
        % IR intensity model
        if strcmp(varargin{1},'default')
            model_Intensity = @(i,r,n,l) i.*5.90e+08.*dot(-n,l)'./r.^2;
        elseif strcmp(varargin{1},'simple')
            model_Intensity = @(i,r,n,l) i.*5.96e+08./r.^2;
        elseif strcmp(varargin{1},'none')
            model_Intensity = @(i,r,n,l) i.*ones(size(r));
            isQuantOK = 0;
        elseif ischar(varargin{1})
            error('The argument ''%s'' is not a valid IR intensity model option.', varargin{1})
        elseif nargin(varargin{1}) ~= 4
            error('IR intensity model must have the form ''@(Iu,r,n,l) fnc''.')
        else % User inputted model
            model_Intensity = varargin{1};
        end
        % IR noise model
        if strcmp(varargin{2},'default')
            model_Noise = @(i) i.*gamrnd(4.54,0.196,size(i))-0.126+10.4.*randn(size(i));
        elseif strcmp(varargin{2},'none')
            model_Noise = @(i) i;
        elseif ischar(varargin{2})
            error('The argument ''%s'' is not a valid IR noise model option.', varargin{2})
        elseif nargin(varargin{2}) ~= 1
            error('IR noise model must have the form ''@(I) fnc''.')
        else % User inputted model
            model_Noise = varargin{2};
        end
    end
end
if nargin > 5
    % Concatenate cell (meant for use with Kinect depth simulator)
    if iscell(varargin{3})
        varargin = [varargin(1:2) varargin{3}];
    end
    k = 3;
    while k < length(varargin)+1
        switch varargin{k}
            % Depth Simulator Parameters
            case 'refine'
                k = k+2;
            case 'quant11'
                k = k+2;
            case 'displayIR'
                if strcmp(varargin{k+1},'off')
                    isPlotIR = 0;
                    isPlot = 0;
                elseif strcmp(varargin{k+1},'on')
                    isPlotIR = 1;
                    isPlot = 1;
                end
                k = k+2;
            % IR Simulator Parameters
            case 'window'
                corrWind = varargin{k+1};
                if length(corrWind) ~= 2 || sum(mod(corrWind,2)) ~= 2 || sum(corrWind>0) ~= 2 || ~isnumeric(corrWind)
                    error('Correlation window must have two odd integer values greater than zero.')
                elseif corrWind(1) > 15
                    error('Number of rows in correlation window cannot exceed 15 pixels.')
                end
                k = k+2;
            case 'subray'
                nsub = varargin{k+1};
                if length(nsub) ~= 2 || sum(rem(nsub,1)==0) ~=2 || sum(nsub>0) ~= 2 || ~isnumeric(nsub)
                    error('Sub-ray grid must have two integer values greater than zero.')
                end
                k = k+2;
            case 'pattern'
                dotPattern = varargin{k+1};
                isLoad = 0;
                if sum([size(find(dotPattern==0),2) size(find(dotPattern==1),2)]) ~= numel(dotPattern)
                    error('Dot pattern image must be binary.')
                end
                k = k+2;
            case 'quant10'
                if strcmp(varargin{k+1},'off')
                    isQuant10 = 0;
                elseif strcmp(varargin{k+1},'on')
                    isQuant10 = 1;
                else
                    error('Quantize IR image option must be set to ''off'' or ''on''.')
                end
                k = k+2;
            case 'display'
                if strcmp(varargin{k+1},'off')
                    isPlot = 0;
                elseif strcmp(varargin{k+1},'on')
                    isPlot = 1;
                else
                    error('Display option must be set to ''off'' or ''on''.')
                end
                k = k+2;
            % Kinect Parameters
            case 'imgfov'
                ImgFOV = varargin{k+1};
                if length(ImgFOV) ~= 2 || sum(ImgFOV>0) ~= 2 || ~isnumeric(ImgFOV)
                    error('Image field of view must have two values greater than zero.')
                end
                k = k+2;
            case 'imgrng'
                ImgRng = varargin{k+1};
                if length(ImgRng) ~= 2 || sum(ImgRng>0) ~= 2 || ~isnumeric(ImgRng)
                    error('Operational range of depths must have two values greater than zero.')
                elseif ImgRng(1) > ImgRng(2)
                    error('Min depth must be less than max depth.')
                end
                k = k+2;
            otherwise
                if isnumeric(varargin{k})
                    error('The argument ''%d'' is not a valid input parameter.', varargin{k})
                elseif ischar(varargin{k})
                    error('The argument ''%s'' is not a valid input parameter.', varargin{k})
                else
                    error('Not a valid input parameter')
                end
        end
    end
end

% =========================================================================
% PROCESS IR IMAGE ========================================================
% =========================================================================

% PREPROCESS PARAMETERS ===================================================
% Determine horizontal and vertical focal lengths
ImgFOV = ImgFOV*(pi/180); % rad
FocalLength = [ImgRes(2)/(2*tan(ImgFOV(2)/2)); ImgRes(1)/(2*tan(ImgFOV(1)/2))]; % pix

% Number of rows and columns to pad IR image for cross correlation
corrRow = (corrWind(1)-1)/2;
corrCol = (corrWind(2)-1)/2;

% Load idealized binary replication of the Kinect dot pattern -------------
if isLoad == 1
    % Check if depth range provides enough coverage for reference images
    if (baseRT*FocalLength(1)/ImgRng(1))-(baseRT*FocalLength(1)/ImgRng(2)) > 211
        error('Depth range too large for default dot pattern (hint: try a minimum depth of 204 mm).')
    else
        load('default_load_files\kinect-pattern_3x3.mat')
    end
else
    if (baseRT*FocalLength(1)/ImgRng(1))-(baseRT*FocalLength(1)/ImgRng(2)) > size(dotPattern,2)
        error('Depth range too large for size of dot pattern.')
    end
end

% Find dot pattern size
ImgSizeDot = size(dotPattern);

% Find where to crop rows of dot pattern for output IR images
cropRow = max([0, ceil((ImgSizeDot(1)-ImgRes(1))/2)]);

% Increase resolution of dot pattern with sub-rays ------------------------
% Minimum and maximum depth values of 3D scene
minDepth = min(vertex(3,:)); % mm
maxDepth = max(vertex(3,:)); % mm

% Add columns of dot pattern to left and right side based on disparity equation
minDisparity = round((baseRT*FocalLength(1))/min([ImgRng(1) minDepth]));
maxDisparity = round((baseRT*FocalLength(1))/max([ImgRng(2) maxDepth]));

% Number of cols cannot exceed one block size (for simplicity of coding)
if isLoad == 1
    pixShftLeft_T = min([211,max([0, minDisparity+corrCol])]);
    pixShftRght_T = min([211,max([0, ImgRes(2)-ImgSizeDot(2)-maxDisparity+corrCol+1])]);
else
    pixShftLeft_T = min([size(dotPattern,2),max([0, minDisparity+corrCol])]);
    pixShftRght_T = min([size(dotPattern,2),max([0, ImgRes(2)-ImgSizeDot(2)-maxDisparity+corrCol+1])]);
end

dotAddLeft = dotPattern(:,end-pixShftLeft_T+1:end);
dotAddRght = dotPattern(:,1:pixShftRght_T);
dotAdd     = [dotAddLeft dotPattern dotAddRght];
ImgSizeAdd = size(dotAdd);

% Increase resolution of dot pattern to nsub_Nsubpx image size
dotInc  = reshape(repmat(dotAdd,nsub(2),1),ImgSizeAdd(1),[]);
dotInc  = reshape(repmat(dotInc',nsub(1),1),ImgSizeAdd(2)*nsub(2),[])';
dotIndx = find(dotInc==1);
ImgSizeInc = size(dotInc);

% SET UP TRANSMITTER RAYS FOR RAY CASTING =================================
% Setup collision structure
t = opcodemesh(vertex,face);

% Create angles of rays for each sub-pixel from transmitter
vertPixLeft_T = ImgSizeDot(1)/2-1/(nsub(1)*2);
horzPixLeft_T = ImgSizeDot(2)/2-1/(nsub(2)*2)+pixShftLeft_T;

% Convert index to subscript values (based on ind2sub)
jpix_y = rem(dotIndx-1, ImgSizeInc(1)) + 1;
jpix_x = (dotIndx - jpix_y)/ImgSizeInc(1) + 1;

% Adjust subscript value to sensor coordinate system values
spix_x = horzPixLeft_T-(jpix_x-1)/nsub(2);
spix_y = vertPixLeft_T-(jpix_y-1)/nsub(1);

% Determine 3D location of where each ray intersects max range
X_T = spix_x * maxDepth / FocalLength(1);
Y_T = spix_y * maxDepth / FocalLength(2);
Z_T = maxDepth*ones(size(dotIndx));

% Set up origin and directions for each ray
orig_T = [zeros(size(X_T))-baseRT zeros(size(Y_T)) zeros(size(Z_T))]';
dir_T  = [           X_T-baseRT              Y_T              Z_T]';

% Find intersecting points from line of sight vectors
[~,d_T,~,~] = t.intersect(orig_T,dir_T-orig_T);
indxNotNan  = ~isnan(d_T);

% OCCLUSION DETECTION =====================================================
% Set up receiver rays based on where transmitted rays intersected CAD
X_R = d_T(indxNotNan).*X_T(indxNotNan)-baseRT;
Y_R = d_T(indxNotNan).*Y_T(indxNotNan);
Z_R = d_T(indxNotNan).*Z_T(indxNotNan);

% Find intersecting points from line of sight vectors
orig_R = [zeros(size(X_R)) zeros(size(Y_R)) zeros(size(Z_R))]';
dir_R  = [           X_R              Y_R              Z_R]';

% Find intersecting points from line of sight vectors
[~,d_R,t_R,~] = t.intersect(orig_R,dir_R-orig_R);

% Build array of rays that are not occluded
indxKeep = find(d_R>.999);

% Find range of all dots wrt transmitter
rng_T = sqrt((X_R+baseRT).^2 + Y_R.^2 + Z_R.^2);
rng_T = rng_T(indxKeep);

% Find surface normal for all intersecting dots
sn_T = normalf(:,t_R(indxKeep));

% Find the IR light direction for all sub-rays
ld_T = bsxfun(@rdivide,[X_R(indxKeep)+baseRT Y_R(indxKeep) Z_R(indxKeep)]',rng_T');

% PROJECT IR DOTS INTO PIXEL COORDINATE SYSTEM ============================
% For transmitted rays that have unoccluded IR dots, find 3D sensor coordinates
center = zeros(2,size(indxKeep,1));
center(1,:) = ImgSizeDot(2)/2 +.5 - FocalLength(1).* X_R(indxKeep)'./Z_R(indxKeep)';
center(2,:) = ImgSizeDot(1)/2 +.5 - FocalLength(2).* Y_R(indxKeep)'./Z_R(indxKeep)';

% GENERATE OUTPUT IR IMAGE ================================================
subIntensity = 1/(nsub(1)*nsub(2));

% Round row and col values to pixel it will be added in to
center = round(center);

% Padded IR image with correlation window (main image used) ---------------
% Filter out values that fall outside operational depths
indxFilt = find(ceil(Z_R(indxKeep))>=ImgRng(1));
indxFilt = indxFilt(floor(Z_R(indxFilt))<=ImgRng(2));

% Filter out values that fall outside image frame
minFiltRow = 1-corrRow+cropRow;
maxFiltRow = ImgRes(1)-1+corrWind(1)-corrRow+cropRow;
minFiltCol = 1-corrCol;
maxFiltCol = ImgRes(2)-1+corrWind(2)-corrCol;

indxFilt = indxFilt(center(1,indxFilt)>=minFiltCol);
indxFilt = indxFilt(center(1,indxFilt)<=maxFiltCol);
indxFilt = indxFilt(center(2,indxFilt)>=minFiltRow);
indxFilt = indxFilt(center(2,indxFilt)<=maxFiltRow);

% Preprocess intensity values for each sub-ray
intensity_T = model_Intensity(subIntensity,rng_T(indxFilt),sn_T(:,indxFilt),ld_T(:,indxFilt));

% Add in sub-ray intensities to pixels
IRimg = zeros(ImgRes+corrWind-1);
for ipt = 1:size(indxFilt,1)
    x_shift = center(2,indxFilt(ipt)) + corrRow-cropRow;
    y_shift = center(1,indxFilt(ipt)) + corrCol;

    % Add partial intensity to pixel
    IRimg(x_shift, y_shift) = IRimg(x_shift, y_shift) + intensity_T(ipt);
end

% Saturate fractional intensity value if dots overlap
% IRimg(IRimg_full > 1) = 1;

% Determine index values for pixels with IR dots
indxDot = find(IRimg>0);

% Introduce IR noise model
IRimg(indxDot) = model_Noise(IRimg(indxDot));

% Quantize image to 10 bit if intensity models are included ---------------
if isQuant10 == 1 && isQuantOK == 1
    % Round intensity to closest integer value
    IRimg = round(IRimg);
    % Saturate high intensity values above max allowable integer
    IRimg(IRimg > 2^10) = 2^10;
    % Saturate low intensity values below min allowable integer
    IRimg(IRimg < 0) = 0;
end

% Store image into function output variable
varargout{1} = IRimg;

% Cropped IR image for displaying -----------------------------------------
if nargout > 1 || isPlotIR == 1
    cropX1_disp = 1 + corrCol;
    cropX2_disp = ImgRes(2) + corrCol;
    cropY1_disp = 1 + corrRow;
    cropY2_disp = ImgRes(1) + corrRow;

    IRimg_disp = IRimg(cropY1_disp:cropY2_disp,cropX1_disp:cropX2_disp);

    % Store image into function output variable
    varargout{2} = IRimg_disp;
end

% Full IR image -----------------------------------------------------------
if nargout > 2
    % Find values that weren't used in main image
    center = center(:,indxKeep);
    center(:,indxFilt) = [];

    % Filter range vector
    rng_T(indxFilt) = [];

    % Filter surface normal vector
    sn_T(:,indxFilt) = [];

    % Filter IR light direction vector
    ld_T(:,indxFilt) = [];

    % Determine min and max column values for full dot pattern projection
    minImg_full = min([min(center(1,:)), 1-corrCol]);
    maxImg_full = max([max(center(1,:))+1-minImg_full, ImgRes(2)+corrCol+1-minImg_full]);

    numPixShift = 1 - minImg_full;

    % Fill full image with values from main image
    IRimg_full = zeros([ImgSizeDot(1), maxImg_full]);
    IRimg_full(minFiltRow:maxFiltRow,(minFiltCol:maxFiltCol)+numPixShift) = IRimg;

    % Preprocess intensity values for each sub-ray
    intensity_T = model_Intensity(subIntensity,rng_T,sn_T,ld_T);

    % Add in sub-ray intensities to pixels
    for ipt = 1:size(center,2)
        x_shift = center(2,ipt);
        y_shift = center(1,ipt) + numPixShift;

        % Add partial intensity to pixel
        IRimg_full(x_shift, y_shift) = IRimg_full(x_shift, y_shift) + intensity_T(ipt);
    end

    % Saturate fractional intensity value if dots overlap
%     IRimg_full(IRimg_full > 1) = 1;

    % Determine index values for pixels with IR dots from filtered sub-rays
    IRimg_temp = IRimg_full;
    IRimg_temp(minFiltRow:maxFiltRow,(minFiltCol:maxFiltCol)+numPixShift) = 0;
    indxDot = find(IRimg_temp>0);

    % Introduce IR noise model
    IRimg_full(indxDot) = model_Noise(IRimg_full(indxDot));

    % Quantize image to 10 bit if intensity models are included ---------------
    if isQuant10 == 1 && isQuantOK == 1
        % Round intensity to closest integer value
        IRimg_full = round(IRimg_full);
        % Saturate high intensity values above max allowable integer
        IRimg_full(IRimg_full > 2^10) = 2^10;
        % Saturate low intensity values below min allowable integer
        IRimg_full(IRimg_full < 0) = 0;
    end

    % Store image into function output variable
    varargout{3} = IRimg_full;
end

% DISPLAY OUTPUT IR IMAGES ================================================
if isPlot == 1
    % Determine max allowable intensity
    if isQuantOK == 1
        imgMax = 2^10;
%         imgMax = model_Intensity(1,minDepth);
%         imgMax = min([2^10, model_Intensity(1,minDepth)]);
    else
        imgMax = 1;
    end

    % Determine bright center dots locations
    oneBlock = ImgSizeDot/3;
    oneBlockHalf = round(oneBlock/2);
    brightDotX = [oneBlockHalf(1) oneBlockHalf(1)+oneBlock(1) oneBlockHalf(1)+2*oneBlock(1)];
    brightDotY = [oneBlockHalf(2) oneBlockHalf(2)+oneBlock(2) oneBlockHalf(2)+2*oneBlock(2)];
    brightRepX = repmat(brightDotX,1,3)';
    brightRepY = reshape(repmat(brightDotY,3,1),1,[])';

    X_bright = ((ImgSizeDot(2)/2-1/2)-(brightRepY-1)) * maxDepth / FocalLength(1);
    Y_bright = ((ImgSizeDot(1)/2-1/2)-(brightRepX-1)) * maxDepth / FocalLength(2);
    Z_bright = maxDepth*ones(size(X_bright));

    orig_bright = [zeros(size(X_bright))-baseRT zeros(size(Y_bright)) zeros(size(Z_bright))]';
    dir_bright  = [           X_bright-baseRT              Y_bright              Z_bright]';

    [~,d_bright,~,~] = t.intersect(orig_bright,dir_bright-orig_bright);

    xvals_bright = d_bright.*X_bright-baseRT;
    yvals_bright = d_bright.*Y_bright;
    zvals_bright = d_bright.*Z_bright;

    brightPlotX = ImgSizeDot(2)/2 +.5 - FocalLength(1) .* xvals_bright./zvals_bright;
    brightPlotY = ImgSizeDot(1)/2 +.5 - FocalLength(2) .* yvals_bright./zvals_bright;

    % Determine where dots had to be added to original dot pattern on the left
    if pixShftLeft_T > 0
        jrow = 0;
        for irow = 1:size(dotAddLeft,1)
            indxMax = find(dotAddLeft(irow,:)==1, 1, 'last' );
            if ~isempty(indxMax)
                % If the dot is on the last 3 columns of the added pattern
                if indxMax >= size(dotAddLeft,2) - 2
                    jrow = jrow + 1;
                    addDotLeftX(jrow) = irow;
                    addDotLeftY(jrow) = indxMax;
                end
            end
        end

        X_add = ((ImgSizeDot(2)/2-1/2+pixShftLeft_T)-(addDotLeftY'-1)) * maxDepth / FocalLength(1);
        Y_add = ((ImgSizeDot(1)/2-1/2)-(addDotLeftX'-1)) * maxDepth / FocalLength(2);
        Z_add = maxDepth*ones(size(addDotLeftX'));

        orig_add = [zeros(size(X_add))-baseRT zeros(size(Y_add)) zeros(size(Z_add))]';
        dir_add  = [           X_add-baseRT              Y_add              Z_add]';

        [~,d_add,~,~] = t.intersect(orig_add,dir_add-orig_add);

        xvals_add = d_add.*X_add-baseRT;
        yvals_add = d_add.*Y_add;
        zvals_add = d_add.*Z_add;

        addPlotXLeft = ImgSizeDot(2)/2 +.5 - FocalLength(1) .* xvals_add./zvals_add;
        addPlotYLeft = ImgSizeDot(1)/2 +.5 - FocalLength(2) .* yvals_add./zvals_add;
    end

    % Determine where dots had to be added to original dot pattern on the right
    if pixShftRght_T > 0
        jrow = 0;
        for irow = 1:ImgSizeDot(1)
            indxMin = find(dotAddRght(irow,:)==1, 1, 'first' );
            if ~isempty(indxMin)
                % If the dot is on the first 3 columns of the added pattern
                if indxMin <= 3
                    jrow = jrow + 1;
                    addDotRghtX(jrow) = irow;
                    addDotRghtY(jrow) = indxMin + ImgSizeDot(2) + pixShftLeft_T;
                end
            end
        end

        X_add = ((ImgSizeDot(2)/2-1/2+pixShftLeft_T)-(addDotRghtY'-1)) * maxDepth / FocalLength(1);
        Y_add = ((ImgSizeDot(1)/2-1/2)-(addDotRghtX'-1)) * maxDepth / FocalLength(2);
        Z_add = maxDepth*ones(size(addDotRghtX'));

        orig_add = [zeros(size(X_add))-baseRT zeros(size(Y_add)) zeros(size(Z_add))]';
        dir_add  = [           X_add-baseRT              Y_add              Z_add]';

        [~,d_add,~,~] = t.intersect(orig_add,dir_add-orig_add);

        xvals_add = d_add.*X_add-baseRT;
        yvals_add = d_add.*Y_add;
        zvals_add = d_add.*Z_add;

        addPlotXRght = ImgSizeDot(2)/2 + .5 - FocalLength(1) .* xvals_add./zvals_add;
        addPlotYRght = ImgSizeDot(1)/2 + .5 - FocalLength(2) .* yvals_add./zvals_add;
    end

    % Plot padded IR image ------------------------------------------------
    if isPlotIR == 0
        figure, imshow(IRimg,[0 imgMax])
%         title('IR image of cropped projected dot pattern for correlation window')

        % Plot stars over bright center dots
        hold on, plot(brightPlotX+corrCol,brightPlotY+corrRow-cropRow,'y*'), hold off

        % Plot dashed line around where IR image will be cropped for displaying
        cropPlotX_corr = [corrCol+1, corrCol+ImgRes(2), corrCol+ImgRes(2), corrCol+1, corrCol+1];
        cropPlotY_corr = [corrRow+1, corrRow+1, corrRow+ImgRes(1), corrRow+ImgRes(1), corrRow+1];

        hold on, plot(cropPlotX_corr,cropPlotY_corr,'y:'), hold off
    end

    % Plot cropped IR image (size of IR image Kinect displays) ------------
    if nargout > 1 || isPlotIR == 1
        figure, imshow(IRimg_disp,[0 imgMax])
%         title('IR image size of Kinect output')

        % Plot stars over bright center dots
        hold on, plot(brightPlotX,brightPlotY-cropRow,'y*'), hold off
    end

    % Plot full IR image --------------------------------------------------
    if nargout > 2
        figure, imshow(IRimg_full,[0 imgMax])
        title('IR image of full projected dot pattern')

        % Plot stars over bright center dots
        hold on, plot(brightPlotX+numPixShift,brightPlotY,'y*'), hold off

        % Plot dashed line around where IR image will be cropped for padded img
        cropX1_corr = numPixShift + 1 - corrCol;
        cropX2_corr = numPixShift + 1 + ImgRes(2) - 1 + corrCol;
        cropY1_corr = cropRow + 1 - corrRow;
        cropY2_corr = cropRow + ImgRes(1) + corrRow;

        cropPlotX_disp = [cropX1_corr, cropX2_corr, cropX2_corr, cropX1_corr, cropX1_corr];
        cropPlotY_disp = [cropY1_corr, cropY1_corr, cropY2_corr, cropY2_corr, cropY1_corr];

        hold on, plot(cropPlotX_disp,cropPlotY_disp,'y:'), hold off

        % Plot where dots had to be added to original dot pattern on the left
        if pixShftLeft_T > 0
            hold on, plot(addPlotXLeft+numPixShift,addPlotYLeft,'b.'), hold off
        end

        % Plot where dots had to be added to original dot pattern on the right
        if pixShftRght_T > 0
            hold on, plot(addPlotXRght+numPixShift,addPlotYRght,'b.'), hold off
        end
    end
end


text:
export Button from './Button'
export ChoiceField from './ChoiceField'
export ChoiceFieldGroup from './ChoiceFieldGroup'
export Dialog from './Dialog'
export Dropdown from './Dropdown'
export Grid from './Grid'
export Icon from './Icon'
export Label from './Label'
export Link from './Link'
export List from './List'
export ListItem from './ListItem'
export NavBar from './NavBar'
export Overlay from './Overlay'
export SearchBox from './SearchBox'
export Table from './Table'
export TextField from './TextField'
export Toggle from './Toggle'

export fabricComponent from './fabricComponent'

redpajama_set_name: RedPajamaGithub


text:
package org.codehaus.modello.maven;

import java.io.File;
import java.util.Properties;

import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.modello.ModelloParameterConstants;

/**
 * Creates a JSON Schema from the model.
 *
 * @author Simone Tripodi
 * @since 1.8
 */
@Mojo( name = "jsonschema", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true )
public final class ModelloJsonSchemaGeneratorMojo
    extends AbstractModelloGeneratorMojo
{

    /**
     * The output directory of the generated JSON Schema. Hint: if you want to publish the schema automatically with
     * the site, configure this parameter to ${basedir}/target/generated-site/resources/jsonschema.
     */
    @Parameter( defaultValue = "${project.build.directory}/generated-site/jsonschema", required = true )
    private File outputDirectory;

    @Parameter
    private String jsonSchemaFileName;

    protected void customizeParameters( Properties parameters )
    {
        super.customizeParameters( parameters );

        if ( jsonSchemaFileName != null )
        {
            parameters.put( ModelloParameterConstants.OUTPUT_JSONSCHEMA_FILE_NAME, jsonSchemaFileName );
        }
    }

    @Override
    protected String getGeneratorType()
    {
        return "jsonschema";
    }

    @Override
    public File getOutputDirectory()
    {
        return outputDirectory;
    }

}


text:
<?php
require('FolderUploaderCode.php');

$rootpath = './songs/';
$fileinfos = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootpath)
);
//accepts multiple files from folder
foreach($fileinfos as $pathname => $fileinfo) {
    if (!$fileinfo->isFile()) continue;
    // var_dump($pathname);
    //reads the ds store file too
    if (strpos($pathname, 'DS_Store')){
    	echo "I hate the DS_Store";
	}
	else{
		$returnedArray = FolderUploaderCode::ParseMachine($pathname);
		// $arrayChunked = array_chunk($returnedArray, 5000, true);
		// var_dump($arrayChunked);die();
		##This bit
		// var_dump($pathname);
		// $str_to_insert = "[P]";
		// $newPathname = substr_replace($pathname, $str_to_insert, -5, 0);
		// var_dump($newPathname);
		// FolderUploaderCode::BuildExcelParsedSheet($returnedArray, $newPathname);
	}
}

echo "

It twerked. Much Success!";

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.test.phpunit"><info><title>Zend_Test_PHPUnit</title></info>

    <para>
        <classname>Zend_Test_PHPUnit</classname> bietet einen Testfall für <acronym>MVC</acronym>-Anwendungen,
        der Zusicherungen für Tests auf eine Vielzahl von Verantwortlichkeiten enthält. Um
        zu verstehen, was man damit machen kann, ist es wahrscheinlich am einfachsten, sich das folgende
        Beispiel anzusehen.
    </para>

    <example xml:id="zend.test.phpunit.loginexample"><info><title>Beispiel eines Testfalls für ein Anwendungs-Login</title></info>

        <para>
            Das folgende ist ein einfacher Testfall für einen <classname>UserController</classname>,
            um verschiedene Dinge zu prüfen:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    Das Login-Formular soll nicht-authentifizierten Benutzern angezeigt werden.
                </para>
            </listitem>

            <listitem>
                <para>
                    Wenn sich ein Benutzer einloggt, soll er zu seiner Profilseite umgeleitet
                    werden und diese Profilseite soll relevante Informationen enthalten.
                </para>
            </listitem>
        </itemizedlist>

        <para>
            Dieses spezielle Beispiel setzt ein paar Dinge voraus. Zunächst verschieben wir das meiste
            unseres Bootstrappings in ein Plugin. Das vereinfacht das Setup des Testfalls, da es uns
            erlaubt, unsere Umgebung gezielt zu definieren und die
            Anwendung mit einer einzigen Zeile zu starten. Außerdem setzt unser spezielles Beispiel auch
            voraus, dass das automatische Laden von Klassen aktiviert ist, so dass wir uns nicht um das Laden
            der benötigten Klassen kümmern müssen (wie die richtigen Controller, Plugins, usw).
        </para>

        <programlisting language="php"><![CDATA[
class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public function setUp()
    {
        $this->bootstrap = array($this, 'appBootstrap');
        parent::setUp();
    }

    public function appBootstrap()
    {
        $this->frontController
             ->registerPlugin(new Bugapp_Plugin_Initialize('development'));
    }

    public function testCallWithoutActionShouldPullFromIndexAction()
    {
        $this->dispatch('/user');
        $this->assertController('user');
        $this->assertAction('index');
    }

    public function testIndexActionShouldContainLoginForm()
    {
        $this->dispatch('/user');
        $this->assertAction('index');
        $this->assertQueryCount('form#loginForm', 1);
    }

    public function testValidLoginShouldGoToProfilePage()
    {
        $this->request->setMethod('POST')
              ->setPost(array(
                  'username' => 'foobar',
                  'password' => 'foobar'
              ));
        $this->dispatch('/user/login');
        $this->assertRedirectTo('/user/view');

        $this->resetRequest()
             ->resetResponse();
        $this->request->setMethod('GET')
             ->setPost(array());
        $this->dispatch('/user/view');
        $this->assertRoute('default');
        $this->assertModule('default');
        $this->assertController('user');
        $this->assertAction('view');
        $this->assertNotRedirect();
        $this->assertQuery('dl');
        $this->assertQueryContentContains('h2', 'User: foobar');
    }
}
]]></programlisting>

        <para>
            Dieses Beispiel könnte auch einfacher geschrieben werden -- nicht alle der gezeigten
            Zusicherungen sind notwendig. Hoffentlich zeigt es, wie einfach es sein kann, die eigene
            Anwendung zu testen.
        </para>
    </example>

    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="Zend_Test-PHPUnit-Bootstrapping.xml"/>
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="Zend_Test-PHPUnit-Testing.xml"/>
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="Zend_Test-PHPUnit-Assertions.xml"/>
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="Zend_Test-PHPUnit-Examples.xml"/>
</section>


text:
#region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.

// KEngine - Toolset and framework for Unity3D
// ===================================
//
// Filename: AssetFileLoader.cs
// Date:     2015/12/03
// Author:  Kelly
// Email: 23110388@qq.com
// Github: https://github.com/mr-kelly/KEngine
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.

#endregion

using System;
using System.Collections;
using System.IO;
using UnityEngine;
using Object = UnityEngine.Object;

namespace KEngine
{
    /// <summary>
    /// 根據不同模式,從AssetBundle中獲取Asset或從Resources中獲取,两种加载方式同时实现的桥接类
    /// 读取一个文件的对象,不做拷贝和引用
    /// </summary>
    public class AssetFileLoader : AbstractResourceLoader
    {
        public delegate void AssetFileBridgeDelegate(bool isOk, Object resultObj);

        public Object Asset
        {
            get { return ResultObject as Object; }
        }

        private bool IsLoadAssetBundle;

        public override float Progress
        {
            get
            {
                if (_bundleLoader != null)
                    return _bundleLoader.Progress;
                return 0;
            }
        }

        private AssetBundleLoader _bundleLoader;

        public static AssetFileLoader Load(string path, AssetFileBridgeDelegate assetFileLoadedCallback = null, LoaderMode loaderMode = LoaderMode.Async)
        {
            // 添加扩展名
			if (!KResourceModule.IsEditorLoadAsset)
	            path = path + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);

            LoaderDelgate realcallback = null;
            if (assetFileLoadedCallback != null)
            {
                realcallback = (isOk, obj) => assetFileLoadedCallback(isOk, obj as Object);
            }

            return AutoNew<AssetFileLoader>(path, realcallback, false, loaderMode);
        }

        /// <summary>
        /// Check Bundles/[Platform]/xxxx.kk exists?
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsBundleResourceExist(string url)
        {
            if (KResourceModule.IsEditorLoadAsset)
            {
                var editorPath = "Assets/" + KEngineDef.ResourcesBuildDir + "/" + url;
                var hasEditorUrl = File.Exists(editorPath);
                if (hasEditorUrl) return true;
            }

            return KResourceModule.IsResourceExist(KResourceModule.BundlesPathRelative  + url.ToLower() + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt));
        }
        protected override void Init(string url, params object[] args)
        {
            var loaderMode = (LoaderMode)args[0];

            base.Init(url, args);
            KResourceModule.Instance.StartCoroutine(_Init(Url, loaderMode));
        }

        private IEnumerator _Init(string path, LoaderMode loaderMode)
        {
            IsLoadAssetBundle = AppEngine.GetConfig("KEngine", "IsLoadAssetBundle").ToInt32() != 0;

            Object getAsset = null;

			if (KResourceModule.IsEditorLoadAsset && Application.isEditor)
			{
#if UNITY_EDITOR
				if (path.EndsWith(".unity"))
				{
					// scene
					getAsset = KResourceModule.Instance;
					Log.LogWarning("Load scene from Build Settings: {0}", path);
				}
				else
				{
					getAsset = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/" + KEngineDef.ResourcesBuildDir + "/" + path, typeof(UnityEngine.Object));
					if (getAsset == null)
					{
						Log.Error("Asset is NULL(from {0} Folder): {1}", KEngineDef.ResourcesBuildDir, path);
					}
				}
#else
				Log.Error("`IsEditorLoadAsset` is Unity Editor only");

#endif
			}
            else if (!IsLoadAssetBundle)
            {
                string extension = Path.GetExtension(path);
                path = path.Substring(0, path.Length - extension.Length); // remove extensions

                getAsset = Resources.Load<Object>(path);
                if (getAsset == null)
                {
                    Log.Error("Asset is NULL(from Resources Folder): {0}", path);
                }
            }
            else
            {
                _bundleLoader = AssetBundleLoader.Load(path, null, loaderMode);

                while (!_bundleLoader.IsCompleted)
                {
                    if (IsReadyDisposed) // 中途释放
                    {
                        _bundleLoader.Release();
                        OnFinish(null);
                        yield break;
                    }
                    yield return null;
                }

                if (!_bundleLoader.IsSuccess)
                {
                    Log.Error("[AssetFileLoader]Load BundleLoader Failed(Error) when Finished: {0}", path);
                    _bundleLoader.Release();
                    OnFinish(null);
                    yield break;
                }

                var assetBundle = _bundleLoader.Bundle;

                DateTime beginTime = DateTime.Now;
#if UNITY_5 || UNITY_2017_1_OR_NEWER
                // Unity 5 下,不能用mainAsset, 要取对象名
                var abAssetName = Path.GetFileNameWithoutExtension(Url).ToLower();
                if (!assetBundle.isStreamedSceneAssetBundle)
                {
                    if (loaderMode == LoaderMode.Sync)
                    {
                        getAsset = assetBundle.LoadAsset(abAssetName);
                        Debuger.Assert(getAsset);
                        _bundleLoader.PushLoadedAsset(getAsset);
                    }
                    else
                    {
                        var request = assetBundle.LoadAssetAsync(abAssetName);
                        while (!request.isDone)
                        {
                            yield return null;
                        }
                        Debuger.Assert(getAsset = request.asset);
                        _bundleLoader.PushLoadedAsset(getAsset);
                    }
                }
                else
                {
                    // if it's a scene in asset bundle, did nothing
                    // but set a fault Object the result
                    getAsset = KResourceModule.Instance;
                }
#else
                // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化
                //AssetBundleRequest request = assetBundle.LoadAsync("", typeof(Object));// mainAsset
                //while (!request.isDone)
                //{
                //    yield return null;
                //}
                try
                {
                    Debuger.Assert(getAsset = assetBundle.mainAsset);
                }
                catch
                {
                    Log.Error("[OnAssetBundleLoaded:mainAsset]{0}", path);
                }
#endif

                KResourceModule.LogLoadTime("AssetFileBridge", path, beginTime);

                if (getAsset == null)
                {
                    Log.Error("Asset is NULL: {0}", path);
                }

            }

            if (Application.isEditor)
            {
                if (getAsset != null)
                    KResoourceLoadedAssetDebugger.Create(getAsset.GetType().Name, Url, getAsset as Object);

                // 编辑器环境下,如果遇到GameObject,对Shader进行Fix
                if (getAsset is GameObject)
                {
                    var go = getAsset as GameObject;
                    foreach (var r in go.GetComponentsInChildren<Renderer>(true))
                    {
                        RefreshMaterialsShaders(r);
                    }
                }
            }

            if (getAsset != null)
            {
                // 更名~ 注明来源asset bundle 带有类型
                getAsset.name = String.Format("{0}~{1}", getAsset, Url);
            }
            OnFinish(getAsset);
        }

        /// <summary>
        /// 编辑器模式下,对指定GameObject刷新一下Material
        /// </summary>
        public static void RefreshMaterialsShaders(Renderer renderer)
        {
            if (renderer.sharedMaterials != null)
            {
                foreach (var mat in renderer.sharedMaterials)
                {
                    if (mat != null && mat.shader != null)
                    {
                        mat.shader = Shader.Find(mat.shader.name);
                    }
                }
            }
        }

        protected override void DoDispose()
        {
            base.DoDispose();

            if (_bundleLoader != null)
                _bundleLoader.Release(); // 释放Bundle(WebStream)

            //if (IsFinished)
            {
                if (!IsLoadAssetBundle)
                {
                    Resources.UnloadAsset(ResultObject as Object);
                }
                else
                {
                    //Object.DestroyObject(ResultObject as UnityEngine.Object);

                    // Destroying GameObjects immediately is not permitted during physics trigger/contact, animation event callbacks or OnValidate. You must use Destroy instead.
//                    Object.DestroyImmediate(ResultObject as Object, true);
                }

                //var bRemove = Caches.Remove(Url);
                //if (!bRemove)
                //{
                //    Log.Warning("[DisposeTheCache]Remove Fail(可能有两个未完成的,同时来到这) : {0}", Url);
                //}
            }
            //else
            //{
            //    // 交给加载后,进行检查并卸载资源
            //    // 可能情况TIPS:两个未完成的!会触发上面两次!
            //}
        }
    }

}


text:
* Multi-selects
* Radio buttons
* Shared module objects

## Data

* Fixtures in @Before and @After
* Create data in @Test and destroy in @After

## Other

* Grab screenshot (how, without failing test?)


text:
using namespace Ilwis;
PaletteColorLookUp::PaletteColorLookUp(){

}

PaletteColorLookUp::PaletteColorLookUp(const QString &definition){
    fromDefinition(definition);
}

PaletteColorLookUp::PaletteColorLookUp(const IDomain &dom, const QString &rprCode)
{
    _cyclic = hasType(dom->valueType(), itINDEXEDITEM | itNAMEDITEM | itSTRING);
    QSqlQuery db(kernel()->database());
    QString query = QString("Select * from representation where code='%1'").arg(rprCode != "" ? rprCode : "primarycolors" );
    if (db.exec(query)) {
        if ( db.next()){
            QSqlRecord rec = db.record();
            QString  definition = rec.field("definition").value().toString();
            fromDefinition(definition, dom);
        }
    }
}

PaletteColorLookUp::PaletteColorLookUp(boost::container::flat_map<quint32, QColor> &newcolors) : _colors(newcolors)
{

}

QColor PaletteColorLookUp::value2color(double index, const NumericRange &, const NumericRange &) const
{
    int localIndex  = index;
    if ( _cyclic){
        localIndex = localIndex % _colors.size();
    }
    auto iter = _colors.find(localIndex);
    if ( iter != _colors.end()){

        QColor clr =  (*iter).second;
        return clr;
    }
    return QColor();
}

void PaletteColorLookUp::fromDefinition(const QString &definition, const IDomain& dom){
    QStringList parts = definition.split("|");
    if ( dom.isValid()){
        if ( hasType(dom->valueType(), itTHEMATICITEM|itNUMERICITEM|itTIMEITEM)){
            IItemDomain itemdom = dom.as<ItemDomain<DomainItem>>();
            int index = 0;
            for(auto item : itemdom){
                QString part = parts[index % parts.size()];
                _colors[(quint32)item->raw()] = string2color(part);
                ++index;
            }
            return;
        }
    }
    int index = 0;
    _cyclic = true;
    for( QString part : parts){
        QColor color = string2color(part);
        _colors[index - 1] = color;
        ++index;
    }
}

ColorLookUp *PaletteColorLookUp::clone() const{
    PaletteColorLookUp *newpalette = new PaletteColorLookUp();
    newpalette->_colors = _colors;
    newpalette->_cyclic = _cyclic;
    return newpalette;
}

void PaletteColorLookUp::setColor(double value, const QColor &clr)
{
    _colors[(quint32)value] = clr;
}


text:
class RootController < ApplicationController
  def index
    @cookie_clickers = CookieClicker.where(:published => true).order('created_at desc').page(params[:page])
    respond_to do |format|
      format.html
      format.js
    end
  end
end


text:
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class BoletoSimples < OmniAuth::Strategies::OAuth2
      DEFAULT_SCOPE = 'profile'
      ENVIRONMENTS = {
        development: 'http://localhost:5000',
        sandbox: 'https://sandbox.boletosimples.com.br',
        production: 'https://boletosimples.com.br'
      }.freeze
      option :name, 'boletosimples'
      option :client_options,
             token_url: '/api/v1/oauth2/token',
             setup: true

      option :authorize_options, %i[scope response_type]
      option :provider_ignores_state, true
      option :environment, :production

      uid { raw_info['id'] }

      info do
        {
          person_type: raw_info['person_type'],
          first_name: raw_info['first_name'],
          middle_name: raw_info['middle_name'],
          last_name: raw_info['last_name'],
          full_name: raw_info['full_name'],
          date_of_birth: raw_info['date_of_birth'],
          email: raw_info['email'],
          cpf: raw_info['cpf'],
          mother_name: raw_info['mother_name'],
          father_name: raw_info['father_name'],
          sex: raw_info['sex']
        }
      end

      extra do
        {
          address_street_name: raw_info['address_street_name'],
          address_number: raw_info['address_number'],
          address_complement: raw_info['address_complement'],
          address_state: raw_info['address_state'],
          address_city_name: raw_info['address_city_name'],
          address_neighborhood: raw_info['address_neighborhood'],
          address_postal_code: raw_info['address_postal_code'],
          phone_number: raw_info['phone_number'],
          business_legal_name: raw_info['business_legal_name'],
          business_name: raw_info['business_name'],
          business_cnpj: raw_info['business_cnpj']
        }
      end

      def setup_phase
        environment = options.environment || :production
        options.client_options[:site] = ENVIRONMENTS[environment.to_sym]
        options.client_options[:authorize_url] = "#{ENVIRONMENTS[environment.to_sym]}/api/v1/oauth2/authorize"

        return unless options.user_agent

        options.client_options[:connection_opts] = {
          headers: {
            'User-Agent' => options.user_agent
          }
        }
      end

      def raw_info
        @raw_info ||= load_identity
      end

      def callback_url
        options[:redirect_uri] || (full_host + script_name + callback_path)
      end

      def authorize_params
        super.tap do |params|
          params[:scope] ||= DEFAULT_SCOPE
        end
      end

      private

      def load_identity
        access_token.get('/api/v1/userinfo').parsed
      end
    end
  end
end

OmniAuth.config.add_camelization 'boletosimples', 'BoletoSimples'


text:
import ldap
import os
import logging

logger = logging.getLogger(__name__)

class Authenticator:
    def __init__(self, config):
        if config.get('debug'):
            self.authenticate = self.debug_auth
            return
        self.authenticate = self.ldap_auth

        if 'ldap_cert_path' in config:
            self.cert_path = config['ldap_cert_path']
            if not os.access(self.cert_path, os.R_OK):
                logger.error("Failed to read ldap_cert_path certificate")
                raise IOError
        else:
            self.cert_path = None

        self.bind_user = config.get('ldap_bind_user')
        self.bind_password = config.get('ldap_bind_password')
        self.search_filter = config.get('ldap_search_filter')

        self.ldap_url = config.get('ldap_url')
        self.base_dn = config.get('ldap_base_dn')

        self.user_suffix = config.get('ldap_user_suffix')

    def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)

        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, ['dn'])
                if len(result) < 1:
                    return False
                auth_user = result[0][0]

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warn("%s", err)
            return None
        return True

    def debug_auth(self, username, password):
        return True


text:
set -e

# install pre-requisite package
sudo apt install -y libssl-dev

TMUX_VERSION=3.2
# set below to a blank string if the version is not RC
# IS_RC='-rc'
# RC_VERSION='-rc3'
IS_RC=''
RC_VERSION=''

LIBEVENT_VERSION=2.1.12
NCURSES_VERSION=6.1

# create our directories
mkdir -p $HOME/local $HOME/tmux_tmp
cd $HOME/tmux_tmp

# download source files for tmux, libevent, and ncurses
# wget -O tmux-${TMUX_VERSION}.tar.gz http://sourceforge.net/projects/tmux/files/tmux/tmux-${TMUX_VERSION}/tmux-${TMUX_VERSION}.tar.gz/download
wget -O tmux-${TMUX_VERSION}.tar.gz https://github.com/tmux/tmux/releases/download/${TMUX_VERSION}${IS_RC}/tmux-${TMUX_VERSION}${RC_VERSION}.tar.gz

# wget https://github.com/downloads/libevent/libevent/libevent-${LIBEVENT_VERSION}-stable.tar.gz
wget https://github.com/libevent/libevent/releases/download/release-${LIBEVENT_VERSION}-stable/libevent-${LIBEVENT_VERSION}-stable.tar.gz

wget ftp://ftp.gnu.org/gnu/ncurses/ncurses-${NCURSES_VERSION}.tar.gz

# extract files, configure, and compile

############
# libevent #
############
tar xvzf libevent-$LIBEVENT_VERSION-stable.tar.gz
cd libevent-$LIBEVENT_VERSION-stable
./configure --prefix=$HOME/local --disable-shared
make
make install
cd ..

############
# ncurses  #
############
tar xvzf ncurses-$NCURSES_VERSION.tar.gz
cd ncurses-$NCURSES_VERSION
./configure --prefix=$HOME/local
make
make install
cd ..

############
# tmux     #
############
tar xvzf tmux-${TMUX_VERSION}.tar.gz
cd tmux-${TMUX_VERSION}${RC_VERSION}
./configure CFLAGS="-I$HOME/local/include -I$HOME/local/include/ncurses" LDFLAGS="-L$HOME/local/lib -L$HOME/local/include/ncurses -L$HOME/local/include"
CPPFLAGS="-I$HOME/local/include -I$HOME/local/include/ncurses" LDFLAGS="-static -L$HOME/local/include -L$HOME/local/include/ncurses -L$HOME/local/lib" make
cp tmux $HOME/local/bin
cd ..

# cleanup
rm -rf $HOME/tmux_tmp

echo "$HOME/local/bin/tmux is now available. You can optionally add $HOME/local/bin to your PATH."


text:
interface Currency {
    symbol: string;
    name: string;
    symbol_native: string;
    decimal_digits: number;
    code: 'USD' | 'JPY';
    name_plural: string;
}

const USD: Currency = {
    'symbol': '$',
    'name': 'US Dollar',
    'symbol_native': '$',
    'decimal_digits': 3,
    'code': 'USD',
    'name_plural': 'US dollars'
}

const JPY: Currency = {
    'symbol': '¥',
    'name': 'Japanese Yen',
    'symbol_native': '¥',
    'decimal_digits': 0,
    'code': 'JPY',
    'name_plural': 'Japanese yen'
}

export interface MoneyJSON {
    amount: number;
    currency: CurrencyType;
}

export interface ExchangeRate {
    main: CurrencyType;
    pairs: ExchangeRatePair[];
}

export interface ExchangeRatePair {
    pair: CurrencyPair;
    rate: number;
}

export type CurrencyPair = 'USD/JPY' | 'JPY/USD';

export type CurrencyType = 'USD' | 'JPY';

class BaseCurrency {
    public static USD = USD;
    public static JPY = JPY;
}

export function isCurrency(object: any): object is Currency {
    return object && typeof object.symbol === 'string' && typeof object.code === 'string';
}

export function isMoney(object: any): object is Money {
    return object && typeof object.amount === 'number' && typeof object.currency === 'string';
}

export class Money extends BaseCurrency {
    amount: number;
    currency: CurrencyType;

    constructor(amount: number, currency: Currency | CurrencyType) {
        super();
        this.amount = amount;
        this.currency = isCurrency(currency) ? currency.code : currency;
    }

    add(money: Money): Money {
        return new Money(this.amount + money.amount, this.currency);
    }

    subtract(money: Money): Money {
        return new Money(this.amount - money.amount, this.currency);
    }

    multiply(multiplier: number): Money {
        const amount = this.amount * multiplier;
        return new Money(amount, this.currency);
    }

    divide(divisor: number): Money {
        const amount = this.amount / divisor;
        return new Money(amount, this.currency);
    }

    equals(money: Money): boolean {
        return this.amount === money.amount && this.currency === money.currency;
    }

    compare(money: Money): -1 | 0 | 1 {
        if (this.amount === money.amount) {
            return 0;
        }

        return this.amount > money.amount ? 1 : -1;
    }

    greaterThan(money: Money): boolean {
        return 1 === this.compare(money);
    }

    greaterThanOrEqual(money: Money): boolean {
        return 0 <= this.compare(money);
    }

    lessThan(money: Money): boolean {
        return -1 === this.compare(money);
    }

    lessThanOrEqual(money: Money): boolean {
        return 0 >= this.compare(money);
    }

    exchange(exchangeRate: ExchangeRate): Money {
        if (this.currency === exchangeRate.main) {
            return this;
        }

        const targetRate = exchangeRate.pairs.find(x => canExchange(this.currency, x, exchangeRate.main));
        if (!targetRate) {
            // cannot exchange
            throw `Cannot exchange because of no exchange rate against ${this.currency}`;
        }

        const amount = this.amount * targetRate.rate;
        return new Money(amount, exchangeRate.main);
    }

    format(decimalPlace: number = Money[this.currency].decimal_digits, fn: typeof round = round): string {
        const formatted = String(fn(this.amount, decimalPlace)).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
        return `${Money[this.currency].symbol_native} ${formatted}`;
    }
}

function canExchange(currency: CurrencyType, exchangeRate: ExchangeRatePair, targetCurrency: CurrencyType) {
    const pair = exchangeRate.pair.split('/');
    return pair[0] === currency && pair[1] === targetCurrency;
}

export function floor(num: number, n: number) {
    const pow = Math.pow(10, n);
    return Math.floor(num * pow) / pow;
}

export function ceil(num: number, n: number) {
    const pow = Math.pow(10, n);
    return Math.ceil(num * pow) / pow;
}

export function round(num: number, n: number) {
    const pow = Math.pow(10, n);
    return Math.round(num * pow) / pow;
}


text:
package jxl.biff;

import jxl.common.Logger;

import jxl.WorkbookSettings;

/**
 * Helper to get the Microsoft encoded URL from the given string
 */
public class EncodedURLHelper
{
  /**
   * The logger
   */
  private static Logger logger = Logger.getLogger(EncodedURLHelper.class);

  // The control codes
  private static byte msDosDriveLetter = 0x01;
  private static byte sameDrive = 0x02;
  private static byte endOfSubdirectory = 0x03;
  private static byte parentDirectory = 0x04;
  private static byte unencodedUrl = 0x05;

  public static byte[] getEncodedURL(String s, WorkbookSettings ws)
  {
    if (s.startsWith("http:"))
    {
      return getURL(s, ws);
    }
    else
    {
      return getFile(s, ws);
    }
  }

  private static byte[] getFile(String s, WorkbookSettings ws)
  {
    ByteArray byteArray = new ByteArray();

    int pos = 0;
    if (s.charAt(1) == ':')
    {
      // we have a drive letter
      byteArray.add(msDosDriveLetter);
      byteArray.add((byte) s.charAt(0));
      pos = 2;
    }
    else if (s.charAt(pos) == '\\' ||
             s.charAt(pos) == '/')
    {
      byteArray.add(sameDrive);
    }

    while (s.charAt(pos) == '\\' ||
           s.charAt(pos) == '/')
    {
      pos++;
    }

    while (pos < s.length())
    {
      int nextSepIndex1 = s.indexOf('/', pos);
      int nextSepIndex2 = s.indexOf('\\', pos);
      int nextSepIndex = 0;
      String nextFileNameComponent = null;

      if (nextSepIndex1 != -1 && nextSepIndex2 != -1)
      {
        // choose the smallest (ie. nearest) separator
        nextSepIndex = Math.min(nextSepIndex1, nextSepIndex2);
      }
      else if (nextSepIndex1 == -1 || nextSepIndex2 == -1)
      {
        // chose the maximum separator
        nextSepIndex = Math.max(nextSepIndex1, nextSepIndex2);
      }

      if (nextSepIndex == -1)
      {
        // no more separators
        nextFileNameComponent = s.substring(pos);
        pos = s.length();
      }
      else
      {
        nextFileNameComponent = s.substring(pos, nextSepIndex);
        pos = nextSepIndex + 1;
      }

      if (nextFileNameComponent.equals("."))
      {
        // current directory - do nothing
      }
      else if (nextFileNameComponent.equals(".."))
      {
        // parent directory
        byteArray.add(parentDirectory);
      }
      else
      {
        // add the filename component
        byteArray.add(StringHelper.getBytes(nextFileNameComponent,
                                            ws));
      }

      if (pos < s.length())
      {
        byteArray.add(endOfSubdirectory);
      }
    }

    return byteArray.getBytes();
  }

  private static byte[] getURL(String s, WorkbookSettings ws)
  {
    ByteArray byteArray = new ByteArray();
    byteArray.add(unencodedUrl);
    byteArray.add((byte) s.length());
    byteArray.add(StringHelper.getBytes(s, ws));
    return byteArray.getBytes();
  }
}


text: This directory contains images to support the demo. They are not otherwise needed


text:
package com.communote.server.core.common.caching;

import java.io.Serializable;

/**
 * A CacheElementProvider is required when an element is requested but not yet cached. In that case
 * the {@link #load(CacheKey)} method is called and the returned element will be cached.
 *
 * @author Communote GmbH - http://www.communote.com/
 *
 * @param <K>
 *            the type of the key to be used for caching
 * @param <T>
 *            the type of the objects that this provider provides
 */
public interface CacheElementProvider<K extends CacheKey, T extends Serializable> {
    /**
     * Constant representing eternal caching.
     */
    public static final int ETERNAL_TIME_TO_LIVE = -1;

    /**
     * Returns a unique string naming the content type of the elements provided by this provider
     * (e.g. 'image' when providing image data).
     *
     * @return the string name
     */
    public String getContentType();

    /**
     * Returns the time in seconds describing how long a provided element will be cached without
     * expiring (when it is not replaced manually). Return {@link #ETERNAL_TIME_TO_LIVE} when the
     * element should never expire.
     *
     * @return the time to live in the cache in seconds.
     */
    public int getTimeToLive();

    /**
     * Provides an element identified by the key for caching.
     *
     * @param key
     *            the key to identify the requested element
     * @return the loaded object or null if there is no element for the key
     * @throws CacheElementProviderException
     *             in case the loading failed and nothing should or can be cached
     */
    public T load(K key) throws CacheElementProviderException;
}


text:
package com.google.common.collect.testing.testers;

import static com.google.common.collect.testing.Helpers.getMethod;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static java.util.Collections.emptyList;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.testing.SerializableTester;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A generic JUnit test which tests {@code subList()} operations on a list.
 * Can't be invoked directly; please see
 * {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
 *
 * @author Chris Povirk
 */
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListSubListTester<E> extends AbstractListTester<E> {
  public void testSubList_startNegative() {
    try {
      getList().subList(-1, 0);
      fail("subList(-1, 0) should throw");
    } catch (IndexOutOfBoundsException expected) {
    }
  }

  public void testSubList_endTooLarge() {
    try {
      getList().subList(0, getNumElements() + 1);
      fail("subList(0, size + 1) should throw");
    } catch (IndexOutOfBoundsException expected) {
    }
  }

  public void testSubList_startGreaterThanEnd() {
    try {
      getList().subList(1, 0);
      fail("subList(1, 0) should throw");
    } catch (IndexOutOfBoundsException expected) {
    } catch (IllegalArgumentException expected) {
      /*
       * The subList() docs claim that this should be an
       * IndexOutOfBoundsException, but many JDK implementations throw
       * IllegalArgumentException:
       * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427
       */
    }
  }

  public void testSubList_empty() {
    assertEquals("subList(0, 0) should be empty",
        emptyList(), getList().subList(0, 0));
  }

  public void testSubList_entireList() {
    assertEquals("subList(0, size) should be equal to the original list",
        getList(), getList().subList(0, getNumElements()));
  }

  @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
  @CollectionSize.Require(absent = ZERO)
  public void testSubList_subListRemoveAffectsOriginal() {
    List<E> subList = getList().subList(0, 1);
    subList.remove(0);
    List<E> expected =
        Arrays.asList(createSamplesArray()).subList(1, getNumElements());
    expectContents(expected);
  }

  @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
  @CollectionSize.Require(absent = ZERO)
  public void testSubList_subListClearAffectsOriginal() {
    List<E> subList = getList().subList(0, 1);
    subList.clear();
    List<E> expected =
        Arrays.asList(createSamplesArray()).subList(1, getNumElements());
    expectContents(expected);
  }

  @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
  public void testSubList_subListAddAffectsOriginal() {
    List<E> subList = getList().subList(0, 0);
    subList.add(e3());
    expectAdded(0, e3());
  }

  @ListFeature.Require(SUPPORTS_SET)
  @CollectionSize.Require(absent = ZERO)
  public void testSubList_subListSetAffectsOriginal() {
    List<E> subList = getList().subList(0, 1);
    subList.set(0, e3());
    List<E> expected = Helpers.copyToList(createSamplesArray());
    expected.set(0, e3());
    expectContents(expected);
  }

  @ListFeature.Require(SUPPORTS_SET)
  @CollectionSize.Require(absent = ZERO)
  public void testSubList_originalListSetAffectsSubList() {
    List<E> subList = getList().subList(0, 1);
    getList().set(0, e3());
    assertEquals("A set() call to a list after a sublist has been created "
        + "should be reflected in the sublist",
        Collections.singletonList(e3()), subList);
  }

  @ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_subListRemoveAffectsOriginalLargeList() {
    List<E> subList = getList().subList(1, 3);
    subList.remove(e2());
    List<E> expected = Helpers.copyToList(createSamplesArray());
    expected.remove(2);
    expectContents(expected);
  }

  @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_subListAddAtIndexAffectsOriginalLargeList() {
    List<E> subList = getList().subList(2, 3);
    subList.add(0, e3());
    expectAdded(2, e3());
  }

  @ListFeature.Require(SUPPORTS_SET)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_subListSetAffectsOriginalLargeList() {
    List<E> subList = getList().subList(1, 2);
    subList.set(0, e3());
    List<E> expected = Helpers.copyToList(createSamplesArray());
    expected.set(1, e3());
    expectContents(expected);
  }

  @ListFeature.Require(SUPPORTS_SET)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_originalListSetAffectsSubListLargeList() {
    List<E> subList = getList().subList(1, 3);
    getList().set(1, e3());
    assertEquals("A set() call to a list after a sublist has been created "
        + "should be reflected in the sublist",
        Arrays.asList(e3(), e2()), subList);
  }

  public void testSubList_ofSubListEmpty() {
    List<E> subList = getList().subList(0, 0).subList(0, 0);
    assertEquals("subList(0, 0).subList(0, 0) should be an empty list",
        emptyList(), subList);
  }

  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_ofSubListNonEmpty() {
    List<E> subList = getList().subList(0, 2).subList(1, 2);
    assertEquals("subList(0, 2).subList(1, 2) "
        + "should be a single-element list of the element at index 1",
        Collections.singletonList(getOrderedElements().get(1)), subList);
  }

  @CollectionSize.Require(absent = {ZERO})
  public void testSubList_size() {
    List<E> list = getList();
    int size = getNumElements();
    assertEquals(list.subList(0, size).size(),
                 size);
    assertEquals(list.subList(0, size - 1).size(),
                 size - 1);
    assertEquals(list.subList(1, size).size(),
                 size - 1);
    assertEquals(list.subList(size, size).size(),
                 0);
    assertEquals(list.subList(0, 0).size(),
                 0);
  }

  @CollectionSize.Require(absent = {ZERO})
  public void testSubList_isEmpty() {
    List<E> list = getList();
    int size = getNumElements();
    for (List<E> subList : Arrays.asList(
        list.subList(0, size),
        list.subList(0, size - 1),
        list.subList(1, size),
        list.subList(0, 0),
        list.subList(size, size))) {
      assertEquals(subList.isEmpty(), subList.size() == 0);
    }
  }

  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_get() {
    List<E> list = getList();
    int size = getNumElements();
    List<E> copy = list.subList(0, size);
    List<E> head = list.subList(0, size - 1);
    List<E> tail = list.subList(1, size);
    assertEquals(list.get(0), copy.get(0));
    assertEquals(list.get(size - 1), copy.get(size - 1));
    assertEquals(list.get(1), tail.get(0));
    assertEquals(list.get(size - 1), tail.get(size - 2));
    assertEquals(list.get(0), head.get(0));
    assertEquals(list.get(size - 2), head.get(size - 2));
    for (List<E> subList : Arrays.asList(copy, head, tail)) {
      for (int index : Arrays.asList(-1, subList.size())) {
        try {
          subList.get(index);
          fail("expected IndexOutOfBoundsException");
        } catch (IndexOutOfBoundsException expected) {
        }
      }
    }
  }

  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_contains() {
    List<E> list = getList();
    int size = getNumElements();
    List<E> copy = list.subList(0, size);
    List<E> head = list.subList(0, size - 1);
    List<E> tail = list.subList(1, size);
    assertTrue(copy.contains(list.get(0)));
    assertTrue(head.contains(list.get(0)));
    assertTrue(tail.contains(list.get(1)));
    // The following assumes all elements are distinct.
    assertTrue(copy.contains(list.get(size - 1)));
    assertTrue(head.contains(list.get(size - 2)));
    assertTrue(tail.contains(list.get(size - 1)));
    assertFalse(head.contains(list.get(size - 1)));
    assertFalse(tail.contains(list.get(0)));
  }

  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_indexOf() {
    List<E> list = getList();
    int size = getNumElements();
    List<E> copy = list.subList(0, size);
    List<E> head = list.subList(0, size - 1);
    List<E> tail = list.subList(1, size);
    assertEquals(copy.indexOf(list.get(0)),
                 0);
    assertEquals(head.indexOf(list.get(0)),
                 0);
    assertEquals(tail.indexOf(list.get(1)),
                 0);
    // The following assumes all elements are distinct.
    assertEquals(copy.indexOf(list.get(size - 1)),
                 size - 1);
    assertEquals(head.indexOf(list.get(size - 2)),
                 size - 2);
    assertEquals(tail.indexOf(list.get(size - 1)),
                 size - 2);
    assertEquals(head.indexOf(list.get(size - 1)),
                 -1);
    assertEquals(tail.indexOf(list.get(0)),
                 -1);
  }

  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testSubList_lastIndexOf() {
    List<E> list = getList();
    int size = list.size();
    List<E> copy = list.subList(0, size);
    List<E> head = list.subList(0, size - 1);
    List<E> tail = list.subList(1, size);
    assertEquals(copy.lastIndexOf(list.get(size - 1)),
                 size - 1);
    assertEquals(head.lastIndexOf(list.get(size - 2)),
                 size - 2);
    assertEquals(tail.lastIndexOf(list.get(size - 1)),
                 size - 2);
    // The following assumes all elements are distinct.
    assertEquals(copy.lastIndexOf(list.get(0)),
                 0);
    assertEquals(head.lastIndexOf(list.get(0)),
                 0);
    assertEquals(tail.lastIndexOf(list.get(1)),
                 0);
    assertEquals(head.lastIndexOf(list.get(size - 1)),
                 -1);
    assertEquals(tail.lastIndexOf(list.get(0)),
                 -1);
  }

  @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
  public void testReserializeWholeSubList() {
    SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements()));
  }

  @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
  public void testReserializeEmptySubList() {
    SerializableTester.reserializeAndAssert(getList().subList(0, 0));
  }

  @CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
  @CollectionSize.Require(absent = {ZERO, ONE})
  public void testReserializeSubList() {
    SerializableTester.reserializeAndAssert(getList().subList(0, 2));
  }

  /**
   * Returns the {@link Method} instance for
   * {@link #testSubList_originalListSetAffectsSubList()} so that tests
   * of {@link CopyOnWriteArrayList} can suppress them with
   * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until Sun bug
   * 6570631 is fixed.
   */
  @GwtIncompatible // reflection
  public static Method getSubListOriginalListSetAffectsSubListMethod() {
    return getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubList");
  }

  /**
   * Returns the {@link Method} instance for
   * {@link #testSubList_originalListSetAffectsSubListLargeList()} ()} so that
   * tests of {@link CopyOnWriteArrayList} can suppress them with
   * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until Sun bug
   * 6570631 is fixed.
   */
  @GwtIncompatible // reflection
  public static Method getSubListOriginalListSetAffectsSubListLargeListMethod() {
    return getMethod(ListSubListTester.class, "testSubList_originalListSetAffectsSubListLargeList");
  }

  /**
   * Returns the {@link Method} instance for
   * {@link #testSubList_subListRemoveAffectsOriginalLargeList()} so that tests
   * of {@link CopyOnWriteArrayList} can suppress it with
   * {@code FeatureSpecificTestSuiteBuilder.suppressing()} until Sun bug
   * 6570575 is fixed.
   */
  @GwtIncompatible // reflection
  public static Method getSubListSubListRemoveAffectsOriginalLargeListMethod() {
    return getMethod(ListSubListTester.class, "testSubList_subListRemoveAffectsOriginalLargeList");
  }

  /*
   * TODO: perform all List tests on subList(), but beware infinite recursion
   */
}


text:
"""A regularizer for convolutions, based on group-lasso.

All the weights that are related to a single output are grouped into one LASSO
group (https://arxiv.org/pdf/1611.06321.pdf).
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from morph_net.framework import generic_regularizers

class ConvGroupLassoRegularizer(generic_regularizers.OpRegularizer):
  """A regularizer for convolutions, based on group-lasso.

  Supported ops: Conv2D and Conv2DBackpropInput (transposed Conv2D).
  are supported. The grouping is done according to the formula:

  (1 - l1_fraction) * L2(weights) / sqrt(dim) + l1_fraction * L1(weights) / dim,

  where `dim` is the number of weights associated with an activation, L2 and L1
  are the respective norms, and l1_fraction controls the balance between L1 and
  L2 grouping. The paper cited above experiments with 0.0 and 0.5 for
  l1_fraction.
  """

  def __init__(self, op, threshold, l1_fraction=0.0):
    """Creates an instance.

    Args:
      op: A tf.Operation object of type Conv2D or Conv2DBackpropInput.
      threshold: A float. When the norm of the group associated with an
        activation is below the threshold, it will be considered dead.
      l1_fraction: A float, controls the balance between L1 and L2 grouping
        (see above).

    Raises:
      ValueError: `op` is not of type 'Conv2D' or 'Conv2DBackpropInput', or
        l1_fraction is outside interval [0.0, 1.0].
    """
    if op.type not in ('Conv2D', 'Conv2DBackpropInput'):
      raise ValueError('The given op is not Conv2D or Conv2DBackpropInput.')
    if l1_fraction < 0.0 or l1_fraction > 1.0:
      raise ValueError(
          'l1_fraction should be in [0.0, 1.0], not %e.' % l1_fraction)

    self._threshold = threshold
    conv_weights = op.inputs[1]
    # For a Conv2D (Conv2DBackpropInput) the output dimension of the weight
    # matrix is 3 (2). We thus reduce over all other dimensions.

    l2_norm = tf.sqrt(
        tf.reduce_mean(tf.square(conv_weights), axis=_get_reduce_dims(op)))
    if l1_fraction > 0.0:
      l1_norm = tf.reduce_mean(tf.abs(conv_weights), axis=_get_reduce_dims(op))
      norm = l1_fraction * l1_norm + (1.0 - l1_fraction) * l2_norm
    else:
      norm = l2_norm
    # Sanity check: Output dimension of 'op' should match that of 'norm':
    assert op.outputs[0].shape.ndims == 4
    assert norm.shape.ndims == 1
    op.outputs[0].shape.dims[3].assert_is_compatible_with(norm.shape.dims[0])
    self._regularization_vector = norm
    self._alive_vector = norm > threshold

  @property
  def regularization_vector(self):
    return self._regularization_vector

  @property
  def alive_vector(self):
    return self._alive_vector

class ConvGroupLassoRegularizerFactory(object):
  """A class for creating a ConvGroupLassoRegularizer for convolutions."""

  def __init__(self, threshold, l1_fraction=0.0):
    """Creates an instance.

    Args:
      threshold: A float scalar, will be used as a threshold for all
        ConvGroupLassoRegularizer-s created by this class.
      l1_fraction: A float scalar, will be passed as l1_fraction to all
        ConvGroupLassoRegularizer-s created by this class.
    """
    self._threshold = threshold
    self._l1_fraction = l1_fraction

  def create_regularizer(self, op, opreg_manager=None):
    """Creates a ConvGroupLassoRegularizer for `op`.

    Args:
      op: A tf.Operation of type 'Conv2D'.
      opreg_manager: unused

    Returns:
      a ConvGroupLassoRegularizer that corresponds to `op`.
    """
    del opreg_manager  # unused
    return ConvGroupLassoRegularizer(op, self._threshold, self._l1_fraction)

def _get_reduce_dims(op):
  """Returns the reduction dimensions for grouping weights of various ops."""
  type_to_dims = {'Conv2D': (0, 1, 2), 'Conv2DBackpropInput': (0, 1, 3)}
  try:
    return type_to_dims[op.type]
  except KeyError:
    raise ValueError('Reduce dims are unknown for op type %s' % op.type)


text:
@interface PodsDummy_Pods_GMYHotSpotView_GMYHotSpotView : NSObject
@end
@implementation PodsDummy_Pods_GMYHotSpotView_GMYHotSpotView
@end


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Application\Model\Entity;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Form\Annotation;
//use Zend\Db\ResultSet\ResultSet;

class  Usuarios extends TableGateway
{
    public function __construct(Adapter $adapter = null, $databaseSchema = null, ResultSet $selectResultPrototype = null)
    {
        return parent::__construct('sofve_usuarios', $adapter, $databaseSchema,$selectResultPrototype);
    }
     public function addUsr($data=array())
        {
          $this->insert($data);
        }
}


text:
package org.perfcake.reporting.reporters;

import org.perfcake.common.PeriodType;
import org.perfcake.reporting.Measurement;
import org.perfcake.reporting.MeasurementUnit;
import org.perfcake.reporting.Quantity;
import org.perfcake.reporting.ReportingException;
import org.perfcake.reporting.destinations.Destination;
import org.perfcake.reporting.reporters.accumulators.Accumulator;
import org.perfcake.reporting.reporters.accumulators.AvgAccumulator;
import org.perfcake.reporting.reporters.accumulators.LastValueAccumulator;
import org.perfcake.reporting.reporters.accumulators.MaxAccumulator;
import org.perfcake.reporting.reporters.accumulators.MinAccumulator;
import org.perfcake.reporting.reporters.accumulators.SlidingWindowAvgAccumulator;
import org.perfcake.reporting.reporters.accumulators.SlidingWindowMaxAccumulator;
import org.perfcake.reporting.reporters.accumulators.SlidingWindowMinAccumulator;

/**
 * Reports the minimal, maximal and average value from the beginning
 * of the measuring to the moment when the results are published including. The actual value about what
 * the statistics are gathered is computed as a result of the {@link #computeResult(MeasurementUnit)} method.
 *
 * The default value of the reporter is a current value at the moment of publishing.
 *
 * @author Pavel Macík
 */
public abstract class StatsReporter extends AbstractReporter {

   /**
    * A property that determines if the metric of a maximal value is enabled or disabled.
    */
   private boolean maximumEnabled = true;

   /**
    * A property that determines if the metric of a minimal value is enabled or disabled.
    */
   private boolean minimumEnabled = true;

   /**
    * A property that determines if the metric of an average value is enabled or disabled.
    */
   private boolean averageEnabled = true;

   /**
    * A property that specifies a window size with the default value of {@link Integer#MAX_VALUE}.
    */
   private int windowSize = Integer.MAX_VALUE;

   /**
    * A String representation of a metric of a maximal value.
    */
   public static final String MAXIMUM = "Maximum";

   /**
    * A String representation of a metric of a minimal value.
    */
   public static final String MINIMUM = "Minimum";

   /**
    * A String representation of a metric of an average value.
    */
   public static final String AVERAGE = "Average";

   @SuppressWarnings("rawtypes")
   @Override
   protected Accumulator getAccumulator(final String key, final Class clazz) {
      if (Double.class.equals(clazz)) {
         if (windowSize == Integer.MAX_VALUE) {
            return getNonWindowedAccumulator(key);
         } else {
            return getWindowedAccumulator(key);
         }
      }
      return super.getAccumulator(key, clazz);
   }

   /**
    * Gets an appropriate accumulator for a given key from the Measurement Unit's results map for the case that the value of the {@link #windowSize} is
    * different from the default value of {@link Integer#MAX_VALUE}.
    *
    * @param key
    *       Name of the key from the results map.
    * @return An appropriate accumulator instance.
    */
   @SuppressWarnings("rawtypes")
   protected Accumulator getWindowedAccumulator(final String key) {
      switch (key) {
         case MAXIMUM:
            return new SlidingWindowMaxAccumulator(windowSize);
         case MINIMUM:
            return new SlidingWindowMinAccumulator(windowSize);
         case Measurement.DEFAULT_RESULT:
            return new LastValueAccumulator();
         case AVERAGE:
         default:
            return new SlidingWindowAvgAccumulator(windowSize);
      }
   }

   /**
    * Gets an appropriate accumulator for a given key from the Measurement Unit's results map for the case that the value of the {@link #windowSize} is
    * equal to the value of {@link Integer#MAX_VALUE}, which is the default value.
    *
    * @param key
    *       Name of the key from the results map.
    * @return An appropriate accumulator instance.
    */
   @SuppressWarnings("rawtypes")
   protected Accumulator getNonWindowedAccumulator(final String key) {
      switch (key) {
         case MAXIMUM:
            return new MaxAccumulator();
         case MINIMUM:
            return new MinAccumulator();
         case Measurement.DEFAULT_RESULT:
            return new LastValueAccumulator();
         case AVERAGE:
         default:
            return new AvgAccumulator();
      }
   }

   /**
    * Computes the actual result value about what the reporter will collect the statistics.
    * @param measurementUnit Provided {@link MeasurementUnit} with all the measured values.
    * @return The processed result based on the input {@link MeasurementUnit}.
    */
   protected abstract Double computeResult(final MeasurementUnit measurementUnit);

   @Override
   protected void doReport(final MeasurementUnit measurementUnit) throws ReportingException {
      final Double result = computeResult(measurementUnit);

      measurementUnit.appendResult(Measurement.DEFAULT_RESULT, result);

      if (averageEnabled) {
         measurementUnit.appendResult(AVERAGE, result);
      }

      if (minimumEnabled) {
         measurementUnit.appendResult(MINIMUM, result);
      }

      if (maximumEnabled) {
         measurementUnit.appendResult(MAXIMUM, result);
      }
   }

   @Override
   public void publishResult(final PeriodType periodType, final Destination destination) throws ReportingException {
      final Measurement m = newMeasurement();
      publishAccumulatedResult(m);
      final String unit = getResultUnit();
      if (unit != null) {
         wrapResultByQuantity(m, Measurement.DEFAULT_RESULT, unit);
         wrapResultByQuantity(m, AVERAGE, unit);
         wrapResultByQuantity(m, MINIMUM, unit);
         wrapResultByQuantity(m, MAXIMUM, unit);
      }
      destination.report(m);
   }

   private void wrapResultByQuantity(final Measurement measurement, final String key, final String unit) {
      final Number result = (Number) measurement.get(key);
      if (result != null) {
         measurement.set(key, new Quantity<>(result, unit));
      }
   }

   @Override
   protected void doReset() {
      // nothing needed, the parent does the job
   }

   /**
    * Gets the status of the metric of a maximal value
    *
    * @return Returns true if the metric of a maximal is enabled or false otherwise.
    */
   public boolean isMaximumEnabled() {
      return maximumEnabled;
   }

   /**
    * Enables or disables the metric of a maximal value.
    *
    * @param maximumEnabled
    *       Set true to enable the metric of a maximal value or false to disable it.
    * @return Instance of this for fluent API.
    */
   public StatsReporter setMaximumEnabled(final boolean maximumEnabled) {
      this.maximumEnabled = maximumEnabled;
      return this;
   }

   /**
    * Gets the status of the metric of a minimal value.
    *
    * @return true if the metric of a minimal value is enabled or false otherwise.
    */
   public boolean isMinimumEnabled() {
      return minimumEnabled;
   }

   /**
    * Enables or disables the metric of a minimal value.
    *
    * @param minimumEnabled
    *       true to enable the metric of a minimal value or false to disable it.
    * @return Instance of this for fluent API.
    */
   public StatsReporter setMinimumEnabled(final boolean minimumEnabled) {
      this.minimumEnabled = minimumEnabled;
      return this;
   }

   /**
    * Gets the status of the metric of an average value.
    *
    * @return true if the metric of an average value is enabled or false otherwise.
    */
   public boolean isAverageEnabled() {
      return averageEnabled;
   }

   /**
    * Enables or disables the metric of an average value.
    *
    * @param averageEnabled
    *       true to enable the metric of an average value or false to disable it.
    * @return Instance of this for fluent API.
    */
   public StatsReporter setAverageEnabled(final boolean averageEnabled) {
      this.averageEnabled = averageEnabled;
      return this;
   }

   /**
    * Gets the sliding window size if set. If the size is equal to {@link Integer#MAX_VALUE}, then it means the
    * sliding window is not used at all and the statistics are taken from the whole run.
    *
    * @return The sliding window size.
    */
   public int getWindowSize() {
      return windowSize;
   }

   /**
    * Sets the size of the sliding window.
    *
    * If the size is equal to {@link Integer#MAX_VALUE} (which is the default value), then it means the
    * sliding window is not used at all and the statistics are taken from the whole run.
    *
    * @param windowSize
    *       The sliding window size.
    * @return Instance of this for fluent API.
    */
   public StatsReporter setWindowSize(final int windowSize) {
      this.windowSize = windowSize;
      return this;
   }

   /**
    * Returns the unit of the results.
    * If it returns a value that is not null the method {@link #publishResult(PeriodType, Destination)} will wrap the reporter's results by a {@link Quantity} with the return value of
    * this method as units before sent to destinations.
    * If a stats reporter is supposed to have results with units the reporter is to override this method.

    * If the method returns a null value, the reporter's results remain untouched.
    *
    * @return The string representation of the reporter results' unit or a null value.
    */
   protected String getResultUnit() {
      return null;
   }
}


text:
angular
	.module('RPSApp', [])
	.controller('gameController', ['$scope', '$timeout',
		function($scope, $timeout) {

			/**
			* 0: rock
			* 1: paper
			* 2: scissor
			*/

			var self = this,
				// comparing the numbers and set points and message for the user
				compare = function compare(c1, c2) {
					if (c1 == c2) {
						self.play.result = 3;
					} else if ((c1 - c2 + 3) % 3 == 1) {
						self.gamestats.points.own += 1;
						self.play.result = 1;
					} else {
						self.gamestats.points.enemy += 1;
						self.play.result = 2;
					}
				},
				// get a random number and returns with selection of 0 || 1 || 2
				getComputerSelection = function getComputerSelection() {
					var c = Math.random();
					return (c < 0.33) ? 0 : (c >= 0.33 && c <= 0.66) ? 1 : 2;
				};

			// storing game points and currently selected items
			self.gamestats = {
				points: {
					own: 0,
					enemy: 0
				},
				choosen: {
					own: 0,
					enemy: 0
				}
			};

			// in animation, disable buttons and store result
			self.play = {
				own: false,
				enemy: false,
				result:0
			};

			self.playFor = function playFor(mine) {
				// re-set properties
				self.gamestats.choosen.own = 0;
				self.gamestats.choosen.enemy = 0;
				self.play.result = 0;
				self.play.own = true;
				self.play.enemy = true;
				// after animation compare and get the result
				// TODO make an event handler for animationEnd
				$timeout(function() {
					var computer = getComputerSelection();
					self.gamestats.choosen.own = parseInt(mine, 10);
					self.gamestats.choosen.enemy = parseInt(computer, 10);
					self.play.own = false;
					self.play.enemy = false;
					compare(mine, computer);
				}, 1200, true);
			};
		}
	]);