text:
package org.apache.commons.imaging;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.imaging.common.BinaryFileParser;
import org.apache.commons.imaging.common.IBufferedImageFactory;
import org.apache.commons.imaging.common.IImageMetadata;
import org.apache.commons.imaging.common.SimpleBufferedImageFactory;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceArray;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.formats.bmp.BmpImageParser;
import org.apache.commons.imaging.formats.dcx.DcxImageParser;
import org.apache.commons.imaging.formats.gif.GifImageParser;
import org.apache.commons.imaging.formats.icns.IcnsImageParser;
import org.apache.commons.imaging.formats.ico.IcoImageParser;
import org.apache.commons.imaging.formats.jpeg.JpegImageParser;
import org.apache.commons.imaging.formats.pcx.PcxImageParser;
import org.apache.commons.imaging.formats.png.PngImageParser;
import org.apache.commons.imaging.formats.pnm.PnmImageParser;
import org.apache.commons.imaging.formats.psd.PsdImageParser;
import org.apache.commons.imaging.formats.rgbe.RgbeImageParser;
import org.apache.commons.imaging.formats.tiff.TiffImageParser;
import org.apache.commons.imaging.formats.wbmp.WbmpImageParser;
import org.apache.commons.imaging.formats.xbm.XbmImageParser;
import org.apache.commons.imaging.formats.xpm.XpmImageParser;
import org.apache.commons.imaging.util.Debug;

public abstract class ImageParser extends BinaryFileParser implements
        SanselanConstants
{

    public static final ImageParser[] getAllImageParsers()
    {
        ImageParser result[] = { new JpegImageParser(), new TiffImageParser(),
                new PngImageParser(), new BmpImageParser(),
                new GifImageParser(), new PsdImageParser(),
                new PnmImageParser(), new IcoImageParser(),
                new IcnsImageParser(), new WbmpImageParser(),
                new PcxImageParser(), new DcxImageParser(),
                new XbmImageParser(), new XpmImageParser(),
                new RgbeImageParser()
        // new JBig2ImageParser(),
        // new TgaImageParser(),
        };

        return result;
    }

    public final IImageMetadata getMetadata(ByteSource byteSource)
            throws ImageReadException, IOException
    {
        return getMetadata(byteSource, null);
    }

    public abstract IImageMetadata getMetadata(ByteSource byteSource, Map params)
            throws ImageReadException, IOException;

    public final IImageMetadata getMetadata(byte bytes[])
            throws ImageReadException, IOException
    {
        return getMetadata(bytes, null);
    }

    public final IImageMetadata getMetadata(byte bytes[], Map params)
            throws ImageReadException, IOException
    {
        return getMetadata(new ByteSourceArray(bytes), params);
    }

    public final IImageMetadata getMetadata(File file)
            throws ImageReadException, IOException
    {
        return getMetadata(file, null);
    }

    public final IImageMetadata getMetadata(File file, Map params)
            throws ImageReadException, IOException
    {
        if (debug)
            System.out.println(getName() + ".getMetadata" + ": "
                    + file.getName());

        if (!canAcceptExtension(file))
            return null;

        return getMetadata(new ByteSourceFile(file), params);
    }

    public abstract ImageInfo getImageInfo(ByteSource byteSource, Map params)
            throws ImageReadException, IOException;

    public final ImageInfo getImageInfo(ByteSource byteSource)
            throws ImageReadException, IOException
    {
        return getImageInfo(byteSource, null);
    }

    public final ImageInfo getImageInfo(byte bytes[], Map params)
            throws ImageReadException, IOException
    {
        return getImageInfo(new ByteSourceArray(bytes), params);
    }

    public final ImageInfo getImageInfo(File file, Map params)
            throws ImageReadException, IOException
    {
        if (!canAcceptExtension(file))
            return null;

        return getImageInfo(new ByteSourceFile(file), params);
    }

    /**
     * @throws ImageReadException may be thrown by sub-classes
     * @throws IOException  may be thrown by sub-classes
     */
    public FormatCompliance getFormatCompliance(ByteSource byteSource)
            throws ImageReadException, IOException
    {
        return null;
    }

    public final FormatCompliance getFormatCompliance(byte bytes[])
            throws ImageReadException, IOException
    {
        return getFormatCompliance(new ByteSourceArray(bytes));
    }

    public final FormatCompliance getFormatCompliance(File file)
            throws ImageReadException, IOException
    {
        if (!canAcceptExtension(file))
            return null;

        return getFormatCompliance(new ByteSourceFile(file));
    }

    public List<BufferedImage> getAllBufferedImages(ByteSource byteSource)
            throws ImageReadException, IOException
    {
        BufferedImage bi = getBufferedImage(byteSource, null);

        List<BufferedImage> result = new ArrayList<BufferedImage>();

        result.add(bi);

        return result;
    }

    public final List<BufferedImage> getAllBufferedImages(byte bytes[])
            throws ImageReadException, IOException
    {
        return getAllBufferedImages(new ByteSourceArray(bytes));
    }

    public final List<BufferedImage> getAllBufferedImages(File file)
            throws ImageReadException, IOException
    {
        if (!canAcceptExtension(file))
            return null;

        return getAllBufferedImages(new ByteSourceFile(file));
    }

    // public boolean extractImages(ByteSource byteSource, File dstDir,
    // String dstRoot, ImageParser encoder) throws ImageReadException,
    // IOException, ImageWriteException
    // {
    // List v = getAllBufferedImages(byteSource);
    //
    // if (v == null)
    // return false;
    //
    // for (int i = 0; i < v.size(); i++)
    // {
    // BufferedImage image = (BufferedImage) v.get(i);
    // File file = new File(dstDir, dstRoot + "_" + i
    // + encoder.getDefaultExtension());
    // encoder.writeImage(image, new FileOutputStream(file), null);
    // }
    //
    // return false;
    // }
    //
    // public final boolean extractImages(byte bytes[], File dstDir,
    // String dstRoot, ImageParser encoder)
    //
    // throws ImageReadException, IOException, ImageWriteException
    // {
    // return extractImages(new ByteSourceArray(bytes), dstDir, dstRoot,
    // encoder);
    // }
    //
    // public final boolean extractImages(File file, File dstDir,
    // String dstRoot, ImageParser encoder)
    //
    // throws ImageReadException, IOException, ImageWriteException
    // {
    // if (!canAcceptExtension(file))
    // return false;
    //
    // return extractImages(new ByteSourceFile(file), dstDir, dstRoot,
    // encoder);
    // }

    public abstract BufferedImage getBufferedImage(ByteSource byteSource,
            Map params) throws ImageReadException, IOException;

    public final BufferedImage getBufferedImage(byte bytes[], Map params)
            throws ImageReadException, IOException
    {
        return getBufferedImage(new ByteSourceArray(bytes), params);
    }

    public final BufferedImage getBufferedImage(File file, Map params)
            throws ImageReadException, IOException
    {
        if (!canAcceptExtension(file))
            return null;

        return getBufferedImage(new ByteSourceFile(file), params);
    }

    /**
     * @throws IOException may be thrown by sub-classes
     */
    public void writeImage(BufferedImage src, OutputStream os, Map params)
            throws ImageWriteException, IOException
    {
        try
        {
            os.close(); // we are obligated to close stream.
        } catch (Exception e)
        {
            Debug.debug(e);
        }

        throw new ImageWriteException("This image format (" + getName()
                + ") cannot be written.");
    }

    public final Dimension getImageSize(byte bytes[])
            throws ImageReadException, IOException
    {
        return getImageSize(bytes, null);
    }

    public final Dimension getImageSize(byte bytes[], Map params)
            throws ImageReadException, IOException
    {
        return getImageSize(new ByteSourceArray(bytes), params);
    }

    public final Dimension getImageSize(File file) throws ImageReadException,
            IOException
    {

        return getImageSize(file, null);
    }

    public final Dimension getImageSize(File file, Map params)
            throws ImageReadException, IOException
    {

        if (!canAcceptExtension(file))
            return null;

        return getImageSize(new ByteSourceFile(file), params);
    }

    public abstract Dimension getImageSize(ByteSource byteSource, Map params)
            throws ImageReadException, IOException;

    public abstract String getXmpXml(ByteSource byteSource, Map params)
            throws ImageReadException, IOException;

    public final byte[] getICCProfileBytes(byte bytes[])
            throws ImageReadException, IOException
    {
        return getICCProfileBytes(bytes, null);
    }

    public final byte[] getICCProfileBytes(byte bytes[], Map params)
            throws ImageReadException, IOException
    {
        return getICCProfileBytes(new ByteSourceArray(bytes), params);
    }

    public final byte[] getICCProfileBytes(File file)
            throws ImageReadException, IOException
    {
        return getICCProfileBytes(file, null);
    }

    public final byte[] getICCProfileBytes(File file, Map params)
            throws ImageReadException, IOException
    {
        if (!canAcceptExtension(file))
            return null;

        if (debug)
            System.out.println(getName() + ": " + file.getName());

        return getICCProfileBytes(new ByteSourceFile(file), params);
    }

    public abstract byte[] getICCProfileBytes(ByteSource byteSource, Map params)
            throws ImageReadException, IOException;

    public final String dumpImageFile(byte bytes[]) throws ImageReadException,
            IOException
    {
        return dumpImageFile(new ByteSourceArray(bytes));
    }

    public final String dumpImageFile(File file) throws ImageReadException,
            IOException
    {
        if (!canAcceptExtension(file))
            return null;

        if (debug)
            System.out.println(getName() + ": " + file.getName());

        return dumpImageFile(new ByteSourceFile(file));
    }

    public final String dumpImageFile(ByteSource byteSource)
            throws ImageReadException, IOException
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        dumpImageFile(pw, byteSource);

        pw.flush();

        return sw.toString();
    }

    /**
     * @throws ImageReadException  may be thrown by sub-classes
     * @throws IOException may be thrown by sub-classes
     */
    public boolean dumpImageFile(PrintWriter pw, ByteSource byteSource)
            throws ImageReadException, IOException
    {
        return false;
    }

    public abstract boolean embedICCProfile(File src, File dst, byte profile[]);

    public abstract String getName();

    public abstract String getDefaultExtension();

    protected abstract String[] getAcceptedExtensions();

    protected abstract ImageFormat[] getAcceptedTypes();

    public boolean canAcceptType(ImageFormat type)
    {
        ImageFormat types[] = getAcceptedTypes();

        for (int i = 0; i < types.length; i++)
            if (types[i].equals(type))
                return true;
        return false;
    }

    protected final boolean canAcceptExtension(File file)
    {
        return canAcceptExtension(file.getName());
    }

    protected final boolean canAcceptExtension(String filename)
    {
        String exts[] = getAcceptedExtensions();
        if (exts == null)
            return true;

        int index = filename.lastIndexOf('.');
        if (index >= 0)
        {
            String ext = filename.substring(index);
            ext = ext.toLowerCase();

            for (int i = 0; i < exts.length; i++)
                if (exts[i].toLowerCase().equals(ext))
                    return true;
        }
        return false;
    }

    protected IBufferedImageFactory getBufferedImageFactory(Map params)
    {
        if (params == null)
            return new SimpleBufferedImageFactory();

        IBufferedImageFactory result = (IBufferedImageFactory) params
                .get(SanselanConstants.BUFFERED_IMAGE_FACTORY);

        if (null != result)
            return result;

        return new SimpleBufferedImageFactory();
    }

    public static final boolean isStrict(Map params)
    {
        if (params == null || !params.containsKey(PARAM_KEY_STRICT))
            return false;
        return ((Boolean) params.get(PARAM_KEY_STRICT)).booleanValue();
    }
}


text:
package org.optaplanner.examples.flp.persistence;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.examples.common.persistence.AbstractTxtSolutionImporter;
import org.optaplanner.examples.flp.domain.FlpLocation;
import org.optaplanner.examples.flp.domain.FlpSolution;
import org.optaplanner.examples.flp.domain.Store;
import org.optaplanner.examples.flp.domain.Warehouse;

public class FlpImporter extends AbstractTxtSolutionImporter {

    private static final String INPUT_FILE_SUFFIX = "txt";

    public FlpImporter() {
        super(true);
    }

    @Override
    public String getInputFileSuffix() {
        return INPUT_FILE_SUFFIX;
    }

    public TxtInputBuilder createTxtInputBuilder() {
        return new FlpInputBuilder();
    }

    public static class FlpInputBuilder extends TxtInputBuilder {

        private FlpSolution solution;

        private int warehousesListSize;
        private int storesListSize;

        public FlpSolution readSolution() throws IOException {
            solution = new FlpSolution();
            solution.setId(0L);
            readHeaders();
            readWarehouseList();
            readStoreList();

            // TODO Calculate the search space size
            logger.info("FacultyPlacerSolution {} has {} warehouses and {} stores with a search space of TODO.",
                    getInputId(),
                    solution.getWarehouseList().size(),
                    solution.getStoreList().size());
            return solution;
        }

        private void readHeaders() throws IOException {
            readConstantLine("\\#.*");
            readConstantLine("\\#.*");
            String[] headerTokens = splitBySpace(bufferedReader.readLine(), 2);
            warehousesListSize = Integer.valueOf(headerTokens[0]);
            storesListSize = Integer.valueOf(headerTokens[1]);
        }

        private void readWarehouseList() throws IOException {
            readConstantLine("\\#.*");
            List<Warehouse> warehouseList = new ArrayList<Warehouse>(warehousesListSize);
            long id = 0L;
            for (int i = 0; i < warehousesListSize; i++) {
                String[] lineTokens = splitBySpace(bufferedReader.readLine(), 4);
                Warehouse warehouse = new Warehouse();
                warehouse.setId(id);
                id++;
                warehouse.setLocation(new FlpLocation(Double.valueOf(lineTokens[3]), Double.valueOf(lineTokens[2])));
                // Avoid doubles by multiplying all numbers by 10000
                warehouse.setSetupCost((long) (Double.valueOf(lineTokens[0]) * 10000.0));
                warehouse.setCapacity(Integer.valueOf(lineTokens[1]));
                warehouseList.add(warehouse);
            }
            solution.setWarehouseList(warehouseList);
        }

        private void readStoreList() throws IOException {
            readConstantLine("\\#.*");
            List<Store> storeList = new ArrayList<Store>(storesListSize);
            long id = 0L;
            for (int i = 0; i < storesListSize; i++) {
                String[] lineTokens = splitBySpace(bufferedReader.readLine(), 3);
                Store store = new Store();
                store.setId(id);
                id++;
                store.setLocation(new FlpLocation(Double.valueOf(lineTokens[2]), Double.valueOf(lineTokens[1])));
                store.setDemand(Integer.valueOf(lineTokens[0]));
                storeList.add(store);
            }
            solution.setStoreList(storeList);
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This is a basic func test for a Common application.
 */
YUI({
    useConsoleOutput: true,
    useBrowserConsole: true,
    logInclude: { TestRunner: true }
}).use('node', 'node-event-simulate', 'test', 'console', function (Y) {

    var suite = new Y.Test.Suite("Common: getparamsbyvaluesimpleclient");

    suite.add(new Y.Test.Case({
        "test getparamsbyvaluesimpleclient": function() {
            Y.Assert.areEqual('Input Parameters Testing', Y.one('#iptitle').get('innerHTML').match(/Input Parameters Testing/gi));
            Y.Assert.areEqual('GET Parameters', Y.one('#gptitle').get('innerHTML').match(/GET Parameters/gi));
            Y.Assert.areEqual('Params by key', Y.one('#desc').get('innerHTML').match(/Params by key/gi));
            Y.Assert.areEqual('Does the \"foo\" param exist\?', Y.one('#question').get('innerHTML').match(/Does the \"foo\" param exist\?/gi));
            Y.Assert.areEqual('YES', Y.one('#answer').get('innerHTML').match(/YES/gi));
        }

    }));

    Y.Test.Runner.add(suite);
});


text:
"""composeexample URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('data_regist/', include('data_regist.urls')),
    path('admin/', admin.site.urls),
]


text:
clear all;
close all;

setflagDS = 0;
plotImage = 1; %plot image for display and save the image in .png format
saveImage = 1; %save image result in .mat format

disp('Added paths....');
%add the paths of subfolders of the software
addpaths();
%set the parameters for running registration process
disp('Setting parameters...');
param = setparameters_prepost();

%open the txt file to enter dice similarity values for each iteration
if(setflagDS ==1)
    output_file='Dice_similarity.txt';
    fid_out = fopen(output_file,'w');
    fprintf(fid_out, 'Level Iteration Background  CSF  GrayMatter  WhiteMatter  Fat  Muscle Muscle/Skin  Skull  vessels  AroundFat  DuraMatter  BoneMarrow\r\n');
end

output_file1 ='output_file_prepost.txt';
fid_out1 = fopen(output_file1,'w');
%tolerance value for stopping criterion in the iteration loop (delta)
tol = 1e-04;
%maximum number of iterations for each refinement level
itermax = 50;
%% 1: Read image data
%Enter file name here
disp('Reading image data...');
filenameI0='PreOp.img';
filenameI1='PostOp.img';

[I1,I2] = read3DImage_prepost(filenameI0,filenameI1);
I1_in = I1; %store initial moving image
I2_in = I2; %store initial target image

%Image size
sizeImage = size(I1);

%compute initial RS value
disp('Compute initial RS...');
Idiff = I1-I2;
Idiff2 = (Idiff).^2;
residual_initial = sqrt(sum(sum(sum(Idiff2,3),2),1));
MSD_initial = sum(sum(sum(Idiff2,3),2),1)/size(I1,1)/size(I1,2)/size(I1,3);
fprintf(fid_out1,'initial residual = %f\r\n',residual_initial);
RS_initial = 1;
fprintf('initial residual %f\n',residual_initial);
fprintf('initial MSD %f\n',MSD_initial);
fprintf('initial RS value %f\n',RS_initial);

%Store the pixel coordinates
disp('Storing pixel coordinates...');
[pixX, pixY, pixZ]= ndgrid(linspace(1,size(I1,1),size(I1,1)),linspace(1,size(I1,2),size(I1,2)),linspace(1,size(I1,3),size(I1,3)));
X = pixX(:);
Y = pixY(:);
Z = pixZ(:);
pix = [X,Y,Z];

%Initialize the parametric space
disp('Store the knotvectors...');
[CP, knotvectorU, knotvectorV, knotvectorW] = storeKnotArray(param,sizeImage);

%% Compute Elem, Basis, Control point data structure for THBS splines
disp('Set B-spline grid...');

tic
[Dm,Em] = setBsplineGrid_func_withoutNode(knotvectorU,knotvectorV,knotvectorW,param);
toc

%% Store level 1 control points
disp('Compute control points at level 1 using Greville abscissae...');
knotu = knotvectorU{1,1};
knotv = knotvectorV{1,1};
knotw = knotvectorW{1,1};

pp = zeros(param.nobU(1,1)*param.nobV(1,1)*param.nobW(1,1),3);
for k = 1:param.nobW(1,1)
    for j =1:param.nobV(1,1)
        for i = 1:param.nobU(1,1)
            index =(k-1)*param.nobV(1,1)*param.nobU(1,1) + (j-1)*param.nobU(1,1) + i;
            %Greville Abscissae
            coordx = sum(knotu(i+1:i+param.pU))./param.pU;
            coordy = sum(knotv(j+1:j+param.pV))./param.pV;
            coordz = sum(knotw(k+1:k+param.pW))./param.pW;
            pp(index,:) = [coordx,coordy,coordz];
        end
    end
end

%Control points stored for each refienement level
CP(1).pts = pp;
Pm = CP;
Pm_old = Pm;

iterct = 0;
rs = zeros(1000,1);
iterations = zeros(1000,1);

%Loop over each refinement level
disp('Loop over each refinement level...');
for multilev = 0:1:param.maxlevel-1
    [DI1X,DI1Y,DI1Z] = gradient(I1);
    Pm = Pm_old; %Reinitialization of the control points done here

    tic
    fprintf('Refinement at level %i...\n',multilev+1);
    if(multilev>0)
        [Em,Dm,Pm] = THB_Refinement(Em,Dm,Pm,knotvectorU, knotvectorV,knotvectorW,bf,CellGrad,meanGrad,param,multilev);
    end
    toc

    disp('Collecting active elements, control points and basis functions...');
    tic
    [ac, bf, ACP, RHS,Em,Dm] = storeActiveElem(Em,Dm,Pm,multilev);
    ac_ct = size(ac,1);
    bf_ct = size(bf,1);
    fprintf(fid_out1,'active elements = %d, active DOF =  %d at level = %d \r\n',ac_ct,bf_ct,multilev+1);
    toc
    %store undeformed control points
    Pm_old = Pm;

    disp('Computing the non-zeros spline over each active element and storing coefficient matrices...');
    tic
    [Jm, Coeff] = computeNonZeroSplines(ac, param, Em, Dm);
    toc

    disp('Computing the basis functions at pixel coordinates...');
    tic
    numPixels = int64(prod(sizeImage));
    [Pixel, Pix2] = storePixelPhi_mex(numPixels, multilev,pix, knotvectorU, knotvectorV, knotvectorW, Em, Coeff, param);
    for p_ind = 1:numPixels
        %Pixel(p_ind).active_cell=Pix1(p_ind);
        %Pix{p_ind,2} = single(Pix{p_ind,2});
        Pixel(p_ind).phi = Pix2{p_ind};
    end
    clear Pix2
    toc;

    tic;
    disp('Computing the basis functions at gaussian points...');
    %compute the gaussian points and weights of the given gauss order
    [Gu,Wu] = ggquad(param.orderGauss);
    [Gv,Wv] = ggquad(param.orderGauss);
    [Gw,Ww] = ggquad(param.orderGauss);

    [PHI,PHIU,PHIV,PHIW,BIGX,BIGY,BIGZ,H] = GaussPhi_mex(ac,Em,knotvectorU,knotvectorV,knotvectorW,Coeff,param);
    % interpolate the intensity values of the target image at the gauss
    % points stored in BIGX, BIGY, BIGZ
    cII2 = interp3(pixY, pixX, pixZ, I2, BIGY, BIGX, BIGZ,'*spline');
    clear('BIGX','BIGY','BIGZ');
    toc;

    %% Start the image registration for each iteration
    disp('Starting the iteration loop for dynamic update of control points...');

    %store the initial RHS value in RHS_init
    RHS_init = RHS;

    % start the iteration loop
    %% Update the iteration loop here

    % Gauss order
    orderGauss = param.orderGauss;

    % lambda 1,2 : regularization parameters
    lambda_1 = param.lambda_1;
    lambda_2 = param.lambda_2;

    % gamma term in g(x)
    smallNumber = param.smallNumber;

    % timestep for each refinement level
    timestep = param.timestep(multilev+1);

    % convert the cell array to struct array
    PHI1 = cell2struct(PHI,'mat',2);
    PHIU1 = cell2struct(PHIU,'mat',2);
    PHIV1 = cell2struct(PHIV,'mat',2);
    PHIW1 = cell2struct(PHIW,'mat',2);

    iterct_level = 0;
    RS_final = 2;

    % while the stopping criterion is satisfied
    while (abs(RS_final-RS_initial)>tol && iterct_level < itermax)

        tic

        % counting total iterations
        iterct = iterct +1;

        % iterations for each refinement level
        iterct_level = iterct_level+1;

        RS_initial = RS_final;
        RHS = RHS_init;

        % compute the spatial transformation function f(x), f_u(x), f_v(x), f_w(x)
        [BIGXX,BIGYY,BIGZZ,BIGMUX,BIGMUY,BIGMUZ,BIGMVX,BIGMVY,BIGMVZ,BIGMWX,BIGMWY,BIGMWZ] = computenewPoints_mex(Jm,ACP,PHI1,PHIU1,PHIV1,PHIW1,orderGauss);

        % interpolate the intensity and grdient at f(x) at the deformed positions of the gauss points
        % cII1:   I1(f(x))
        % cDII1X: I1_x(f(x))
        % cDII1Y: I1_y(f(x))
        % cDII1Z: I1_z(f(x))
        cII1 = interp3(pixY, pixX, pixZ, I1, BIGYY, BIGXX, BIGZZ,'*spline');
        cDII1X = interp3(pixY, pixX, pixZ, DI1X,BIGYY, BIGXX, BIGZZ,'*spline');
        cDII1Y = interp3(pixY, pixX, pixZ, DI1Y, BIGYY, BIGXX, BIGZZ,'*spline');
        cDII1Z = interp3(pixY, pixX, pixZ, DI1Z, BIGYY, BIGXX, BIGZZ,'*spline');
        clear('BIGXX','BIGYY','BIGZZ');

        % denominator of the fidelity term (g(x))
        denominate = sqrt((cDII1X.^2) + (cDII1Y.^2) + (cDII1Z.^2)+ smallNumber); %g(x)

        % fidelity term in x, y, z directions
        Bterm1 = (cII1 - cII2).*2.*cDII1Y./denominate;
        Bterm2 = (cII1 - cII2).*2.*cDII1X./denominate;
        Bterm3 = (cII1 - cII2).*2.*cDII1Z./denominate;

        % Now compute the integrals for each basis function in the support of the active cell.
        RHS= compute_Integ_Domain_mex(Jm,Bterm1,Bterm2,Bterm3,BIGMUX,BIGMUY,BIGMUZ,BIGMVX,BIGMVY,BIGMVZ,BIGMWX,BIGMWY,BIGMWZ,RHS,PHI1,PHIU1,PHIV1,PHIW1,lambda_1,lambda_2, Wu,Wv,Ww,H);

        % apply dirichlet boundary condition on the control points at the
        % boundary
        RHS = bcondition3D(RHS);

        % update the control points P_new = P_old - epsilon*delta(E)
        ACP(:,1:3) = ACP(:,1:3) - timestep.*RHS(:,1:3);

        %compute the new positions of the pixel coordiantes using the spatial
        %transformation function
        [pxx, pyy, pzz] = tripleIterLoop_mex(sizeImage, Pixel, Jm, ACP);

        %Using the new position of the pixels, compute the new moving image
        I1(I1<0) = 0;
        I1(I1>255) = 255;
        I1 = interp3(pixY, pixX, pixZ, I1,pyy,pxx,pzz,'*spline');
        I1 = round(I1);
        Iplot = interp3(pixY, pixX, pixZ, I1,pyy,pxx,pzz);

        %compute the image gradient
        [DI1X,DI1Y,DI1Z] = gradient(I1);

        %compute the residual and RS value
        Idiff2 = I1-I2;
        Idiff22 = (Idiff2).^2;
        Sum1 = sum(sum(sum(Idiff22,3),2),1);
        final_residual = sqrt(Sum1);
        RS_final = final_residual/residual_initial;
        fprintf('RS = %f at Iteration = %d   ',RS_final, iterct_level);
        fprintf(fid_out1,'Iteration = %d, residual = %f, RS = %f\r\n',iterct_level, final_residual, RS_final);
        rs(iterct,1) = RS_final;
        iterations(iterct,1) = iterct;

        %compute Dice similarity
        if(setflagDS ==1)
            computeDiceSimilarity(fid_out,iterct,I1,I2);
        end

        % Plot the image and store the image in .png format
        if(plotImage==1 && saveImage == 1)
            PlotImage_prepost(iterct,I1_in,I2_in,Iplot);
        end

        if(RS_final>RS_initial)
            break;
        end
        toc;

    end

    %the centroids of the B-spline grid
    cell_co = zeros(ac_ct,3);
    for i = 1:ac_ct
        cell_id = ac(i,1);
        cell_le = ac(i,2);
        cell_co(i,:) = Em(cell_le).cell_centre(cell_id,:);
    end

    %compute the absolute difference between the pair of images at centroid
    %of elements
    [CellGrad, meanGrad] = computeDiffGradImage(cell_co,I1,I2, pixX, pixY, pixZ);
    fprintf('Mean Gradient = %f\n',meanGrad);
end
figure;
plot(rs,iterations)


text:
namespace OutParser
{
    partial class formOut2xyz
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tbPath = new System.Windows.Forms.TextBox();
            this.btBrowse = new System.Windows.Forms.Button();
            this.tbLog = new System.Windows.Forms.TextBox();
            this.btBuild = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // tbPath
            //
            this.tbPath.AllowDrop = true;
            this.tbPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.tbPath.Location = new System.Drawing.Point(12, 12);
            this.tbPath.Name = "tbPath";
            this.tbPath.Size = new System.Drawing.Size(481, 20);
            this.tbPath.TabIndex = 7;
            this.tbPath.Text = "c:\\1000-D\\hus\\dersler\\Tez\\_Cu_2012.04.04\\Cu\\100\\big\\PBC-1K+\\";
            //
            // btBrowse
            //
            this.btBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btBrowse.Location = new System.Drawing.Point(499, 11);
            this.btBrowse.Name = "btBrowse";
            this.btBrowse.Size = new System.Drawing.Size(75, 23);
            this.btBrowse.TabIndex = 8;
            this.btBrowse.Text = "Browse";
            this.btBrowse.UseVisualStyleBackColor = true;
            this.btBrowse.Click += new System.EventHandler(this.button1_Click);
            //
            // tbLog
            //
            this.tbLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.tbLog.BackColor = System.Drawing.Color.White;
            this.tbLog.Location = new System.Drawing.Point(12, 38);
            this.tbLog.Multiline = true;
            this.tbLog.Name = "tbLog";
            this.tbLog.ReadOnly = true;
            this.tbLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.tbLog.Size = new System.Drawing.Size(481, 311);
            this.tbLog.TabIndex = 9;
            this.tbLog.WordWrap = false;
            //
            // btBuild
            //
            this.btBuild.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btBuild.Location = new System.Drawing.Point(499, 326);
            this.btBuild.Name = "btBuild";
            this.btBuild.Size = new System.Drawing.Size(75, 23);
            this.btBuild.TabIndex = 10;
            this.btBuild.Text = "Generate XYZ";
            this.btBuild.UseVisualStyleBackColor = true;
            this.btBuild.Click += new System.EventHandler(this.btBuild_Click);
            //
            // formOut2xyz
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(584, 361);
            this.Controls.Add(this.btBuild);
            this.Controls.Add(this.tbLog);
            this.Controls.Add(this.btBrowse);
            this.Controls.Add(this.tbPath);
            this.Name = "formOut2xyz";
            this.Text = "formOut2xyz";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox tbPath;
        private System.Windows.Forms.Button btBrowse;
        private System.Windows.Forms.TextBox tbLog;
        private System.Windows.Forms.Button btBuild;
    }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AuthModule } from './auth/auth.module';
import { DashboardModule } from './dashboard/dashboard.module';
import { LayoutModule } from './layout/layout.module';
import { SubjectModule } from './subject/subject.module';
import { TeacherModule } from './teacher/teacher.module';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    LayoutModule,
    AuthModule,
    DashboardModule,
    SubjectModule,
    TeacherModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
<?php

namespace Bundles\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Recipe
 */
class Recipe
{
    const IMAGE_BASEPATH = 'img/uploads/recipe/';
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $title;

    /**
     * @var string
     */
    private $slug;

    /**
     * @var string
     */
    private $image;

    private $imageFile;

    /**
     * @var string
     */
    private $content;

    /**
     * @var boolean
     */
    private $is_active;

    private $category;

    private $features;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Recipe
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Recipe
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Recipe
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

        /**
     * Set imageFile
     *
     * @param string $image
     * @return Recipe
     */
    public function setImageFile($image)
    {
        $this->imageFile = $image;

        return $this;
    }

    /**
     * Get imageFile
     *
     * @return string
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }
    /**
     * Set content
     *
     * @param string $content
     * @return Recipe
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set is_active
     *
     * @param boolean $isActive
     * @return Recipe
     */
    public function setIsActive($isActive)
    {
        $this->is_active = $isActive;

        return $this;
    }

    /**
     * Get is_active
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->is_active;
    }

    function __toString()
    {
        return $this->title?$this->title:'New';
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->features = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set category
     *
     * @param \Bundles\StoreBundle\Entity\Category $category
     * @return Recipe
     */
    public function setCategory(\Bundles\StoreBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \Bundles\StoreBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Add features
     *
     * @param \Bundles\StoreBundle\Entity\Feature $features
     * @return Recipe
     */
    public function addFeature(\Bundles\StoreBundle\Entity\Feature $features)
    {
        $this->features[] = $features;

        return $this;
    }

    /**
     * Remove features
     *
     * @param \Bundles\StoreBundle\Entity\Feature $features
     */
    public function removeFeature(\Bundles\StoreBundle\Entity\Feature $features)
    {
        $this->features->removeElement($features);
    }

    /**
     * Get features
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getFeatures()
    {
        return $this->features;
    }
}


text:
using namespace std;
extern const double Fuse_coeffs_Xing[];
extern const double Fuse_coefs_NRL[];
// ----- Bosch & Hale coeffs ---
//extern const double BH_B_G; //defined elsewhere
extern const double BH_A[];
extern const double BH_B[];
//-------------------------------------
double Xsec_Fusion(double& Energy); // Energy in in Joules, and energy is collision energy
double Xsec_Fusion_NRL(double& Energy);
double Xsec_Fusion_BH(double E);
#endif
#endif
#endif
#endif
#endif


text:
# Jenkins backup script

[![Build Status](https://github.com/sue445/jenkins-backup-script/workflows/test/badge.svg?branch=master)](https://github.com/sue445/jenkins-backup-script/actions?query=workflow%3Atest)

Archive Jenkins settings and plugins

* `$JENKINS_HOME/*.xml`
* `$JENKINS_HOME/jobs/*/*.xml`
* `$JENKINS_HOME/nodes/*`
* `$JENKINS_HOME/plugins/*.jpi`
* `$JENKINS_HOME/secrets/*`
* `$JENKINS_HOME/users/*`

# Usage
```sh
./jenkins-backup.sh /path/to/jenkins_home archive.tar.gz

# add timestamp suffix
./jenkins-backup.sh /path/to/jenkins_home backup_`date +"%Y%m%d%H%M%S"`.tar.gz
```

# run with Jenkins Job
## 1. install Exclusive Execution Plugin
https://wiki.jenkins-ci.org/display/JENKINS/Exclusive+Execution+Plugin

## 2. New Job
![img](http://cdn-ak.f.st-hatena.com/images/fotolife/s/sue445/20131208/20131208001948.png)

## 3. Configure
### Source Code Management > Repository URL
```
https://github.com/sue445/jenkins-backup-script.git
```

* **Recommended** : specify Branch Specifier with latest release tag
* Check https://github.com/sue445/jenkins-backup-script/releases

![0.0.3](http://f.st-hatena.com/images/fotolife/s/sue445/20140331/20140331010645.png)

### Build Triggers > Build periodically
![img](http://cdn-ak.f.st-hatena.com/images/fotolife/s/sue445/20131110/20131110180825.png)

### Build Environment > Set exclusive Execution
![img](http://cdn-ak.f.st-hatena.com/images/fotolife/s/sue445/20131110/20131110194540.png)

### Build > Execute shell
![img](http://cdn-ak.f.st-hatena.com/images/fotolife/s/sue445/20131110/20131110193935.png)

ex.

```bash
./jenkins-backup.sh $JENKINS_HOME /path/to/backup_`date +"%Y%m%d%H%M%S"`.tar.gz
```

# Operability confirmed
* Debian wheezy
* Debian jessie
* Debian stretch
* Debian buster
* CentOS 6
* CentOS 7

## Testing
requirements [Docker](https://www.docker.com/)

```sh
bundle install

bundle exec itamae docker --node-yaml=spec/node.yml spec/recipes/bootstrap.rb --image=centos:7 --tag local:latest
DOCKER_IMAGE=local:latest bundle exec rspec
```

# Tips
## rotate backup files
```bash
# keep backup with latest 30 days
find /path/to/backup_* -mtime +30 -delete
```

## Restore commands
example

```bash
sudo /etc/init.d/jenkins stop
cd /path/to/backup_dir
tar xzvf backup.tar.gz
sudo cp -R jenkins-backup/* /path/to/jenkins/
sudo chown jenkins:jenkins -R /path/to/jenkins/
sudo /etc/init.d/jenkins start
```

# Changelog
[CHANGELOG.md](CHANGELOG.md)


text:
[![Build Status](https://travis-ci.org/jalkoby/tt.svg?branch=master)](https://travis-ci.org/jalkoby/tt)
[![Gem Version](https://badge.fury.io/rb/t_t.svg)](https://badge.fury.io/rb/t_t)

Dos-T introduces a translation convention for a ruby web application (with a focus on the rails flow). The library is based on the next ideas:
- focus on a every day issues
- reduce amount of duplications inside translation files
- easy to use from day one & minimum to write (nobody likes to write a long and obvious method names)
- have a clear defaults

## Usage

Dos-T adds an extra helper method `tt` into your controllers, mailers & views. The best way to explain all features
is to look at [Cheatsheet](./cheatsheet.md). The below is shown a brief overview:

```Haml
# en:
#   actions:
#     base:
#       add: "Add a new %{r}"
#   attributes:
#     user:
#       name: "Name"
#       email: "Email"
#       role: "Role"
#   common:
#     actions: "Actions"
#     confirm: "Are you sure?"
#     edit: "Edit"
#     delete: "Delete"
#   enums:
#     user:
#       role:
#         a: "Admin"
#         g: "Guest"
#         m: "Manager"
#   models:
#     user:
#       one: "User"
#       other: "Users"

# app/views/users/index.haml
%h2= tt.rs :user

%table
  %thead
    %th= tt.attr :name
    %th= tt.attr :email
    %th= tt.attr :role
    %th= tt.c :actions

  %tbody
    - @users.each do |user|
      %tr
        %td= user.name
        %td= user.email
        %td= tt.enum :role, user.role
        %td
          = link_to tt.c(:edit), edit_user_path(user)
          = link_to tt.c(:delete), user_path(user), method: :delete, confirm: tt.c(:confirm)

= link_to tt.a(:add), new_user_path
```

The result will be the next:
```Haml
%h2 Users

%table
  %thead
    %th Name
    %th Email
    %th Role
    %th Actions

  %tbody
    - @users.each do |user|
      %tr
        %td= user.name
        %td= user.email
        %td= { 'a' => 'Admin', 'g' => 'Guest', 'm' => 'Manager' }[user.role]
        %td
          = link_to 'Edit', edit_user_path(user)
          = link_to 'Delete', user_path(user), method: :delete, confirm: 'Are you sure?'

= link_to 'Add a new user', new_user_path
```

## Additional features

#### [The action factory](./docs/action_factory.md)

#### [Synchronisation of a translation files](./docs/synchronisation.md)

## Setup

Just add `gem "t_t"` into your Gemfile and run `bundle`.

## Requirements

Dos-T is tested against Ruby 1.9.3+ & JRuby(1.9+ compatible). If your application uses Ruby on Rails the framework version should be 3.2+

## Changelog
- 1.3.1
  - Add csv export in tt:m task
- 1.3.0
  - Allow specify a custom mark for locale file synchonization
- 1.2.2
  - Fix rails 5 integration
- 1.2.0
  - Deprecate TT::Translator in favour of TT::Base & TT::Rails
  - Introduce a real-time watcher for [translation file synchronisation](./docs/synchronisation.md)
- 1.1.0:
  - Added [the action factory](./docs/action_factory.md)
  - Improve #attr, #r, #rs methods to make them more compatible with ActiveModel methods
  - Fix a documentation mismatching
- 1.0.1
  - fix the activerecord integration


text:
// Copyright 2011 Marty Dill
// See License.txt for details

using System;
using Mirror.Framework;
using NUnit.Framework;

namespace Mirror.Tests
{
    [TestFixture]
    class MirrorCountTest
    {
        class test
        {
        }

        interface ITest
        {
            void DoStuff();
            void DoStuff(int i);
            void DoStuff(test t, string s);
        }

        [Test]
        public void TestCountThrowsExceptionIfLambdaIsNull()
        {
            var mock = new Mirror<ITest>();
            Assert.Throws<ArgumentNullException>(() => mock.Count(null));
        }

        [Test]
        public void TestCountReturnsCorrectValueForNoParameterMethod()
        {
            var mock = new Mirror<ITest>();
            mock.It.DoStuff();
            mock.It.DoStuff();
            mock.It.DoStuff();

            Assert.AreEqual(3, mock.Count(s => s.DoStuff()));
        }

        [Test]
        public void TestCountReturnsCorrectValueForSingleParameterMethod()
        {
            var mock = new Mirror<ITest>();
            mock.It.DoStuff(1);
            mock.It.DoStuff(2);
            mock.It.DoStuff(1);

            Assert.AreEqual(2, mock.Count(s => s.DoStuff(1)));
        }

        [Test]
        public void TestCountReturnsCorrectValuesForMultiParameterMethod()
        {
            var t = new test();
            var mock = new Mirror<ITest>();
            mock.It.DoStuff(t, "a");
            mock.It.DoStuff(t, "b");
            mock.It.DoStuff(null, "a");
            mock.It.DoStuff(t, "a");
            mock.It.DoStuff(null, "a");

            Assert.AreEqual(2, mock.Count(s => s.DoStuff(t, "a")));
            Assert.AreEqual(1, mock.Count(s => s.DoStuff(t, "b")));
            Assert.AreEqual(2, mock.Count(s => s.DoStuff(null, "a")));
        }

        [Test]
        public void TestCountReturnsCorrectValuesForAnyParameterMethod()
        {
            var mock = new Mirror<ITest>();

            mock.It.DoStuff(1);
            mock.It.DoStuff(2);
            mock.It.DoStuff(1);

            Assert.AreEqual(3, mock.Count(s => s.DoStuff(Any<int>.Value)));
            Assert.AreEqual(2, mock.Count(s => s.DoStuff(1)));
        }

        [Test]
        public void TestCountReturnsCorrectValuesForMultipleAnyParameterMethod()
        {
            var mock = new Mirror<ITest>();
            var test = new test();

            mock.It.DoStuff(null, "a");
            mock.It.DoStuff(null, "a");
            mock.It.DoStuff(null, "b");
            mock.It.DoStuff(new test(), "c");
            mock.It.DoStuff(test, "c");
            mock.It.DoStuff(test, "a");

            Assert.AreEqual(6, mock.Count(s => s.DoStuff(Any<test>.Value, Any<string>.Value)));
            Assert.AreEqual(3, mock.Count(s => s.DoStuff(null, Any<string>.Value)));
            Assert.AreEqual(2, mock.Count(s => s.DoStuff(Any<test>.Value, "c")));
            Assert.AreEqual(2, mock.Count(s => s.DoStuff(test, Any<string>.Value)));

        }
    }
}


text:
/*
 * joystick.h
 *
 *  Created on: 4 Oct 2017
 *      Author: nick
 */

#ifndef JOYSTICK_H_
#define JOYSTICK_H_

typedef enum {
	JoystickDirectionNone,
	JoystickDirectionCenter,
	JoystickDirectionN,
	JoystickDirectionNE,
	JoystickDirectionE,
	JoystickDirectionSE,
	JoystickDirectionS,
	JoystickDirectionSW,
	JoystickDirectionW,
	JoystickDirectionNW,
} JoystickDirection;

#endif /* JOYSTICK_H_ */


text:
:: This script creates a symlink to the game binaries to account for different installation directories on different systems.

@echo off
set /p path="Please enter the folder location of your SpaceEngineersDedicated.exe: "
cd %~dp0
mklink /J GameBinaries "%path%"
if errorlevel 1 goto Error
echo Done! You can now open the Torch solution without issue.
goto End
:Error
echo An error occured creating the symlink.
:End
pause


text:
package com.example.myfirstapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Queue;

import android.os.Handler;

/**
 * TCP Receiver Worker to handle established incoming connections.
 * @author Shung-Hsi Yu <syu07@nyit.edu> ID#0906172
 * @version Apr 11, 2014
 */
public class TcpReceiverWorker implements Runnable {
    private Socket sender;
    private final Queue<String> uiMessageQueue;
    private Handler mHandler;

    /**
     * Constructor for TcpReceiverWorker class.
     * @param sender the socket object that is connect to the sender
     * @param uiMessageQueue Queue which will take the received messages
     */
    public TcpReceiverWorker(Socket sender, Queue<String> uiMessageQueue, Handler mHandler) {
        this.mHandler = mHandler;
    	this.sender = sender;
        this.uiMessageQueue = uiMessageQueue;
    }

    /**
     * Default method called by thread objects.
     */
    @Override
    public void run() {
        try {
        	BufferedReader in = new BufferedReader(
        			new InputStreamReader(
        					sender.getInputStream()));
            String message = getWholeMessage(in);
            showMessage(sender.getInetAddress(), message);
            in.close();
        } catch (IOException e) {
            // TODO write error recovery code
            System.out.println(":: Can't retrieve message");
            e.printStackTrace();
        }
    }

    /**
     * Retrieve the whole message, rather than retrieving a line.
     * @param in BufferedReader instance to read from
     * @return the message in the specified BufferedReader instance
     * @throws IOException
     */
    private String getWholeMessage(BufferedReader in) throws IOException {
        StringBuilder sb = new StringBuilder();
        String input = in.readLine();
        while (input != null) {
            sb.append(input);
            sb.append(String.format("%n"));
            input = in.readLine();
        }
        return sb.toString();
    }

    /**
     * Display the retrieved message according to the implementation. This
     * implementation simple add the message to a queue.
     * @param senderIp IP adress of the sender
     * @param message the message to display
     */
    private void showMessage(InetAddress senderIp, String message) {
        uiMessageQueue.add(senderIp.getHostAddress() + ": " + message);
        mHandler.sendEmptyMessage(0);
    }

}


text:
using namespace Field3D;

#include "field3D_Tools.h"

class Field3dCacheFormat : public MPxCacheFormat
{
public:

	Field3dCacheFormat(
			Field3DTools::FieldTypeEnum type           = Field3DTools::DENSE ,
			Field3DTools::FieldDataTypeEnum data_type  = Field3DTools::FLOAT
	);
	~Field3dCacheFormat();

	MString	extension() { return "f3d"; } ;

	// specific creator : D = Dense , S = Sparse, F = float , H = half
	static void    *DHCreator()  { return new Field3dCacheFormat(Field3DTools::DENSE  , Field3DTools::HALF)  ; };
	static void    *DFCreator()  { return new Field3dCacheFormat(Field3DTools::DENSE  , Field3DTools::FLOAT) ; };
	static void    *SHCreator()  { return new Field3dCacheFormat(Field3DTools::SPARSE , Field3DTools::HALF)  ; };
	static void    *SFCreator()  { return new Field3dCacheFormat(Field3DTools::SPARSE , Field3DTools::FLOAT) ; };

	// general functions inherited from MPxCacheFormat
	MStatus open    ( const MString& fileName, FileAccessMode mode);
	void    close   ();
	MStatus isValid ();

	// write functions inherited from MPxCacheFormat
	MStatus writeHeader      ( const MString& version, MTime& startTime, MTime& endTime);
	MStatus writeFloatArray  ( const MFloatArray&   );
	MStatus writeDoubleArray ( const MDoubleArray&  );
	MStatus writeChannelName ( const MString & name );
	MStatus writeTime        ( MTime& time);
	void    beginWriteChunk  () {};
	void    endWriteChunk    () {};

	// read functions inherited from MPxCacheFormat
	MStatus  readFloatArray  ( MFloatArray&  , unsigned size );
	MStatus  readDoubleArray ( MDoubleArray& , unsigned size );
	MStatus  findChannelName ( const MString & name);
	MStatus  readChannelName ( MString& name);
	unsigned readArraySize   ();
	MStatus  readHeader      ();
	MStatus  beginReadChunk  () {return MStatus::kSuccess;};
	void     endReadChunk    () {};

	// timeline
	MStatus  readTime        ( MTime& time);
	MStatus  findTime        ( MTime& time, MTime& foundTime);
	MStatus  readNextTime    ( MTime& foundTime);
	MStatus  rewind();

private:

	template< class T >  // T is MFloatArray or MDoubleArray
	MStatus writeArray(T  &array);

	template< class T >  // T is MFloatArray or MDoubleArray
	MStatus readArray(T &array, unsigned arraySize);

	Field3DInputFile   *m_inFile  ;
	Field3DOutputFile  *m_outFile ;

	std::string  m_filename      ;
	bool         m_isFileOpened  ;
	MString      m_currentName   ;
	bool         m_ReadNameStack ;
	float        m_offset[3]     ;

	// export Type
	Field3DTools::FieldTypeEnum     FIELD_TYPE       ;
	Field3DTools::FieldDataTypeEnum FIELD_DATA_TYPE  ;

};

#endif


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. fl. 23:126. 1928

#### Original name
null

### Remarks
null


text:
header {
  background-color: ActiveCaption;
}
header #username span {
  padding-left: 8%;
}
/*# sourceMappingURL=header.css.map */


text:
import React from 'react';

export default class LinkNode extends React.Component{
  static get nodeType(){
    return 'link';
  }

  constructor(props){
    super(props);
  }

  render(){
    const { data } = this.props.node;
    const href = data.get('href');
    return (
      <a {...this.props.attributes} href={href}>
        {this.props.children}
      </a>
    );
  }
}


text:
<?php
class ControllerApiReward extends Controller {
	public function index() {
		$this->load->language('api/reward');

		// Delete past reward in case there is an error
		unset($this->session->data['reward']);

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$points = $this->customer->getRewardPoints();

			$points_total = 0;

			foreach ($this->cart->getProducts() as $product) {
				if ($product['points']) {
					$points_total += $product['points'];
				}
			}

			if (empty($this->request->post['reward'])) {
				$json['error'] = $this->language->get('error_reward');
			}

			if ($this->request->post['reward'] > $points) {
				$json['error'] = sprintf($this->language->get('error_points'), $this->request->post['reward']);
			}

			if ($this->request->post['reward'] > $points_total) {
				$json['error'] = sprintf($this->language->get('error_maximum'), $points_total);
			}

			if (!$json) {
				$this->session->data['reward'] = abs($this->request->post['reward']);

				$this->session->data['success'] = $this->language->get('text_success');
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function maximum() {
		$this->load->language('api/reward');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$json['maximum'] = 0;

			foreach ($this->cart->getProducts() as $product) {
				if ($product['points']) {
					$json['maximum'] += $product['points'];
				}
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function available() {
		$this->load->language('api/reward');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$json['points'] = $this->customer->getRewardPoints();
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}


text:
package ua.com.fielden.platform.sample.domain;

import com.google.inject.Inject;

import ua.com.fielden.platform.dao.CommonEntityDao;
import ua.com.fielden.platform.entity.annotation.EntityType;
import ua.com.fielden.platform.entity.query.IFilter;

/**
 * DAO implementation for companion object {@link ITgWebApiEntitySyntheticSingle}.
 *
 * @author TG Team
 *
 */
@EntityType(TgWebApiEntitySyntheticSingle.class)
public class TgWebApiEntitySyntheticSingleDao extends CommonEntityDao<TgWebApiEntitySyntheticSingle> implements ITgWebApiEntitySyntheticSingle {

    @Inject
    public TgWebApiEntitySyntheticSingleDao(final IFilter filter) {
        super(filter);
    }

}


text:
#import "DOMNode.h"

@interface DOMNode (UIWebFormPeripheral)
- (id)createPeripheral;
@end


text:
class Operation < ActiveRecord::Base
  OPERATION_TYPES = %w(deal_card pass_trump accept_trump pick_trump play_card draw_trump discard_card)
  OPERATION_NAMES = OPERATION_TYPES.map(&:to_s)

  belongs_to :player
  composed_of :card, mapping: [ %w(suit suit), %w(rank rank) ], allow_nil: true

  validates :operation_type, null: false, inclusion: { in: OPERATION_NAMES }
  validate :suit_and_rank_are_mutually_existing
  validate :suit_is_null_or_valid
  validate :rank_is_null_or_allowed_in_euchre

  OPERATION_TYPES.each do |type|
    scope type, -> { where(operation_type: type) }

    define_method("#{type}?") do
      operation_type == type
    end
  end

  def symbol
    operation_type.to_sym
  end

  def card
    if suit && rank
      Card.new(suit, rank)
    else
      raise 'the operation does not have an associated card'
    end
  end

  private

  def suit_and_rank_are_mutually_existing
    if suit.nil? != rank.nil?
      errors.add(:suit, "an operation must set both 'suit' and 'rank' or neither")
    end
  end

  def suit_is_null_or_valid
    if suit
      is_valid = Card::SUIT_NAMES.include?(suit)

      if !is_valid
        errors.add(:suit, "suit must be one of '#{Card::SUIT_NAMES.join(', ')}'")
      end
    end
  end

  def rank_is_null_or_allowed_in_euchre
    if rank
      is_valid = rank == Card::ACE || Card::EUCHRE_CARD_RANGE.include?(rank)

      if !is_valid
        errors.add(:rank, "card rank must be 1 or between 9 and 13 (inclusive)")
      end
    end
  end
end


text:
<?php

/**
 * @file
 * Contains \Drupal\pathauto\PathautoGenerator.
 */

namespace Drupal\pathauto;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Utility\Token;
use Drupal\token\TokenEntityMapperInterface;

/**
 * Provides methods for generating path aliases.
 */
class PathautoGenerator implements PathautoGeneratorInterface {

  use StringTranslationTrait;

  /**
   * Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * Calculated pattern for a specific entity.
   *
   * @var array
   */
  protected $patterns = array();

  /**
   * Available patterns per entity type ID.
   *
   * @var array
   */
  protected $patternsByEntityType = array();

  /**
   * The alias cleaner.
   *
   * @var \Drupal\pathauto\AliasCleanerInterface
   */
  protected $aliasCleaner;

  /**
   * The alias storage helper.
   *
   * @var \Drupal\pathauto\AliasStorageHelperInterface
   */
  protected $aliasStorageHelper;

  /**
   * The alias uniquifier.
   *
   * @var \Drupal\pathauto\AliasUniquifierInterface
   */
  protected $aliasUniquifier;

  /**
   * The messenger service.
   *
   * @var \Drupal\pathauto\MessengerInterface
   */
  protected $messenger;

  /**
   * @var \Drupal\token\TokenEntityMapperInterface
   */
  protected $tokenEntityMapper;

  /**
   * Creates a new Pathauto manager.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Utility\Token $token
   *   The token utility.
   * @param \Drupal\pathauto\AliasCleanerInterface $alias_cleaner
   *   The alias cleaner.
   * @param \Drupal\pathauto\AliasStorageHelperInterface $alias_storage_helper
   *   The alias storage helper.
   * @param AliasUniquifierInterface $alias_uniquifier
   *   The alias uniquifier.
   * @param MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, Token $token, AliasCleanerInterface $alias_cleaner, AliasStorageHelperInterface $alias_storage_helper, AliasUniquifierInterface $alias_uniquifier, MessengerInterface $messenger, TranslationInterface $string_translation, TokenEntityMapperInterface $token_entity_mappper) {
    $this->configFactory = $config_factory;
    $this->moduleHandler = $module_handler;
    $this->token = $token;
    $this->aliasCleaner = $alias_cleaner;
    $this->aliasStorageHelper = $alias_storage_helper;
    $this->aliasUniquifier = $alias_uniquifier;
    $this->messenger = $messenger;
    $this->stringTranslation = $string_translation;
    $this->tokenEntityMapper = $token_entity_mappper;
  }

  /**
   * {@inheritdoc}
   */
  public function createEntityAlias(EntityInterface $entity, $op) {
    // Retrieve and apply the pattern for this content type.
    $pattern = $this->getPatternByEntity($entity);
    if (empty($pattern)) {
      // No pattern? Do nothing (otherwise we may blow away existing aliases...)
      return NULL;
    }

    $source = '/' . $entity->toUrl()->getInternalPath();
    $config = $this->configFactory->get('pathauto.settings');
    $langcode = $entity->language()->getId();

    // Core does not handle aliases with language Not Applicable.
    if ($langcode == LanguageInterface::LANGCODE_NOT_APPLICABLE) {
      $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
    }

    // Build token data.
    $data = [
      $this->tokenEntityMapper->getTokenTypeForEntityType($entity->getEntityTypeId()) => $entity,
    ];

    // Allow other modules to alter the pattern.
    $context = array(
      'module' => $entity->getEntityType()->getProvider(),
      'op' => $op,
      'source' => $source,
      'data' => $data,
      'bundle' => $entity->bundle(),
      'language' => &$langcode,
    );
    // @todo Is still hook still useful?
    $this->moduleHandler->alter('pathauto_pattern', $pattern, $context);

    // Special handling when updating an item which is already aliased.
    $existing_alias = NULL;
    if ($op == 'update' || $op == 'bulkupdate') {
      if ($existing_alias = $this->aliasStorageHelper->loadBySource($source, $langcode)) {
        switch ($config->get('update_action')) {
          case PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW:
            // If an alias already exists,
            // and the update action is set to do nothing,
            // then gosh-darn it, do nothing.
            return NULL;
        }
      }
    }

    // Replace any tokens in the pattern.
    // Uses callback option to clean replacements. No sanitization.
    // Pass empty BubbleableMetadata object to explicitly ignore cacheablity,
    // as the result is never rendered.
    $alias = $this->token->replace($pattern->getPattern(), $data, array(
      'clear' => TRUE,
      'callback' => array($this->aliasCleaner, 'cleanTokenValues'),
      'langcode' => $langcode,
      'pathauto' => TRUE,
    ), new BubbleableMetadata());

    // Check if the token replacement has not actually replaced any values. If
    // that is the case, then stop because we should not generate an alias.
    // @see token_scan()
    $pattern_tokens_removed = preg_replace('/\[[^\s\]:]*:[^\s\]]*\]/', '', $pattern->getPattern());
    if ($alias === $pattern_tokens_removed) {
      return NULL;
    }

    $alias = $this->aliasCleaner->cleanAlias($alias);

    // Allow other modules to alter the alias.
    $context['source'] = &$source;
    $context['pattern'] = $pattern;
    $this->moduleHandler->alter('pathauto_alias', $alias, $context);

    // If we have arrived at an empty string, discontinue.
    if (!Unicode::strlen($alias)) {
      return NULL;
    }

    // If the alias already exists, generate a new, hopefully unique, variant.
    $original_alias = $alias;
    $this->aliasUniquifier->uniquify($alias, $source, $langcode);
    if ($original_alias != $alias) {
      // Alert the user why this happened.
      $this->messenger->addMessage($this->t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', array(
        '%original_alias' => $original_alias,
        '%alias' => $alias,
      )), $op);
    }

    // Return the generated alias if requested.
    if ($op == 'return') {
      return $alias;
    }

    // Build the new path alias array and send it off to be created.
    $path = array(
      'source' => $source,
      'alias' => $alias,
      'language' => $langcode,
    );

    return $this->aliasStorageHelper->save($path, $existing_alias, $op);
  }

  /**
   * Loads pathauto patterns for a given entity type ID
   *
   * @param string $entity_type_id
   *   An entity type ID.
   *
   * @return \Drupal\pathauto\PathautoPatternInterface[]
   *   A list of patterns, sorted by weight.
   */
  protected function getPatternByEntityType($entity_type_id) {
    if (!isset($this->patternsByEntityType[$entity_type_id])) {
      $ids = \Drupal::entityQuery('pathauto_pattern')
        ->condition('type', array_keys(\Drupal::service('plugin.manager.alias_type')
          ->getPluginDefinitionByType($this->tokenEntityMapper->getTokenTypeForEntityType($entity_type_id))))
        ->sort('weight')
        ->execute();

      $this->patternsByEntityType[$entity_type_id] = \Drupal::entityTypeManager()
        ->getStorage('pathauto_pattern')
        ->loadMultiple($ids);
    }

    return $this->patternsByEntityType[$entity_type_id];
  }

  /**
   * {@inheritdoc}
   */
  public function getPatternByEntity(EntityInterface $entity) {
    $langcode = $entity->language()->getId();
    if (!isset($this->patterns[$entity->getEntityTypeId()][$entity->id()][$langcode])) {
      foreach ($this->getPatternByEntityType($entity->getEntityTypeId()) as $pattern) {
        if ($pattern->applies($entity)) {
          $this->patterns[$entity->getEntityTypeId()][$entity->id()][$langcode] = $pattern;
          break;
        }
      }
      // If still not set.
      if (!isset($this->patterns[$entity->getEntityTypeId()][$entity->id()][$langcode])) {
        $this->patterns[$entity->getEntityTypeId()][$entity->id()][$langcode] = NULL;
      }
    }
    return $this->patterns[$entity->getEntityTypeId()][$entity->id()][$langcode];
  }

  /**
   * {@inheritdoc}
   */
  public function resetCaches() {
    $this->patterns = [];
    $this->patternsByEntityType = [];
    $this->aliasCleaner->resetCaches();
  }

  /**
   * {@inheritdoc}
   */
  public function updateEntityAlias(EntityInterface $entity, $op, array $options = array()) {
    // Skip if the entity does not have the path field.
    if (!($entity instanceof ContentEntityInterface) || !$entity->hasField('path')) {
      return NULL;
    }

    // Skip if pathauto processing is disabled.
    if ($entity->path->pathauto != PathautoState::CREATE && empty($options['force'])) {
      return NULL;
    }

    $options += array('language' => $entity->language()->getId());
    $type = $entity->getEntityTypeId();

    // Skip processing if the entity has no pattern.
    if (!$this->getPatternByEntity($entity)) {
      return NULL;
    }

    // Deal with taxonomy specific logic.
    // @todo Update and test forum related code.
    if ($type == 'taxonomy_term') {

      $config_forum = $this->configFactory->get('forum.settings');
      if ($entity->getVocabularyId() == $config_forum->get('vocabulary')) {
        $type = 'forum';
      }
    }

    $result = $this->createEntityAlias($entity, $op);

    // @todo Move this to a method on the pattern plugin.
    if ($type == 'taxonomy_term') {
      foreach ($this->loadTermChildren($entity->id()) as $subterm) {
        $this->updateEntityAlias($subterm, $op, $options);
      }
    }

    return $result;
  }

  /**
   * Finds all children of a term ID.
   *
   * @param int $tid
   *   Term ID to retrieve parents for.
   *
   * @return \Drupal\taxonomy\TermInterface[]
   *   An array of term objects that are the children of the term $tid.
   */
  protected function loadTermChildren($tid) {
    return \Drupal::entityManager()->getStorage('taxonomy_term')->loadChildren($tid);
  }

}


text:
@interface TKTableViewController ()

@end

@implementation TKTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableView];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.edges.offset(0);

    }];

    [self tk_addRefreshComponent];
}

- (void)loadPropertysAtInitialization
{
    [super loadPropertysAtInitialization];

    self.currentPage = 1;

    self.tableView = ({

        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.backgroundColor = UIColor.whiteColor;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        tableView.showsVerticalScrollIndicator = false;
        tableView.showsHorizontalScrollIndicator = false;

        tableView;
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UITableViewCell new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark - 上拉下拉刷新
#pragma mark - 刷新

/// 添加刷新组件
- (void)tk_addRefreshComponent
{
    [self installAllRefresh];
}

-(void)installHeaderRefresh
{
    if (!self.tableView.mj_header && self.headerRefreshEnable) {

        self.tableView.mj_header = self.refreshHeader;

    }
}

-(void)installFooterRefresh
{
    if (!self.tableView.mj_footer && self.footerRefreshEnable) {

        self.tableView.mj_footer = self.refreshFooter;
    }
}

-(void)installAllRefresh
{
    [self installHeaderRefresh];
    [self installFooterRefresh];
}

-(void)unstallHeaderRefresh
{
    if (self.tableView.mj_header) {

        self.tableView.mj_header = nil;
        [self.tableView.mj_header removeFromSuperview];
    }
}

-(void)unstallFooterRefresh
{
    if (self.tableView.mj_footer) {

        self.tableView.mj_footer = nil;
        [self.tableView.mj_footer removeFromSuperview];
    }
}

-(void)unstallAllRefresh
{
    [self unstallHeaderRefresh];
    [self unstallFooterRefresh];
}

- (BOOL)headerRefreshEnable
{
    return false;
}

- (BOOL)footerRefreshEnable
{
    return false;
}

- (Class)classForRefreshHeader
{
    return [MJRefreshNormalHeader class];
}

- (Class)classForRefreshFooter
{
    return [MJRefreshBackStateFooter class];
}

- (void)headerRefreshBeginHandler
{

}

- (void)footerRefreshBeginHandler
{

}

- (void)endHeaderRefreshing
{
    if (self.tableView.mj_header && self.tableView.mj_header.isRefreshing) {

        [self.refreshHeader endRefreshing];
    }
}

- (void)endFooterRefreshing
{
    if (self.tableView.mj_footer && self.tableView.mj_footer.isRefreshing) {

        [self.refreshFooter endRefreshing];
    }
}

-(TKRefreshGifHeader *)refreshHeader
{
    if (!_refreshHeader) {

        __weak typeof(self) weakSelf = self;

        //初始化
        _refreshHeader = [TKRefreshGifHeader headerWithRefreshingBlock:^{

            [weakSelf headerRefreshBeginHandler];

        }];

        _refreshHeader.lastUpdatedTimeLabel.hidden = true;
        _refreshHeader.stateLabel.hidden = true;

    }
    return _refreshHeader;
}

-(MJRefreshBackStateFooter *)refreshFooter
{
    if (!_refreshFooter) {

        __weak typeof(self) weakSelf = self;

        _refreshFooter = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{

            [weakSelf footerRefreshBeginHandler];

        }];

        _refreshFooter.stateLabel.font = [UIFont systemFontOfSize:12];
        _refreshFooter.stateLabel.textColor = TKColorFromRGB(0xB9B9B9);
        [_refreshFooter setTitle:self.titleForFooterRefreshWithNoMoreData forState:MJRefreshStateNoMoreData];
    }

    return _refreshFooter;
}

-(NSString *)titleForFooterRefreshWithNoMoreData
{
    if (!_titleForFooterRefreshWithNoMoreData) {

        return @"-----更多内容,敬请期待-----";
    }

    return _titleForFooterRefreshWithNoMoreData;
}

@end


text:
Every December my friends do a "Secret Santa" - the traditional gift exchange
where everybody is randomly assigned to give a gift to a friend. To make
things exciting, the matching is all random (you cannot pick your gift
recipient) and nobody knows who got assigned to who until the day when the
gifts are exchanged - hence, the "secret" in the name.

Since we're a big group with many couples and families, often a husband gets
his wife as secret santa (or vice-versa), or a father is assigned to one of
his children. This creates a series of issues:

* If you have a younger kid and he/she is assigned to you, you might end up
paying for your own gift and ruining the surprise.
* When your significant other asks "who did you get for Secret Santa", you
have to lie, hide gifts, etc.
* The inevitable "this game is rigged!" commentary on the day of revelation.

To fix this, you must design a program that randomly assigns the Secret Santa
gift exchange, but *prevents people from the same family to be assigned to
each other*.

# Input

A list of all Secret Santa participants. People who belong to the same family
are listed in the same line separated by spaces. Thus, "Jeff Jerry" represents
two people, Jeff and Jerry, who are family and should not be assigned to
eachother.

    Joe
    Jeff Jerry
    Johnson

# Output

The list of Secret Santa assignments. As Secret Santa is a random assignment,
output may vary.

    Joe -> Jeff
    Johnson -> Jerry
    Jerry -> Joe
    Jeff -> Johnson

But **not** `Jeff -> Jerry` or `Jerry -> Jeff`!

# Challenge Input

    Sean
    Winnie
    Brian Amy
    Samir
    Joe Bethany
    Bruno Anna Matthew Lucas
    Gabriel Martha Philip
    Andre
    Danielle
    Leo Cinthia
    Paula
    Mary Jane
    Anderson
    Priscilla
    Regis Julianna Arthur
    Mark Marina
    Alex Andrea

# Bonus

The assignment list must avoid "closed loops" where smaller subgroups get
assigned to each other, breaking the overall loop.

    Joe -> Jeff
    Jeff -> Joe # Closed loop of 2
    Jerry -> Johnson
    Johnson -> Jerry # Closed loop of 2

# Challenge Credit

Thanks to /u/oprimo for his idea in /r/dailyprogrammer_ideas


text: <!DOCTYPE html>


text:
module OntapStorageSystemHelper
  include_concern 'TextualSummary'
end


text:
<?php

require_once dirname(__FILE__).'/include/config.inc.php';

$page['title'] = _('Other configuration parameters');
$page['file'] = 'adm.other.php';
$page['hist_arg'] = array();

require_once dirname(__FILE__).'/include/page_header.php';

// VAR	TYPE	OPTIONAL	FLAGS	VALIDATION	EXCEPTION
$fields = array(
	'refresh_unsupported' => array(T_ZBX_INT, O_NO,	null, BETWEEN(0, 65535), 'isset({update})',
		_('Refresh unsupported items (in sec)')),
	'alert_usrgrpid' =>			array(T_ZBX_INT, O_NO,	null,		DB_ID,				'isset({update})'),
	'discovery_groupid' =>		array(T_ZBX_INT, O_NO,	null,		DB_ID,				'isset({update})'),
	'snmptrap_logging' =>		array(T_ZBX_INT, O_OPT,	null,		IN('1'),			null),
	// actions
	'update' =>					array(T_ZBX_STR, O_OPT,	P_SYS|P_ACT, null,				null),
	'form_refresh' =>			array(T_ZBX_INT, O_OPT,	null,		null,				null)
);
check_fields($fields);

/*
 * Actions
 */
if (hasRequest('update')) {
	DBstart();

	$orig_config = select_config(false);

	$configs = array(
		'refresh_unsupported' => getRequest('refresh_unsupported'),
		'alert_usrgrpid' => getRequest('alert_usrgrpid'),
		'discovery_groupid' => getRequest('discovery_groupid'),
		'snmptrap_logging' => getRequest('snmptrap_logging') ? 1 : 0
	);
	$result = update_config($configs);

	if ($result) {
		$audit = array(
			_s('Refresh unsupported items (in sec) "%1$s".', getRequest('refresh_unsupported'))
		);

		if (hasRequest('discovery_groupid')) {
			$hostGroup = API::HostGroup()->get(array(
				'groupids' => getRequest('discovery_groupid'),
				'editable' => true,
				'output' => array('groupid', 'name')
			));
			if ($hostGroup) {
				$hostGroup = reset($hostGroup);

				$audit[] = _s('Group for discovered hosts "%1$s".', $hostGroup['name']);

				if (bccomp($hostGroup['groupid'], $orig_config['discovery_groupid']) != 0) {
					setHostGroupInternal($orig_config['discovery_groupid'], ZBX_NOT_INTERNAL_GROUP);
					setHostGroupInternal($hostGroup['groupid'], ZBX_INTERNAL_GROUP);
				}
			}
		}

		if (hasRequest('alert_usrgrpid')) {
			$userGroupId = getRequest('alert_usrgrpid');

			if ($userGroupId) {
				$userGroupName = DBfetch(DBselect('SELECT u.name FROM usrgrp u WHERE u.usrgrpid='.zbx_dbstr($userGroupId)));
				$userGroupName = reset($userGroupName);
			}
			else {
				$userGroupName = _('None');
			}

			$audit[] = _s('User group for database down message "%1$s".', $userGroupName);
		}

		add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_ZABBIX_CONFIG, implode('; ', $audit));
	}

	$result = DBend($result);
	show_messages($result, _('Configuration updated'), _('Cannot update configuration'));
}

/*
 * Display
 */
$form = new CForm();
$form->cleanItems();
$cmbConf = new CComboBox('configDropDown', 'adm.other.php', 'redirect(this.options[this.selectedIndex].value);');
$cmbConf->addItems(array(
	'adm.gui.php' => _('GUI'),
	'adm.housekeeper.php' => _('Housekeeping'),
	'adm.images.php' => _('Images'),
	'adm.iconmapping.php' => _('Icon mapping'),
	'adm.regexps.php' => _('Regular expressions'),
	'adm.macros.php' => _('Macros'),
	'adm.valuemapping.php' => _('Value mapping'),
	'adm.workingtime.php' => _('Working time'),
	'adm.triggerseverities.php' => _('Trigger severities'),
	'adm.triggerdisplayoptions.php' => _('Trigger displaying options'),
	'adm.other.php' => _('Other')
));
$form->addItem($cmbConf);

$cnf_wdgt = new CWidget();
$cnf_wdgt->addPageHeader(_('OTHER CONFIGURATION PARAMETERS'), $form);

$data = array();

if (hasRequest('form_refresh')) {
	$data['config']['discovery_groupid'] = getRequest('discovery_groupid');
	$data['config']['alert_usrgrpid'] = getRequest('alert_usrgrpid');
	$data['config']['refresh_unsupported'] = getRequest('refresh_unsupported');
	$data['config']['snmptrap_logging'] = getRequest('snmptrap_logging');
}
else {
	$data['config'] = select_config(false);
}

$data['discovery_groups'] = API::HostGroup()->get(array(
	'output' => array('usrgrpid', 'name'),
	'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL),
	'editable' => true
));
order_result($data['discovery_groups'], 'name');

$data['alert_usrgrps'] = DBfetchArray(DBselect(
	'SELECT u.usrgrpid,u.name FROM usrgrp u'
));

order_result($data['alert_usrgrps'], 'name');

$otherForm = new CView('administration.general.other.edit', $data);
$cnf_wdgt->addItem($otherForm->render());
$cnf_wdgt->show();

require_once dirname(__FILE__).'/include/page_footer.php';


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Mass.cs" company="PropertyTools">
//   Copyright (c) 2014 PropertyTools contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataGridDemo
{
    using System;
    using System.Text.RegularExpressions;

    public struct Mass : IComparable<Mass>, IComparable
    {
        public static Mass Kilogram = new Mass(1);
        public static Mass Gram = new Mass(1e-3);
        public static Mass Tonne = new Mass(1000);
        public static Mass Pound = new Mass(0.45359237);

        private static readonly Regex ParseExpression = new Regex(@"^\s*(?<value>[\d\.\,]+)*\s*(?<unit>.*)\s*$");

        private readonly double value;

        public Mass(double value)
        {
            this.value = value;
        }

        public override string ToString()
        {
            return this.value + " kg";
        }

        public int CompareTo(Mass that)
        {
            return this.value.CompareTo(that.value);
        }

        public int CompareTo(object obj)
        {
            if (obj is Mass)
            {
                return this.CompareTo((Mass)obj);
            }

            throw new ArgumentException("Object is not of type Mass");
        }

        public static Mass operator +(Mass x, Mass y)
        {
            return new Mass(x.value + y.value);
        }

        public static Mass operator -(Mass x, Mass y)
        {
            return new Mass(x.value - y.value);
        }

        public static Mass operator *(double x, Mass y)
        {
            return new Mass(x * y.value);
        }

        public static Mass operator *(Mass x, double y)
        {
            return new Mass(x.value * y);
        }

        public static Mass operator /(Mass x, double y)
        {
            return new Mass(x.value / y);
        }

        public static Mass Parse(string s, IFormatProvider formatProvider)
        {
            var m = ParseExpression.Match(s);
            if (!m.Success)
            {
                throw new FormatException();
            }

            var value = double.Parse(m.Groups["value"].Value, formatProvider);
            var unit = m.Groups["unit"].Value;
            switch (unit)
            {
                case "tonne":
                case "t":
                    return value * Tonne;
                case "lb":
                    return value * Pound;
                case "g":
                    return value * Gram;
                case "kg":
                case "":
                    return value * Kilogram;
                default:
                    throw new FormatException();
            }
        }
    }
}


text:
layout: text/textblock
---

When important content has a deadline that is not necessarily fixed, both content managers and requesters need to:
- negotiate an appropriate deadline
- prioritise the work
- allocate appropriate resources

Let requesters know why you need notice of timeframes for announcements or initiatives. Help them understand your process.

### [2]Senior communications / content lead / publisher questions
- Does there need to be a related news story, blog or social media strategy?
- Does this content already exist, on this website or another channel?
- Does the content impact existing content that will need to be updated or removed?
- Do you have inaccessible PDFs? If so, make them accessible and provide an extract and contact details.
- For high profile content that is of poor quality, discuss a way to resolve before publishing.


text:
namespace content {
class ContentBrowserClient;
class ContentClient;
class ContentRendererClient;
}

namespace extensions {

class ShellMainDelegate : public content::ContentMainDelegate {
 public:
  ShellMainDelegate();
  ~ShellMainDelegate() override;

  // ContentMainDelegate implementation:
  bool BasicStartupComplete(int* exit_code) override;
  void PreSandboxStartup() override;
  content::ContentClient* CreateContentClient() override;
  content::ContentBrowserClient* CreateContentBrowserClient() override;
  content::ContentRendererClient* CreateContentRendererClient() override;
  void ProcessExiting(const std::string& process_type) override;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
  void ZygoteStarting(
      std::vector<std::unique_ptr<service_manager::ZygoteForkDelegate>>*
          delegates) override;
#endif
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
  void ZygoteForked() override;
#endif
#if defined(OS_MACOSX)
  void PreCreateMainMessageLoop() override;
#endif

 private:
  // |process_type| is zygote, renderer, utility, etc. Returns true if the
  // process needs data from resources.pak.
  static bool ProcessNeedsResourceBundle(const std::string& process_type);

  std::unique_ptr<content::ContentClient> content_client_;
  std::unique_ptr<content::ContentBrowserClient> browser_client_;
  std::unique_ptr<content::ContentRendererClient> renderer_client_;

  DISALLOW_COPY_AND_ASSIGN(ShellMainDelegate);
};

}  // namespace extensions

#endif  // EXTENSIONS_SHELL_APP_SHELL_MAIN_DELEGATE_H_


text:
package helloscala.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;

@FunctionalInterface
public interface ConnectionPreparedStatementCreator {
    PreparedStatement apply(Connection conn);
}


text:
@implementation TYMasterTools {

}
+ (NSUInteger)getImageSizeFromImage:(UIImage *)image {
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    return [imgData length];
}

+ (NSUInteger)getImageSizeFromPath:(NSString *)imagePath {
    return [TYMasterTools getImageSizeFromImage:[UIImage imageNamed:imagePath]];
}
@end


text:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using SourceCode.Clay;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace SourceCode.Chasm.IO.AzureBlob
{
    partial class AzureBlobChasmRepo // .CommitRef
    {
        #region Fields

        private const string CommitExtension = ".commit";

        #endregion

        #region List

        public override async ValueTask<IReadOnlyList<CommitRef>> GetBranchesAsync(string name, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

            var refsContainer = _refsContainer.Value;
            var results = new List<CommitRef>();
            name = DeriveCommitRefBlobName(name, null);

            BlobContinuationToken token = null;

            do
            {
                var resultSegment = await refsContainer.ListBlobsSegmentedAsync(name, false, BlobListingDetails.None, null, token, null, null).ConfigureAwait(false);

                foreach (var blobItem in resultSegment.Results)
                {
                    if (!(blobItem is CloudBlob blob))
                        continue;

                    if (!blob.Name.EndsWith(CommitExtension, StringComparison.OrdinalIgnoreCase))
                        continue;

                    var branch = blob.Name.Substring(name.Length, blob.Name.Length - CommitExtension.Length - name.Length);
                    branch = Uri.UnescapeDataString(branch);

                    using (var output = new MemoryStream())
                    {
                        await blob.DownloadToStreamAsync(output, default, default, default, cancellationToken).ConfigureAwait(false);

                        if (output.Length < Sha1.ByteLen)
                            throw new SerializationException($"{nameof(CommitRef)} '{name}/{branch}' expected to have byte length {Sha1.ByteLen} but has length {output.Length}");

                        var commitId = Serializer.DeserializeCommitId(output.ToArray());
                        results.Add(new CommitRef(branch, commitId));
                    }
                }

                token = resultSegment.ContinuationToken;
            } while (token != null);

            return results;
        }

        public override async ValueTask<IReadOnlyList<string>> GetNamesAsync(CancellationToken cancellationToken)
        {
            var refsContainer = _refsContainer.Value;
            var results = new List<string>();

            BlobContinuationToken token = null;

            do
            {
                var resultSegment = await refsContainer.ListBlobsSegmentedAsync("", false, BlobListingDetails.None, null, token, null, null).ConfigureAwait(false);

                foreach (var blobItem in resultSegment.Results)
                {
                    if (!(blobItem is CloudBlobDirectory dir))
                        continue;

                    var name = dir.Prefix.Substring(0, dir.Prefix.Length - 1); // Ends with / always.
                    name = Uri.UnescapeDataString(name);
                    results.Add(name);
                }

                token = resultSegment.ContinuationToken;
            } while (token != null);

            return results;
        }

        #endregion

        #region Read

        public override async ValueTask<CommitRef?> ReadCommitRefAsync(string name, string branch, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
            if (string.IsNullOrWhiteSpace(branch)) throw new ArgumentNullException(nameof(branch));

            var (found, commitId, _, _) = await ReadCommitRefImplAsync(name, branch, cancellationToken).ConfigureAwait(false);

            // NotFound
            if (!found) return null;

            // Found
            var commitRef = new CommitRef(branch, commitId);
            return commitRef;
        }

        #endregion

        #region Write

        public override async Task WriteCommitRefAsync(CommitId? previousCommitId, string name, CommitRef commitRef, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));
            if (commitRef == CommitRef.Empty) throw new ArgumentNullException(nameof(commitRef));

            // Load existing commit ref in order to use its etag
            var (found, existingCommitId, ifMatchCondition, blobRef) = await ReadCommitRefImplAsync(name, commitRef.Branch, cancellationToken).ConfigureAwait(false);

            // Optimistic concurrency check
            if (found)
            {
                // We found a previous commit but the caller didn't say to expect one
                if (!previousCommitId.HasValue)
                    throw BuildConcurrencyException(name, commitRef.Branch, null); // TODO: May need a different error

                // Semantics follow Interlocked.Exchange (compare then exchange)
                if (existingCommitId != previousCommitId.Value)
                {
                    throw BuildConcurrencyException(name, commitRef.Branch, null);
                }

                // Idempotent
                if (existingCommitId == commitRef.CommitId) // We already know that the name matches
                    return;
            }
            // The caller expected a previous commit, but we didn't find one
            else if (previousCommitId.HasValue)
            {
                throw BuildConcurrencyException(name, commitRef.Branch, null); // TODO: May need a different error
            }

            try
            {
                // Required to create blob before appending to it
                await blobRef.CreateOrReplaceAsync(ifMatchCondition, default, default, cancellationToken).ConfigureAwait(false); // Note etag access condition

                // CommitIds are not compressed
                using (var session = Serializer.Serialize(commitRef.CommitId))
                using (var output = new MemoryStream())
                {
                    var seg = session.Result;
                    output.Write(seg.Array, seg.Offset, seg.Count);
                    output.Position = 0;

                    // Append blob. Following seems to be the only safe multi-writer method available
                    // http://stackoverflow.com/questions/32530126/azure-cloudappendblob-errors-with-concurrent-access
                    await blobRef.AppendBlockAsync(output).ConfigureAwait(false);
                }
            }
            catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
            {
                throw BuildConcurrencyException(name, commitRef.Branch, se);
            }
        }

        #endregion

        #region Helpers

        private static string DeriveCommitRefBlobName(string name, string branch)
        {
            if (string.IsNullOrEmpty(branch))
                return Uri.EscapeDataString(name) + "/";

            name = Uri.EscapeDataString(name);
            branch = Uri.EscapeDataString(branch);

            var refName = $"{name}/{branch}.commit";
            return refName;
        }

        private async ValueTask<(bool found, CommitId, AccessCondition, CloudAppendBlob)> ReadCommitRefImplAsync(string name, string branch, CancellationToken cancellationToken)
        {
            // Callers have already validated parameters

            var refsContainer = _refsContainer.Value;
            var blobName = DeriveCommitRefBlobName(name, branch);
            var blobRef = refsContainer.GetAppendBlobReference(blobName);

            try
            {
                using (var output = new MemoryStream())
                {
                    // TODO: Perf: Use a stream instead of a preceding call to fetch the buffer length
                    // Or use blobRef.DownloadToByteArrayAsync() since we already know expected length of data (Sha1.ByteLen)
                    // Keep in mind Azure and/or specific IChasmSerializer may add some overhead: it looks like emperical byte length is 40-52 bytes
                    await blobRef.DownloadToStreamAsync(output, default, default, default, cancellationToken).ConfigureAwait(false);

                    // Grab the etag - we need it for optimistic concurrency control
                    var ifMatchCondition = AccessCondition.GenerateIfMatchCondition(blobRef.Properties.ETag);

                    if (output.Length < Sha1.ByteLen)
                        throw new SerializationException($"{nameof(CommitRef)} '{name}/{branch}' expected to have byte length {Sha1.ByteLen} but has length {output.Length}");

                    // CommitIds are not compressed
                    var commitId = Serializer.DeserializeCommitId(output.ToArray()); // TODO: Perf

                    // Found
                    return (true, commitId, ifMatchCondition, blobRef);
                }
            }
            catch (StorageException se) when (se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
            {
                // Try-catch is cheaper than a separate (latent) exists check
                se.Suppress();
            }

            // NotFound
            return (false, default, default, blobRef);
        }

        #endregion
    }
}


text:
package com.hackfmi.sport.squad.dto;

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

import com.hackfmi.sport.squad.domain.ScheduleInterval;

public class TeamDto implements BaseDto {

	private String id;
	private String city;
    private String name;

    private PlayerDto captainDto;
    private List<ScheduleInterval> schedule = new ArrayList<>();
    private List<String> playersIds = new ArrayList<>();

    private Double rating = 0d;

	@Override
	public String getId() {
		return id;
	}

	@Override
	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

    public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public PlayerDto getCaptainDto() {
		return captainDto;
	}

	public void setCaptainDto(PlayerDto captainDto) {
		this.captainDto = captainDto;
	}

	public List<ScheduleInterval> getSchedule() {
		return schedule;
	}

	public void setSchedule(List<ScheduleInterval> schedule) {
		this.schedule = schedule;
	}

	public List<String> getPlayersIds() {
		return playersIds;
	}

	public void setPlayersIds(List<String> playersIds) {
		this.playersIds = playersIds;
	}

	public Double getRating() {
		return rating;
	}

	public void setRating(Double rating) {
		this.rating = rating;
	}

}