text:
package eu.monnetproject.math.sparse.eigen;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Perform QR Decomposition and Eigenvalue solve on very large matrices.
 * This implementation uses on disk matrices and multi-threading across most operations
 *
 * @author jmccrae
 */
public class QROnDisk {

    public static int NUM_THREADS = 10;

    /**
     * Calculate the QR decomposition. Such that X = QR, Q is orthonormal and R is
     * upper triangular. The result is stored in the Q and R files
     * @param X The matrix (note this is not preserved!)
     * @param Q The buffer to write Q to. This should be initialized
     * @param R The buffer to write R to. This should be initialized
     * @throws IOException
     */
    public static void decompose(DiskMatrix X, DiskMatrix Q, DiskMatrix R) throws IOException {
        final int n = X.n;
        transpose(X);
        double[] rDiag = new double[n];
        for (int minor = 0; minor < n; minor++) {
            performHouseholderReflection(minor, X, rDiag);
        }
        getQT(X, rDiag, Q);
        transpose(Q);
        getR(X, rDiag, R);
    }

    /**
     * Calculate the eigendecomposition of a matrix X.
     * @param X A symmetric matrix to decompose
     * @param eigenvectors A nxn buffer
     * @param Q A nxn buffer
     * @param Q2 A nxn buffer
     * @param R A nxn buffer
     * @return The solution such that the file indicated by Soln.Q is the eigenvector
     * matrix (and is either the 2nd or 4th parameter) and Soln.R is an approximately
     * diagonal matrix with eigenvalues on the diagonal
     * @throws IOException
     */
    public static Soln eigen(DiskMatrix X, DiskMatrix eigenvectors, DiskMatrix Q, DiskMatrix Q2, DiskMatrix R) throws IOException {
        final int n = X.n;
        identity(n, eigenvectors);
        identity(n, Q2);
        while (!converged(X)) {
            decompose(X, Q, R);
            matMult(eigenvectors, Q, Q2);
            DiskMatrix Qt = eigenvectors;
            eigenvectors = Q2;
            Q2 = Qt;
            matMult(R, Q, X);
            X.print();
        }
        return new Soln(eigenvectors, X);
    }

    /**
     * Perform Householder reflection for a minor A(minor, minor) of A.
     *
     * @param minor minor index
     * @param matrix transposed matrix
     * @since 3.2
     */
    protected static void performHouseholderReflection(final int minor, DiskMatrix qrt, double[] rDiag) throws IOException {
        final ThreadPoolExecutor threadPool = makeThreadPool();
        final double[] qrtMinor = qrt.readRow(minor);

        double xNormSqr = 0;
        for (int row = minor; row < qrtMinor.length; row++) {
            final double c = qrtMinor[row];
            xNormSqr += c * c;
        }
        final double a = (qrtMinor[minor] > 0) ? -Math.sqrt(xNormSqr) : Math.sqrt(xNormSqr);
        rDiag[minor] = a;

        if (a != 0.0) {
            qrtMinor[minor] -= a;
            for (int col = minor + 1; col < qrt.n; col++) {
                threadPool.execute(new HouseholderInner(qrt, col, minor, qrtMinor, a));
            }
            barrier(threadPool);
            qrt.writeRow(minor, qrtMinor);
        }
    }

    /**
     * Start a thread pool
     * @return
     */
    private static ThreadPoolExecutor makeThreadPool() {
        final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(NUM_THREADS - 1, NUM_THREADS - 1, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        threadPool.setRejectedExecutionHandler(new Wait());
        return threadPool;
    }

    /**
     * Wait for all threads to terminate
     * @param threadPool
     * @throws RuntimeException
     */
    private static void barrier(ThreadPoolExecutor threadPool) throws RuntimeException {
        threadPool.shutdown();
        try {
            threadPool.awaitTermination(5, TimeUnit.DAYS);
        } catch (InterruptedException x) {
            throw new RuntimeException(x);
        }
    }

    private static class HouseholderInner implements Runnable {

        final DiskMatrix qrt;
        final int col;
        final int minor;
        final double[] qrtMinor;
        final double a;

        public HouseholderInner(final DiskMatrix qrt, final int col, final int minor, final double[] qrtMinor, final double a) {
            this.qrt = qrt;
            this.col = col;
            this.minor = minor;
            this.qrtMinor = qrtMinor;
            this.a = a;
        }

        @Override
        public void run() {
            try {
                final double[] qrtCol = qrt.readRow(col);
                double alpha = 0;
                for (int row = minor; row < qrtCol.length; row++) {
                    alpha -= qrtCol[row] * qrtMinor[row];
                }
                alpha /= a * qrtMinor[minor];

                for (int row = minor; row < qrtCol.length; row++) {
                    qrtCol[row] -= alpha * qrtMinor[row];
                }
                qrt.writeRow(col, qrtCol);
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }
    }

    private static class GetRInner implements Runnable {

        final int n;
        final DiskMatrix qrt;
        final int row;
        final double[] rDiag;
        final DiskMatrix R;

        public GetRInner(int n, DiskMatrix qrt, int row, double[] rDiag, DiskMatrix R) {
            this.n = n;
            this.qrt = qrt;
            this.row = row;
            this.rDiag = rDiag;
            this.R = R;
        }

        @Override
        public void run() {
            try {
                double[] ra_row = new double[n];
                final double[] qrt_row = qrt.readRow(row);
                ra_row[row] = rDiag[row];
                System.arraycopy(qrt_row, row + 1, ra_row, row + 1, n - row - 1);
                R.writeRow(row, ra_row);
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }
    }

    /**
     * Extract R from the QRT matrix
     * @param qrt The QRT matrix
     * @param rDiag The diagonal of R
     * @param R The matrix to write R to
     * @throws IOException
     */
    private static void getR(DiskMatrix qrt, double[] rDiag, DiskMatrix R) throws IOException {
        final int n = qrt.n;
        transpose(qrt);
        final int m = n;
        final ThreadPoolExecutor threadPool = makeThreadPool();
        // copy the diagonal from rDiag and the upper triangle of qr
        for (int row = Math.min(m, n) - 1; row >= 0; row--) {
            threadPool.execute(new GetRInner(n, qrt, row, rDiag, R));
        }
        barrier(threadPool);
    }

    private static class GetQTInner implements Runnable {

        DiskMatrix qta;
        int col;
        int minor;
        final int m;
        final double[] qrtMinor;
        double[] rDiag;

        public GetQTInner(DiskMatrix qta, int col, int minor, int m, double[] qrtMinor, double[] rDiag) {
            this.qta = qta;
            this.col = col;
            this.minor = minor;
            this.m = m;
            this.qrtMinor = qrtMinor;
            this.rDiag = rDiag;
        }

        @Override
        public void run() {
            try {
                final double[] qta_col = qta.readRow(col);
                double alpha = 0;
                for (int row = minor; row < m; row++) {
                    alpha -= qta_col[row] * qrtMinor[row];
                }
                alpha /= rDiag[minor] * qrtMinor[minor];

                for (int row = minor; row < m; row++) {
                    qta_col[row] += -alpha * qrtMinor[row];
                }
                qta.writeRow(col, qta_col);
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }
    }

    /**
     * Get the Q^T matrix from the QR^T matrix
     * @param qrt The QR^T matrix
     * @param rDiag The diagonal of R
     * @param qta The matrix to write to
     * @throws IOException
     */
    private static void getQT(DiskMatrix qrt, double[] rDiag, DiskMatrix qta) throws IOException {
        // QT is supposed to be m x m
        final int n = qrt.n;
        final int m = n;

        qta.clear();

        for (int minor = Math.min(m, n) - 1; minor >= 0; minor--) {
            final ThreadPoolExecutor threadPool = makeThreadPool();
            final double[] qrtMinor = qrt.readRow(minor);
            qta.writeSingle(minor, minor, 1.0);
            if (qrtMinor[minor] != 0.0) {
                for (int col = minor; col < m; col++) {
                    threadPool.execute(new GetQTInner(qta, col, minor, m, qrtMinor, rDiag));
                }
            }
            barrier(threadPool);
        }
    }

    private static class TransposeInner implements Runnable {

        final int i;
        final int BLOCK_SIZE;
        final DiskMatrix q;

        public TransposeInner(final int i, final int BLOCK_SIZE, final DiskMatrix q) {
            this.i = i;
            this.BLOCK_SIZE = BLOCK_SIZE;
            this.q = q;
        }

        @Override
        public void run() {
            try {
                double[][] values = new double[Math.min(i + BLOCK_SIZE, q.n) - i][Math.min(i + BLOCK_SIZE, q.n) - i];
                q.readBlock(i, i, BLOCK_SIZE, values);
                transpose2D(values);
                q.writeBlock(i, i, BLOCK_SIZE, values);
                for (int j = i + BLOCK_SIZE; j < q.n; j += BLOCK_SIZE) {
                    double[][] values1 = new double[Math.min(i + BLOCK_SIZE, q.n) - i][Math.min(j + BLOCK_SIZE, q.n) - j];
                    double[][] values2 = new double[Math.min(j + BLOCK_SIZE, q.n) - j][Math.min(i + BLOCK_SIZE, q.n) - i];
                    q.readBlock(i, j, BLOCK_SIZE, values1);
                    q.readBlock(j, i, BLOCK_SIZE, values2);
                    transpose2D(values1, values2);
                    q.writeBlock(i, j, BLOCK_SIZE, values1);
                    q.writeBlock(j, i, BLOCK_SIZE, values2);
                }
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }
    }

    /**
     * Transpose a matrix using the blocking strategy
     * @param q The matrix to transpose (in place)
     * @throws IOException
     */
    private static void transpose(DiskMatrix q) throws IOException {
        final int BLOCK_SIZE = 1024;
        transpose(q, BLOCK_SIZE);
    }

    /**
     * Transpose a matrix using the blocking strategy
     * @param q The matrix to transpose (in place)
     * @throws IOException
     */
    public static void transpose(DiskMatrix q, int BLOCK_SIZE) throws IOException {
        final ThreadPoolExecutor threadPool = makeThreadPool();
        for (int i = 0; i < q.n; i += BLOCK_SIZE) {
            threadPool.execute(new TransposeInner(i, BLOCK_SIZE, q));
        }
        barrier(threadPool);
    }

    private static void transpose2D(double[][] q) {
        for (int i = 0; i < q.length; i++) {
            for (int j = i + 1; j < q[0].length; j++) {
                double t = q[i][j];
                q[i][j] = q[j][i];
                q[j][i] = t;
            }
        }
    }

    private static void transpose2D(double[][] q, double[][] q2) {
        for (int i = 0; i < q.length; i++) {
            for (int j = 0; j < q2.length; j++) {
                double t = q[i][j];
                q[i][j] = q2[j][i];
                q2[j][i] = t;
            }
        }
    }
    private static final double EPSILON = 1e-6;

    /**
     * True if the matrix is approximately diagonal
     * @param X The matrix
     * @return
     * @throws IOException
     */
    private static boolean converged(DiskMatrix X) throws IOException {
        for (int i = 0; i < X.n; i++) {
            final double[] row = X.readRow(i);
            for (int j = 0; j < X.n; j++) {
                if (i != j && Math.abs(row[j]) > EPSILON) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Initialize a matrix as a nxn identity matrix
     * @param n The size of the matrix
     * @param I The matrix to write to
     * @throws IOException
     */
    private static void identity(int n, DiskMatrix I) throws IOException {
        I.reset();
        for (int i = 0; i < n; i++) {
            byte[] buf = new byte[n * 8];
            final ByteBuffer bb = ByteBuffer.wrap(buf);
            bb.putDouble(i * 8, 1.0);
            I.write(buf);
        }
    }

    private static class MatMultInner implements Runnable {

        DiskMatrix left;
        int i;
        DiskMatrix right;
        DiskMatrix result;

        public MatMultInner(DiskMatrix left, int i, DiskMatrix right, DiskMatrix result) {
            this.left = left;
            this.i = i;
            this.right = right;
            this.result = result;
        }

        @Override
        public void run() {
            try {
                final double[] left_i = left.readRow(i);
                final double[] result_i = new double[left.n];
                for (int j = 0; j < right.n; j++) {
                    final double[] right_j = right.readRow(j);
                    for (int k = 0; k < right.n; k++) {
                        result_i[k] += left_i[j] * right_j[k];
                    }
                }
                result.writeRow(i, result_i);
            } catch (IOException x) {
                throw new RuntimeException(x);
            }
        }
    }

    private static void matMult(DiskMatrix left, DiskMatrix right, DiskMatrix result) throws IOException {
        final ThreadPoolExecutor threadPool = makeThreadPool();
        for (int i = 0; i < left.n; i++) {
            threadPool.execute(new MatMultInner(left, i, right, result));
        }
        barrier(threadPool);
    }

    /**
     * Class for on disk matrices
     */
    public static class DiskMatrix {

        private final RandomAccessFile matrix;
        public final int n;

        /**
         * Create a nxn on disk matrix
         * @param matrix A randomaccessfile opened in "rw" mode
         * @param n The size of the matrix
         */
        public DiskMatrix(RandomAccessFile matrix, int n) {
            this.matrix = matrix;
            this.n = n;
        }

        /**
         * Print to STDOUT (for debugging)
         * @throws IOException
         */
        public void print() throws IOException {
            for (int i = 0; i < n; i++) {
                double[] d = readRow(i);
                for (int j = 0; j < n; j++) {
                    System.out.print(d[j] + " ");
                }
                System.out.println();
            }
        }

        /**
         * Replace this matrix with the nxn zero matrix
         * @throws IOException
         */
        public void clear() throws IOException {
            this.reset();
            for (int i = 0; i < n; i++) {
                byte[] buf = new byte[8 * n];
                this.write(buf);
            }
        }

        /**
         * Create and intialize a nxn zero matrix
         * @param matrix The matrix file
         * @param n The size of the matrix
         * @return The object
         * @throws IOException
         */
        public static DiskMatrix allocate(RandomAccessFile matrix, int n) throws IOException {
            final DiskMatrix m = new DiskMatrix(matrix, n);
            m.clear();
            return m;
        }

        /**
         * Read a row
         * @param i The row to read
         * @return The row as a double array
         * @throws IOException
         */
        public double[] readRow(int i) throws IOException {
            double[] row = new double[n];
            byte[] buf = new byte[n * 8];
            synchronized (this) {
                matrix.seek((long) n * i * 8);
                matrix.readFully(buf);
            }
            final ByteBuffer bb = ByteBuffer.wrap(buf);
            for (int j = 0; j < n; j++) {
                row[j] = bb.getDouble();
            }
            return row;
        }

        /**
         * Write a row
         * @param i The row to write
         * @param row The values to write
         * @throws IOException
         */
        public void writeRow(int i, double[] row) throws IOException {
            byte[] buf = new byte[n * 8];
            final ByteBuffer bb = ByteBuffer.wrap(buf);
            for (int j = 0; j < n; j++) {
                bb.putDouble(row[j]);
            }
            synchronized (this) {
                matrix.seek((long) n * i * 8);
                matrix.write(buf);
            }
        }

        /**
         * Reset the matrix to the beginning (not thread-safe!)
         * @throws IOException
         */
        public void reset() throws IOException {
            matrix.seek(0);
        }

        /**
         * Write directly to underlying file (not thread-safe!)
         * @param buf
         * @throws IOException
         */
        public void write(byte[] buf) throws IOException {
            matrix.write(buf);
        }

        /**
         * Put a single value into the matrix (Avoid for speed reasons)
         * @param i The row index
         * @param j The col index
         * @param value The value
         * @throws IOException
         */
        public void writeSingle(int i, int j, double value) throws IOException {
            byte[] buf = new byte[8];
            ByteBuffer.wrap(buf).putDouble(value);
            synchronized (this) {
                matrix.seek((long) n * i * 8 + j * 8);
                matrix.write(buf);
            }
        }

        /**
         * Read a mxm sub-matrix starting from (i,j). If there are not sufficient
         * then the largest subblock is returned
         * @param i The row index to start the block
         * @param j The col index to start the block
         * @param m The size of the sub-matrix
         * @param values The values to write into should be a matrix of dimension
         * {@code [Math.min(i + m, this.n) - i][Math.min(j + m, this.n) - j]}
         * @throws IOException
         */
        public void readBlock(int i, int j, int m, double[][] values) throws IOException {
            for (int i2 = i; i2 < Math.min(i + m, n); i2++) {
                final int cols = Math.min(j + m, n) - j;
                byte[] buf = new byte[8 * cols];
                synchronized (this) {
                    matrix.seek((long) n * i2 * 8 + j * 8);
                    matrix.readFully(buf);
                }
                final ByteBuffer bb = ByteBuffer.wrap(buf);
                for (int j2 = j; j2 < j + cols; j2++) {
                    values[i2 - i][j2 - j] = bb.getDouble();
                }
            }
        }

        /**
         * Write an mxm sub-matrix to (i,j). If the values matrix is too large overflow may occur!
         * @param i The row index to write to
         * @param j The col index to write to
         * @param m The size of the sub-matrix
         * @param values The values to write. Should be a matrix of dimension
         * {@code [Math.min(i + m, this.n) - i][Math.min(j + m, this.n) - j]}
         * @throws IOException
         */
        public void writeBlock(int i, int j, int m, double[][] values) throws IOException {
            assert(values.length == Math.min(i + m, this.n) - i);
            assert(values[0].length == Math.min(j + m, this.n) - j);
            for (int i2 = 0; i2 < values.length; i2++) {
                byte[] buf = new byte[values[i2].length * 8];
                final ByteBuffer bb = ByteBuffer.wrap(buf);
                for (int j2 = 0; j2 < values[i2].length; j2++) {
                    bb.putDouble(values[i2][j2]);
                }
                synchronized (this) {
                    matrix.seek((long) n * (i + i2) * 8 + j * 8);
                    matrix.write(buf);
                }
            }
        }

        /**
         * Read the diagonal of this matrix
         * @return The diagonal vector
         * @throws IOException
         */
        public double[] diagonal() throws IOException {
            matrix.seek(0);
            double[] diag = new double[n];
            byte[] buf = new byte[8];
            for (int i = 0; i < n; i++) {
                matrix.read(buf);
                diag[i] = ByteBuffer.wrap(buf).getDouble();
                if (i != n - 1) {
                    matrix.skipBytes(8 * n);
                }
            }
            return diag;
        }
    }

    /**
     * A solution to a QR or eigen problem
     */
    public static class Soln {
        /**
         * The Q matrix (for a QR decomposition) or the eigenvector matrix (for eigendecomposition)
         */
        public final DiskMatrix Q;
        /**
         * The R matrix (for a QR decomposition) or the diagonal eigenvalue matrix (for eigendecomposition)
         */
        public final DiskMatrix R;

        public Soln(DiskMatrix Q, DiskMatrix R) {
            this.Q = Q;
            this.R = R;
        }
    }

    /**
     * Wait until a thread pool is free by polling
     */
    private static class Wait implements RejectedExecutionHandler {

        private final HashSet<Runnable> waiting = new HashSet<Runnable>();

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            if (waiting.contains(r)) {
                throw new RejectedExecutionException();
            }
            while (true) {
                waiting.add(r);
                try {
                    synchronized (this) {
                        this.wait(200);
                    }
                } catch (InterruptedException x) {
                }
                try {
                    if (executor.getActiveCount() < executor.getPoolSize()) {
                        executor.submit(r);
                        waiting.remove(r);
                        return;
                    }
                } catch (RejectedExecutionException ree) {
                }
            }
        }
    }
}


text:
layout: post
author: asherman
categories: post
title: Making a Jekyll Site
---

[My Jekyll site](http://ans729.github.io/mysite/)

To set up a new Jekyll site, open a new terminal and type:
```
jeykll new mysite
```
Replacing 'mysite' with whatever you would like to call it.  Then change directories to the new site by typing:
```
cd mysite
```
Add a git repository by typing:
```
git init
git add .
```
Commit and comment on your commit by typing
```
git commit -m "Added my blank Jekyll site"
```
I think I already had .gitignore, so I didn't need to add that, but I did need to change the master branch to gh-pages by typing:

```
git branch -m master gh-pages
```
On Github.com – make a new repository called mysite, then go back to the terminal and add a remote by typing:

```
git remote add origin https://github.com/ans729/mysite
```
Push the commit with:

```
git push origin gh-pages
```

From there, I made changes from github.com and not the terminal.  So to make the site look better by adding the CSS, I followed along with Grant in class and added {{site.baseurl}} in _layouts/default.html to:

```
<!-- syntax highlighting CSS -->
<link rel="stylesheet" href="{{site.baseurl}}/css/syntax.css">

<!-- Custom CSS -->
<link rel="stylesheet" href="{{site.baseurl}}/css/main.css">
```

To edit things like the name, go to _config.yml

![Change Name](http://farm8.staticflickr.com/7347/10476631946_44d991dc1f_o.jpg)

And to edit the github.com and twitter (I don't use twitter, so I put in my google+ instead) go to _layouts/default.html

![Change Links](http://farm4.staticflickr.com/3678/10476631706_f3573253be_o.jpg)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Rhubarb\Leaf\Controls\Common\FileUpload;

use Rhubarb\Leaf\Leaves\Controls\ControlView;
use Rhubarb\Leaf\Leaves\LeafDeploymentPackage;

class SimpleFileUploadView extends ControlView
{
    protected $requiresContainer = false;
    protected $requiresStateInputs = false;

    /**
     * @var SimpleFileUploadModel
     */
    protected $model;

    public $filters = [];

    protected function printViewContent()
    {
        $accepts = "";

        if (sizeof($this->model->acceptFileTypes) > 0) {
            $accepts = " accept=\"" . implode(",", $this->model->acceptFileTypes) . "\"";
        }

        ?>
        <input type="file" name="<?= $this->model->leafPath; ?>" id="<?= $this->model->leafPath; ?>"
               leaf-name="<?= $this->model->leafName ?>"<?= $accepts . $this->model->getHtmlAttributes() . $this->model->getClassAttribute() ?>/>
        <?php
    }

    public function getDeploymentPackage()
    {
        return new LeafDeploymentPackage(__DIR__ . "/SimpleFileUploadViewBridge.js");
    }

    protected function getViewBridgeName()
    {
        return "SimpleFileUploadViewBridge";
    }
}


text:
  Paars est
       un village
       géographiquement positionné dans le département de l'Aisne en Picardie. Elle comptait 252 habitants en 2008.

À proximité de Paars sont localisées les villes de
Vauxtin localisée à 2 km, 51 habitants,
Courcelles-sur-Vesles localisée à 2 km, 321 habitants,
Braine localisée à 4 km, 2 099 habitants,
Ville-Savoye localisée à 4 km, 58 habitants,
Quincy-sous-le-Mont située à 4 km, 64 habitants,
Bazoches-sur-Vesles localisée à 2 km, 440 habitants,
 entre autres. De plus, Paars est située à seulement 20 km de Soissons.

Si vous pensez demenager à Paars, vous pourrez aisément trouver une maison à vendre.

La ville propose quelques  équipements sportifs, elle propose entre autres un terrain de sport.

Le nombre d'habitations, à Paars, se décomposait en 2011 en zero appartements et 122 maisons soit
 un marché relativement équilibré.


text:
package org.elasticsearch.ingest;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.AbstractDiffable;
import org.elasticsearch.cluster.Diff;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ContextParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * Encapsulates a pipeline's id and configuration as a blob
 */
public final class PipelineConfiguration extends AbstractDiffable<PipelineConfiguration> implements ToXContent {

    private static final ObjectParser<Builder, Void> PARSER = new ObjectParser<>("pipeline_config", Builder::new);
    static {
        PARSER.declareString(Builder::setId, new ParseField("id"));
        PARSER.declareField((parser, builder, aVoid) -> {
            XContentBuilder contentBuilder = XContentBuilder.builder(parser.contentType().xContent());
            XContentHelper.copyCurrentStructure(contentBuilder.generator(), parser);
            builder.setConfig(contentBuilder.bytes(), contentBuilder.contentType());
        }, new ParseField("config"), ObjectParser.ValueType.OBJECT);

    }

    public static ContextParser<Void, PipelineConfiguration> getParser() {
        return (parser, context) -> PARSER.apply(parser, null).build();
    }
    private static class Builder {

        private String id;
        private BytesReference config;
        private XContentType xContentType;

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

        void setConfig(BytesReference config, XContentType xContentType) {
            this.config = config;
            this.xContentType = xContentType;
        }

        PipelineConfiguration build() {
            return new PipelineConfiguration(id, config, xContentType);
        }
    }

    private final String id;
    // Store config as bytes reference, because the config is only used when the pipeline store reads the cluster state
    // and the way the map of maps config is read requires a deep copy (it removes instead of gets entries to check for unused options)
    // also the get pipeline api just directly returns this to the caller
    private final BytesReference config;
    private final XContentType xContentType;

    public PipelineConfiguration(String id, BytesReference config, XContentType xContentType) {
        this.id = Objects.requireNonNull(id);
        this.config = Objects.requireNonNull(config);
        this.xContentType = Objects.requireNonNull(xContentType);
    }

    public String getId() {
        return id;
    }

    public Map<String, Object> getConfigAsMap() {
        return XContentHelper.convertToMap(config, true, xContentType).v2();
    }

    // pkg-private for tests
    XContentType getXContentType() {
        return xContentType;
    }

    // pkg-private for tests
    BytesReference getConfig() {
        return config;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field("id", id);
        builder.field("config", getConfigAsMap());
        builder.endObject();
        return builder;
    }

    public static PipelineConfiguration readFrom(StreamInput in) throws IOException {
        if (in.getVersion().onOrAfter(Version.V_5_3_0)) {
            return new PipelineConfiguration(in.readString(), in.readBytesReference(), XContentType.readFrom(in));
        } else {
            final String id = in.readString();
            final BytesReference config = in.readBytesReference();
            return new PipelineConfiguration(id, config, XContentFactory.xContentType(config));
        }
    }

    public static Diff<PipelineConfiguration> readDiffFrom(StreamInput in) throws IOException {
        return readDiffFrom(PipelineConfiguration::readFrom, in);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeString(id);
        out.writeBytesReference(config);
        if (out.getVersion().onOrAfter(Version.V_5_3_0)) {
            xContentType.writeTo(out);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PipelineConfiguration that = (PipelineConfiguration) o;

        if (!id.equals(that.id)) return false;
        return config.equals(that.config);

    }

    @Override
    public int hashCode() {
        int result = id.hashCode();
        result = 31 * result + config.hashCode();
        return result;
    }
}


text:
<?php

namespace Tga\OpenGraphBundle\Renderer;

use Tga\OpenGraphBundle\Document\OpenGraphDocument;
use Tga\OpenGraphBundle\Renderer\Exception\EntityNotSupported;
use Tga\OpenGraphBundle\Registry\Registry;

class OpenGraphMapRenderer
{
    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @param Registry $registry
     */
    public function __construct(Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @param object $entity
     * @return string
     * @throws EntityNotSupported
     */
    public function render($entity)
    {
        $this->registry->freeze();

        foreach ($this->registry->getMaps() as $map) {
            if ($map->supports($entity)) {
                $docuemnt = $this->createDocument();

                $map->map($docuemnt, $entity);

                return $docuemnt->render();
            }
        }

        throw new EntityNotSupported($entity, $this->registry);
    }

    /**
     * @return \Tga\OpenGraphBundle\Registry\Registry
     */
    public function getRegistry()
    {
        return $this->registry;
    }

    /**
     * @return OpenGraphDocument
     */
    protected function createDocument()
    {
        return new OpenGraphDocument();
    }
}


text:
require 'test_helper'

class Test43sHelperTest < ActionView::TestCase
end


text:
package org.innovateuk.ifs.upload.service;

import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.threads.attachment.resource.AttachmentResource;
import org.springframework.core.io.ByteArrayResource;

public interface AttachmentRestService {
    RestResult<AttachmentResource> find(Long fileId);

    RestResult<AttachmentResource> upload(Long contextId, String contentType, long contentLength,
                                          String originalFilename, byte[] bytes);

    RestResult<Void> delete(Long id);

    RestResult<ByteArrayResource> download(Long fileId);
}


text:
<?php

namespace Booking\Service;

use Base\Manager\ConfigManager;
use Base\Manager\OptionManager;
use Base\Service\AbstractService;
use RuntimeException;
use Zend\Json\Json;

class PayPalService extends AbstractService
{

    protected $configManager;
    protected $optionManager;

    protected $access;

    public function __construct(ConfigManager $configManager, OptionManager $optionManager)
    {
        $this->configManager = $configManager;
        $this->optionManager = $optionManager;
    }

    public function setAccess($access)
    {
        $this->access = $access;
    }

    public function getAccess()
    {
        throw new RuntimeException('PayPal payment not yet implemented');
    }

    public function getPayment(array $data)
    {
        throw new RuntimeException('PayPal payment not yet implemented');
    }

    public function executePayment($access = null, $paymentId = null, $payerId = null)
    {
        throw new RuntimeException('PayPal payment not yet implemented');
    }

}


text:
mysql < /home/f2etest-web/f2etest.sql
sleep 2
nginx
sleep 2
pm2 start app.js --name f2etest-web


text:
module Dorsale::Flyboy::TaskPolicyHelper
  POLICY_METHODS = [
    :list?,
    :export?,
    :create?,
    :read?,
    :comment?,
    :update?,
    :delete?,
    :complete?,
    :snooze?,
    :copy?,
  ]

  def create?
    return false if cannot_read_taskable?
    super
  end

  def complete?
    return false if task.done?
    super
  end

  def snooze?
    return false unless task.snoozer.snoozable?
    super
  end

  private

  def cannot_read_taskable?
    return false if task == Dorsale::Flyboy::Task
    return false if task.taskable.blank?

    !policy(task.taskable).read?
  end
end


text:
package org.apache.lucene.queryParser.standard.builders;

import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.core.QueryNodeException;
import org.apache.lucene.queryParser.core.nodes.FieldQueryNode;
import org.apache.lucene.queryParser.core.nodes.QueryNode;
import org.apache.lucene.search.TermQuery;

/**
 * Builds a {@link TermQuery} object from a {@link FieldQueryNode} object.
 */
public class FieldQueryNodeBuilder implements StandardQueryBuilder {

  public FieldQueryNodeBuilder() {
    // empty constructor
  }

  public TermQuery build(QueryNode queryNode) throws QueryNodeException {
    FieldQueryNode fieldNode = (FieldQueryNode) queryNode;

    return new TermQuery(new Term(fieldNode.getFieldAsString(), fieldNode
        .getTextAsString()));

  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDisplayName</key>
	<string>${AppName}</string>
	<key>CFBundleIdentifier</key>
	<string>${AppIdentifier}</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleVersion</key>
	<string>1.0</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>MinimumOSVersion</key>
	<string>7.0</string>
	<key>UIDeviceFamily</key>
	<array>
		<integer>1</integer>
		<integer>2</integer>
	</array>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>armv7</string>
	</array>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>CFBundleIconFiles</key>
	<array>
		<string>Icon-60@2x</string>
		<string>Icon-60@3x</string>
		<string>Icon-76</string>
		<string>Icon-76@2x</string>
		<string>Default</string>
		<string>Default@2x</string>
		<string>Default-568h</string>
		<string>Default-568h@2x</string>
		<string>Default-Landscape</string>
		<string>Default-Landscape@2x</string>
		<string>Default-Portrait</string>
		<string>Default-Portrait@2x</string>
		<string>Icon-Small-40</string>
		<string>Icon-Small-40@2x</string>
		<string>Icon-Small-40@3x</string>
		<string>Icon-Small</string>
		<string>Icon-Small@2x</string>
		<string>Icon-Small@3x</string>
	</array>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
</dict>
</plist>


text:
FROM protoc-artifacts:latest

RUN scl enable devtoolset-1.1 'bash -c "cd /protobuf && \
    git fetch && \
    git checkout v3.5.1 && \
    ./autogen.sh && \
    CXXFLAGS=-m32 ./configure --disable-shared --prefix=/protobuf-32 && \
    make clean && make -j$(nproc) && make -j$(nproc) install"'

RUN scl enable devtoolset-1.1 'bash -c "cd /protobuf && \
    CXXFLAGS=-m64 ./configure --disable-shared --prefix=/protobuf-64 && \
    make clean && make -j$(nproc) && make -j$(nproc) install"'

ENV CXXFLAGS=-I/protobuf-32/include \
    LDFLAGS="-L/protobuf-32/lib -L/protobuf-64/lib"

RUN git clone --depth 1 https://github.com/grpc/grpc-java.git

# Start in devtoolset environment that uses GCC 4.7
CMD ["scl", "enable", "devtoolset-1.1", "bash"]


text:
import User from "./user.model";
import IUserModel from "./user.model";
import * as config from "../../config/environment/shared";
import * as express from "express";
import * as jwt from "jsonwebtoken";

export class UserController {
    public static getPublic(req:express.Request, res:express.Response):void {
        var userIdList = req.body;
        User.find({
        })
        .then(users => res.json(users))
        .catch(err => res.status(500).json(err));
    }

    public static index(req:express.Request, res:express.Response):void {
        User.find({}, "-salt -password")
        .then(users => res.json(users))
        .catch(err => res.status(500).json(err));
    }

    public static create(req:express.Request, res:express.Response):void {
        var newUser = new User(req.body);
        newUser.provider = "local";
        newUser.role = "user";
        newUser.validate()
        .then(() => newUser.makeSalt())
        .then(salt => {
            newUser.salt = salt;
            return newUser.encryptPassword(newUser.password)
        })
        .then(encryptedPassword => {
            newUser.password = encryptedPassword;
            return newUser.save();
        })
        .then(user => {
            let tmp = { _id: user._id, role: user.role };
            let token =  jwt.sign(tmp, config.shared.secret.session, {
                expiresIn: 60 * 60 * 5
            });
            res.json({token});
        })
        .catch(err => {
            res.status(422).json(err)
        });
    }

    public static show(req:express.Request, res:express.Response, next:express.NextFunction):void {
        var userId:string = req.params.id;
        User.findById(userId)
        .then(user => {
            if(!user) {
                return res.status(404).end();
            }
            res.json(user.profile);
        })
        .catch(err => res.status(500).json(err));
    }

    public static destroy(req:express.Request, res:express.Response) {
        User.findByIdAndRemove(req.params.id)
        .then(() => res.status(204).end())
        .catch(err => res.status(500).json(err));
    }

    public static changePassword(req:express.Request, res:express.Response):void {
        var userId:string = req.user._id;
        var oldPass = String(req.body.oldPassword);
        var newPass = String(req.body.newPassword);
        var myUser = null;

        User.findById(userId)
        .then(user => {
            myUser = user;
            user.authenticate(oldPass)
        })
        .then(() => {
            myUser.password = newPass;
            return myUser.save()
        })
        .then(user => res.json())
        .catch(err => res.status(500).json(err));
    }

    public static me(req:express.Request, res:express.Response):void {
        var userId:string = req.user._id;

        User.findOne({
            _id: userId
        }, "-salt -password")
        .then(user => {
            if (!user) {
                return res.status(401).end();
            }
            res.json(user);
        })
        .catch(err => res.status(500).json(err));
    }

    public static authCallback(req:express.Request, res:express.Response) {
        res.redirect("/");
    }
}


text: A basic Blockchain application


text:
/*
****************************************************************************************************************************
* DiLib v2.0 (dilib.dimutu.com)
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product documentation
* would be appreciated.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* 4. Third party open source "TinyXML" is used in this program, and for more information please see its own terms of use.
*******************************************************************************************************************************
*/
namespace DiTree.Properties
{

    // This class allows you to handle specific events on the settings class:
    //  The SettingChanging event is raised before a setting's value is changed.
    //  The PropertyChanged event is raised after a setting's value is changed.
    //  The SettingsLoaded event is raised after the setting values are loaded.
    //  The SettingsSaving event is raised before the setting values are saved.
    internal sealed partial class Settings {

        public Settings() {
            // // To add event handlers for saving and changing settings, uncomment the lines below:
            //
            // this.SettingChanging += this.SettingChangingEventHandler;
            //
            // this.SettingsSaving += this.SettingsSavingEventHandler;
            //
        }

        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
            // Add code to handle the SettingChangingEvent event here.
        }

        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
            // Add code to handle the SettingsSaving event here.
        }
    }
}


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/ads/googleads/v11/enums/conversion_custom_variable_status.proto", :syntax => :proto3) do
    add_message "google.ads.googleads.v11.enums.ConversionCustomVariableStatusEnum" do
    end
    add_enum "google.ads.googleads.v11.enums.ConversionCustomVariableStatusEnum.ConversionCustomVariableStatus" do
      value :UNSPECIFIED, 0
      value :UNKNOWN, 1
      value :ACTIVATION_NEEDED, 2
      value :ENABLED, 3
      value :PAUSED, 4
    end
  end
end

module Google
  module Ads
    module GoogleAds
      module V11
        module Enums
          ConversionCustomVariableStatusEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v11.enums.ConversionCustomVariableStatusEnum").msgclass
          ConversionCustomVariableStatusEnum::ConversionCustomVariableStatus = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v11.enums.ConversionCustomVariableStatusEnum.ConversionCustomVariableStatus").enummodule
        end
      end
    end
  end
end


text:
$(document).ready(function(){
    if (document.cookie.indexOf("theme_title") >= 0) {
        if (tapbbs_viewport === 'mobile')
        {
            $('#header').prepend(
                "
["+$.cookie('theme_title')+"] "+lang['theme_preview_mode'] +
                " ["+lang['close']+"]
"
            );
        }
        else
        {
            $('body').prepend(
                "
" +
                " ["+$.cookie('theme_title')+"] "+lang['theme_preview_mode']+"" +
                " ["+lang['close']+"]" +
                "<button type='button' class='close' data-dismiss='alert'>×</button>
");

            $('#remove_theme_cookie_bar').bind('closed', function () {
                remove_theme_cookies();
            });
        }
    }
});

function remove_theme_cookies()
{
    var options = {path : '/'};

    $.removeCookie('theme_type', options);
    $.removeCookie('theme_title', options);
    $.removeCookie('theme_folder_name', options);
}


text:
package net.dv8tion.jda.core.utils;

import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.entities.impl.AbstractChannelImpl;
import net.dv8tion.jda.core.entities.impl.GuildImpl;
import net.dv8tion.jda.core.entities.impl.PermissionOverrideImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.util.Args;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class PermissionUtil
{
    /**
     * Checks if one given Member can interact with a 2nd given Member - in a permission sense (kick/ban/modify perms).
     * This only checks the Role-Position and does not check the actual permission (kick/ban/manage_role/...)
     *
     * @param  issuer
     *         The member that tries to interact with 2nd member
     * @param  target
     *         The member that is the target of the interaction
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True, if issuer can interact with target in guild
     */
    public static boolean canInteract(Member issuer, Member target)
    {
        Args.notNull(issuer, "Issuer Member");
        Args.notNull(target, "Target Member");

        Guild guild = issuer.getGuild();
        if (!guild.equals(target.getGuild()))
            throw new IllegalArgumentException("Provided members must both be Member objects of the same Guild!");
        if(guild.getOwner().equals(issuer))
            return true;
        if(guild.getOwner().equals(target))
            return false;
        List<Role> issuerRoles = issuer.getRoles();
        List<Role> targetRoles = target.getRoles();
        return !issuerRoles.isEmpty() && (targetRoles.isEmpty() || canInteract(issuerRoles.get(0), targetRoles.get(0)));
    }

    /**
     * Checks if a given Member can interact with a given Role - in a permission sense (kick/ban/modify perms).
     * This only checks the Role-Position and does not check the actual permission (kick/ban/manage_role/...)
     *
     * @param  issuer
     *         The member that tries to interact with the role
     * @param  target
     *         The role that is the target of the interaction
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True, if issuer can interact with target
     */
    public static boolean canInteract(Member issuer, Role target)
    {
        Args.notNull(issuer, "Issuer Member");
        Args.notNull(target, "Target Role");

        Guild guild = issuer.getGuild();
        if (!guild.equals(target.getGuild()))
            throw new IllegalArgumentException("Provided Member issuer and Role target must be from the same Guild!");
        if(guild.getOwner().equals(issuer))
            return true;
        List<Role> issuerRoles = issuer.getRoles();
        return !issuerRoles.isEmpty() && canInteract(issuerRoles.get(0), target);
    }

    /**
     * Checks if one given Role can interact with a 2nd given Role - in a permission sense (kick/ban/modify perms).
     * This only checks the Role-Position and does not check the actual permission (kick/ban/manage_role/...)
     *
     * @param  issuer
     *         The role that tries to interact with 2nd role
     * @param  target
     *         The role that is the target of the interaction
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True, if issuer can interact with target
     */
    public static boolean canInteract(Role issuer, Role target)
    {
        Args.notNull(issuer, "Issuer Role");
        Args.notNull(target, "Target Role");

        if(!issuer.getGuild().equals(target.getGuild()))
            throw new IllegalArgumentException("The 2 Roles are not from same Guild!");
        return target.getPosition() < issuer.getPosition();
    }

    /**
     * Check whether the provided {@link net.dv8tion.jda.core.entities.Member Member} can use the specified {@link net.dv8tion.jda.core.entities.Emote Emote}.
     *
     *
If the specified Member is not in the emote's guild or the emote provided is fake this will return false.
     * Otherwise it will check if the emote is restricted to any roles and if that is the case if the Member has one of these.
     *
Note: This is not checking if the issuer owns the Guild or not.
     *
     * @param  issuer
     *         The member that tries to interact with the Emote
     * @param  emote
     *         The emote that is the target interaction
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True, if the issuer can interact with the emote
     */
    public static boolean canInteract(Member issuer, Emote emote)
    {
        Args.notNull(issuer, "Issuer Member");
        Args.notNull(emote,  "Target Emote");

        if (!issuer.getGuild().equals(emote.getGuild()))
            throw new IllegalArgumentException("The issuer and target are not in the same Guild");
        return !emote.isFake() // Fake emote -> can't use
                && (emote.getRoles().isEmpty() // Emote restricted to roles -> check if the issuer has them
                    || CollectionUtils.containsAny(issuer.getRoles(), emote.getRoles()));
    }

    /**
     * Checks whether the specified {@link net.dv8tion.jda.core.entities.Emote Emote} can be used by the provided
     * {@link net.dv8tion.jda.core.entities.User User} in the {@link net.dv8tion.jda.core.entities.MessageChannel MessageChannel}.
     *
     * @param  issuer
     *         The user that tries to interact with the Emote
     * @param  emote
     *         The emote that is the target interaction
     * @param  channel
     *         The MessageChannel this emote should be interacted within
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True, if the issuer can interact with the emote within the specified MessageChannel
     */
    public static boolean canInteract(User issuer, Emote emote, MessageChannel channel)
    {
        Args.notNull(issuer,  "Issuer Member");
        Args.notNull(emote,   "Target Emote");
        Args.notNull(channel, "Target Channel");

        if (emote.isFake() || !emote.getGuild().isMember(issuer))
            return false; // cannot use an emote if you're not in its guild
        Member member = emote.getGuild().getMemberById(issuer.getIdLong());
        if (!canInteract(member, emote))
            return false;
        switch (channel.getType())
        {
            case TEXT:
                TextChannel text = (TextChannel) channel;
                member = text.getGuild().getMemberById(issuer.getIdLong());
                return emote.getGuild().equals(text.getGuild()) // within the same guild
                    || (emote.isManaged() && checkPermission(text, member, Permission.MESSAGE_EXT_EMOJI)); // in different guild
            default:
                return emote.isManaged(); // In Group or Private it only needs to be managed
        }
    }

    @Deprecated
    public static PermissionOverride getFullPermOverride()
    {
        PermissionOverrideImpl override = new PermissionOverrideImpl(null, 0, null);
        long allow = 0, deny = 0;
        for (Permission permission : Permission.values())
        {
            if(permission != Permission.UNKNOWN)
            {
                allow = allow | (1 << permission.getOffset());
            }
        }
        return override.setAllow(allow).setDeny(deny);
    }

    /**
     * @deprecated Use {@link #checkPermission(net.dv8tion.jda.core.entities.Member, net.dv8tion.jda.core.Permission...)} instead
     */
    @Deprecated
    public static boolean checkPermission(Guild guild, Member member, Permission... permissions)
    {
        return checkPermission(member, permissions);
    }

    /**
     * Checks to see if the {@link net.dv8tion.jda.core.entities.Member Member} has the specified {@link net.dv8tion.jda.core.Permission Permissions}
     * in the specified {@link net.dv8tion.jda.core.entities.Guild Guild}. This method properly deals with Owner status.
     *
     *
Note: this is based on effective permissions, not literal permissions. If a member has permissions that would
     * enable them to do something without the literal permission to do it, this will still return true.
     *
Example: If a member has the {@link net.dv8tion.jda.core.Permission#ADMINISTRATOR} permission, they will be able to
     * {@link net.dv8tion.jda.core.Permission#MANAGE_SERVER} as well, even without the literal permissions.
     *
     * @param  member
     *         The {@link net.dv8tion.jda.core.entities.Member Member} whose permissions are being checked.
     * @param  permissions
     *         The {@link net.dv8tion.jda.core.Permission Permissions} being checked for.
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is null
     *
     * @return True -
     *         if the {@link net.dv8tion.jda.core.entities.Member Member} effectively has the specified {@link net.dv8tion.jda.core.Permission Permissions}.
     */
    public static boolean checkPermission(Member member, Permission... permissions)
    {
        Args.notNull(member, "Member");
        Args.notNull(permissions, "Permissions");

        long effectivePerms = getEffectivePermission(member);
        return isApplied(effectivePerms, Permission.ADMINISTRATOR.getRawValue())
                || isApplied(effectivePerms, Permission.getRaw(permissions));
    }

    /**
     * Checks to see if the {@link net.dv8tion.jda.core.entities.Member Member} has the specified {@link net.dv8tion.jda.core.Permission Permissions}
     * in the specified {@link net.dv8tion.jda.core.entities.Channel Channel}. This method properly deals with
     * {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides} and Owner status.
     *
     *
Note: this is based on effective permissions, not literal permissions. If a member has permissions that would
     * enable them to do something without the literal permission to do it, this will still return true.
     *
Example: If a member has the {@link net.dv8tion.jda.core.Permission#ADMINISTRATOR} permission, they will be able to
     * {@link net.dv8tion.jda.core.Permission#MESSAGE_WRITE} in every channel.
     *
     * @param  member
     *         The {@link net.dv8tion.jda.core.entities.Member Member} whose permissions are being checked.
     * @param  channel
     *         The {@link net.dv8tion.jda.core.entities.Channel Channel} being checked.
     * @param  permissions
     *         The {@link net.dv8tion.jda.core.Permission Permissions} being checked for.
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return True -
     *         if the {@link net.dv8tion.jda.core.entities.Member Member} effectively has the specified {@link net.dv8tion.jda.core.Permission Permissions}.
     */
    public static boolean checkPermission(Channel channel, Member member, Permission... permissions)
    {
        Args.notNull(channel, "Channel");
        Args.notNull(member, "Member");
        Args.notNull(permissions, "Permissions");

        GuildImpl guild = (GuildImpl) channel.getGuild();
        checkGuild(guild, member.getGuild(), "Member");

//        if (guild.getOwner().equals(member) // Admin or owner? If yes: no need to iterate
//                || guild.getPublicRole().hasPermission(Permission.ADMINISTRATOR)
//                || member.getRoles().stream().anyMatch(role -> role.hasPermission(Permission.ADMINISTRATOR)))
//            return true; // can be removed as getEffectivePermissions calculates these cases in

        long effectivePerms = getEffectivePermission(channel, member);
        return isApplied(effectivePerms, Permission.ADMINISTRATOR.getRawValue())
                || isApplied(effectivePerms, Permission.getRaw(permissions));
    }

    /**
     * @deprecated Use {@link #getEffectivePermission(net.dv8tion.jda.core.entities.Member)} instead
     */
    @Deprecated
    public static long getEffectivePermission(Guild guild, Member member)
    {
        return getEffectivePermission(member);
    }

    /**
     * Gets the {@code long} representation of the effective permissions allowed for this {@link net.dv8tion.jda.core.entities.Member Member}
     * in this {@link net.dv8tion.jda.core.entities.Guild Guild}. This can be used in conjunction with
     * {@link net.dv8tion.jda.core.Permission#getPermissions(long) Permission.getPermissions(int)} to easily get a list of all
     * {@link net.dv8tion.jda.core.Permission Permissions} that this member has in this {@link net.dv8tion.jda.core.entities.Guild Guild}.
     *
     *
This only returns the Guild-level permissions!
     *
     * @param  member
     *         The {@link net.dv8tion.jda.core.entities.Member Member} whose permissions are being checked.
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return The {@code long} representation of the literal permissions that
     *         this {@link net.dv8tion.jda.core.entities.Member Member} has in this {@link net.dv8tion.jda.core.entities.Guild Guild}.
     */
    public static long getEffectivePermission(Member member)
    {
        Args.notNull(member, "Member");

        if (member.isOwner())
            return Permission.ALL_PERMISSIONS;
        //Default to binary OR of all global permissions in this guild
        long permission = member.getGuild().getPublicRole().getPermissionsRaw();
        for (Role role : member.getRoles())
        {
            permission |= role.getPermissionsRaw();
            if (isApplied(permission, Permission.ADMINISTRATOR.getRawValue()))
                return Permission.ALL_PERMISSIONS;
        }

        return permission;
    }

    /**
     * Gets the {@code long} representation of the effective permissions allowed for this {@link net.dv8tion.jda.core.entities.Member Member}
     * in this {@link net.dv8tion.jda.core.entities.Channel Channel}. This can be used in conjunction with
     * {@link net.dv8tion.jda.core.Permission#getPermissions(long) Permission.getPermissions(long)} to easily get a list of all
     * {@link net.dv8tion.jda.core.Permission Permissions} that this member can use in this {@link net.dv8tion.jda.core.entities.Channel Channel}.
     *
This functions very similarly to how {@link net.dv8tion.jda.core.entities.Role#getPermissionsRaw() Role.getPermissionsRaw()}.
     *
     * @param  channel
     *         The {@link net.dv8tion.jda.core.entities.Channel Channel} being checked.
     * @param  member
     *         The {@link net.dv8tion.jda.core.entities.Member Member} whose permissions are being checked.
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return The {@code long} representation of the effective permissions that this {@link net.dv8tion.jda.core.entities.Member Member}
     *         has in this {@link net.dv8tion.jda.core.entities.Channel Channel}.
     */
    public static long getEffectivePermission(Channel channel, Member member)
    {
        Args.notNull(channel, "Channel");
        Args.notNull(member, "Member");
        final long admin = Permission.ADMINISTRATOR.getRawValue();

        if (!channel.getGuild().equals(member.getGuild()))
            throw new IllegalArgumentException("Provided channel and provided member are not of the same guild!");

        if (member.isOwner())
            // Owner effectively has all permissions
            return Permission.ALL_PERMISSIONS;

        final AbstractChannelImpl<?> abstractChannel = (AbstractChannelImpl<?>) channel;
        final Guild guild = member.getGuild();
        long permission = getEffectivePermission(member) | getExplicitPermission(channel, member);

        AtomicLong allow = new AtomicLong(0);
        AtomicLong deny = new AtomicLong(0);

        getExplicitOverrides(channel, member, allow, deny);
        permission = apply(permission, allow.get(), deny.get());

        if (isApplied(permission, admin))
            // If the public role is marked as administrator we can return full permissions here
            return Permission.ALL_PERMISSIONS;
        else if (!isApplied(permission, Permission.MESSAGE_READ.getRawValue()))
            // When the permission to read messages is not applied it is not granted
            return permission & ~Permission.ALL_TEXT_PERMISSIONS;

        final boolean isPerms = isApplied(permission, Permission.MANAGE_PERMISSIONS.getRawValue());
        final boolean isChan = isApplied(permission, Permission.MANAGE_CHANNEL.getRawValue());
        if (isPerms || isChan)
            // In text channels MANAGE_CHANNEL and MANAGE_PERMISSIONS grant full text/voice permissions
            permission |= Permission.ALL_TEXT_PERMISSIONS | Permission.ALL_VOICE_PERMISSIONS;

        return permission & ~deny.get() | allow.get();
    }

    /**
     * Gets the {@code long} representation of the effective permissions allowed for this {@link net.dv8tion.jda.core.entities.Role Role}
     * in this {@link net.dv8tion.jda.core.entities.Channel Channel}. This can be used in conjunction with
     * {@link net.dv8tion.jda.core.Permission#getPermissions(long) Permission.getPermissions(long)} to easily get a list of all
     * {@link net.dv8tion.jda.core.Permission Permissions} that this role can use in this {@link net.dv8tion.jda.core.entities.Channel Channel}.
     *
     * @param  channel
     *         The {@link net.dv8tion.jda.core.entities.Channel Channel} in which permissions are being checked.
     * @param  role
     *         The {@link net.dv8tion.jda.core.entities.Role Role} whose permissions are being checked.
     *
     * @throws IllegalArgumentException
     *         if any of the provided parameters is {@code null}
     *         or the provided entities are not from the same guild
     *
     * @return The {@code long} representation of the effective permissions that this {@link net.dv8tion.jda.core.entities.Role Role}
     *         has in this {@link net.dv8tion.jda.core.entities.Channel Channel}
     */
    public static long getEffectivePermission(Channel channel, Role role)
    {
        Args.notNull(channel, "Channel");
        Args.notNull(role, "Role");

        Guild guild = channel.getGuild();
        if (!guild.equals(role.getGuild()))
            throw new IllegalArgumentException("Provided channel and role are not of the same guild!");

        long permissions = role.getPermissionsRaw() | guild.getPublicRole().getPermissionsRaw();

        PermissionOverride publicOverride = channel.getPermissionOverride(guild.getPublicRole());
        PermissionOverride roleOverride = channel.getPermissionOverride(role);

        if (publicOverride != null)
        {
            permissions &= ~publicOverride.getDeniedRaw();
            permissions |= publicOverride.getAllowedRaw();
        }

        if (roleOverride != null)
        {
            permissions &= ~roleOverride.getDeniedRaw();
            permissions |= roleOverride.getAllowedRaw();
        }

        return permissions;
    }

    /**
     * Retrieves the explicit permissions of the specified {@link net.dv8tion.jda.core.entities.Member Member}
     * in its hosting {@link net.dv8tion.jda.core.entities.Guild Guild}.
     *
This method does not calculate the owner in.
     *
     *
All permissions returned are explicitly granted to this Member via its {@link net.dv8tion.jda.core.entities.Role Roles}.
     *
Permissions like {@link net.dv8tion.jda.core.Permission#ADMINISTRATOR Permission.ADMINISTRATOR} do not
     * grant other permissions in this value.
     *
     * @param  member
     *         The non-null {@link net.dv8tion.jda.core.entities.Member Member} for which to get implicit permissions
     *
     * @throws IllegalArgumentException
     *         If the specified member is {@code null}
     *
     * @return Primitive (unsigned) long value with the implicit permissions of the specified member
     *
     * @since  3.1
     */
    public static long getExplicitPermission(Member member)
    {
        Args.notNull(member, "Member");

        final Guild guild = member.getGuild();
        long permission = guild.getPublicRole().getPermissionsRaw();

        for (Role role : member.getRoles())
            permission |= role.getPermissionsRaw();

        return permission;
    }

    /**
     * Retrieves the explicit permissions of the specified {@link net.dv8tion.jda.core.entities.Member Member}
     * in its hosting {@link net.dv8tion.jda.core.entities.Guild Guild} and specific {@link net.dv8tion.jda.core.entities.Channel Channel}.
     *
This method does not calculate the owner in.
     * Allowed permissions override denied permissions of {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides}!
     *
     *
All permissions returned are explicitly granted to this Member via its {@link net.dv8tion.jda.core.entities.Role Roles}.
     *
Permissions like {@link net.dv8tion.jda.core.Permission#ADMINISTRATOR Permission.ADMINISTRATOR} do not
     * grant other permissions in this value.
     *
This factor in all {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides} that affect this member
     * and only grants the ones that are explicitly given.
     *
     * @param  channel
     *         The target channel of which to check {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides}
     * @param  member
     *         The non-null {@link net.dv8tion.jda.core.entities.Member Member} for which to get implicit permissions
     *
     * @throws IllegalArgumentException
     *         If any of the arguments is {@code null}
     *         or the specified entities are not from the same {@link net.dv8tion.jda.core.entities.Guild Guild}
     *
     * @return Primitive (unsigned) long value with the implicit permissions of the specified member in the specified channel
     *
     * @since  3.1
     */
    public static long getExplicitPermission(Channel channel, Member member)
    {
        Args.notNull(channel, "Channel");
        Args.notNull(member, "Member");

        final Guild guild = member.getGuild();
        checkGuild(channel.getGuild(), guild, "Member");

        long permission = guild.getPublicRole().getPermissionsRaw();

        AtomicLong allow = new AtomicLong(0);
        AtomicLong deny = new AtomicLong(0);

        // populates allow/deny
        getExplicitOverrides(channel, member, allow, deny);

        return apply(permission, allow.get(), deny.get());
    }

    /**
     * Retrieves the explicit permissions of the specified {@link net.dv8tion.jda.core.entities.Role Role}
     * in its hosting {@link net.dv8tion.jda.core.entities.Guild Guild} and specific {@link net.dv8tion.jda.core.entities.Channel Channel}.
     *
Allowed permissions override denied permissions of {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides}!
     *
     *
All permissions returned are explicitly granted to this Role.
     *
Permissions like {@link net.dv8tion.jda.core.Permission#ADMINISTRATOR Permission.ADMINISTRATOR} do not
     * grant other permissions in this value.
     *
This factor in existing {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides} if possible.
     *
     * @param  channel
     *         The target channel of which to check {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverrides}
     * @param  role
     *         The non-null {@link net.dv8tion.jda.core.entities.Role Role} for which to get implicit permissions
     *
     * @throws IllegalArgumentException
     *         If any of the arguments is {@code null}
     *         or the specified entities are not from the same {@link net.dv8tion.jda.core.entities.Guild Guild}
     *
     * @return Primitive (unsigned) long value with the implicit permissions of the specified role in the specified channel
     *
     * @since  3.1
     */
    public static long getExplicitPermission(Channel channel, Role role)
    {
        Args.notNull(channel, "Channel");
        Args.notNull(role, "Role");

        final Guild guild = role.getGuild();
        checkGuild(channel.getGuild(), guild, "Role");

        long permission = role.getPermissionsRaw() | guild.getPublicRole().getPermissionsRaw();
        PermissionOverride override = channel.getPermissionOverride(guild.getPublicRole());
        if (override != null)
            permission = apply(permission, override.getAllowedRaw(), override.getDeniedRaw());
        if (role.isPublicRole())
            return permission;

        override = channel.getPermissionOverride(role);

        return override == null
            ? permission
            : apply(permission, override.getAllowedRaw(), override.getDeniedRaw());
    }

    /**
     * Pushes all deny/allow values to the specified BiConsumer
     *
First parameter is allow, second is deny
     */
    private static void getExplicitOverrides(Channel channel, Member member, AtomicLong allow, AtomicLong deny)
    {
        PermissionOverride override = channel.getPermissionOverride(member.getGuild().getPublicRole());
        long allowRaw = 0;
        long denyRaw = 0;
        if (override != null)
        {
            denyRaw = override.getDeniedRaw();
            allowRaw = override.getAllowedRaw();
        }

        long allowRole = 0;
        long denyRole = 0;
        // create temporary bit containers for role cascade
        for (Role role : member.getRoles())
        {
            override = channel.getPermissionOverride(role);
            if (override != null)
            {
                // important to update role cascade not others
                denyRole |= override.getDeniedRaw();
                allowRole |= override.getAllowedRaw();
            }
        }
        // Override the raw values of public role then apply role cascade
        allowRaw = (allowRaw & ~denyRole) | allowRole;
        denyRaw = (denyRaw & ~allowRole) | denyRole;

        override = channel.getPermissionOverride(member);
        if (override != null)
        {
            // finally override the role cascade with member overrides
            final long oDeny = override.getDeniedRaw();
            final long oAllow = override.getAllowedRaw();
            allowRaw = (allowRaw & ~oDeny) | oAllow;
            denyRaw = (denyRaw & ~oAllow) | oDeny;
            // this time we need to exclude new allowed bits from old denied ones and OR the new denied bits as final overrides
        }
        // set as resulting values
        allow.set(allowRaw);
        deny.set(denyRaw);
    }

    /*
     * Check whether the specified permission is applied in the bits
     */
    private static boolean isApplied(long permissions, long perms)
    {
        return (permissions & perms) == perms;
    }

    private static long apply(long permission, long allow, long deny)
    {
        permission &= ~deny;  //Deny everything that the cascade of roles denied.
        permission |= allow;  //Allow all the things that the cascade of roles allowed
                              // The allowed bits override the denied ones!
        return permission;
    }

    private static void checkGuild(Guild o1, Guild o2, String name)
    {
        Args.check(o1.equals(o2),
            "Specified %s is not in the same guild! (%s / %s)", name, o1.toString(), o2.toString());
    }
}


text:
{% extends "oscar/customer/baseaccountpage.html" %}
{% load i18n %}

{% block breadcrumbs %}

                {% trans 'Home' %}

                {% trans 'Account' %}

                {% trans 'Wish Lists' %}

                {% if wishlist %}
                    {{ wishlist.name }}
                {% else %}
                    {% trans "Create" %}
                {% endif %}

{% endblock %}

{% block tabcontent %}
    <form method="post" data-behaviours="lock">
        {% csrf_token %}
        {{ shared_emails_formset.management_form }}

        {% if not wishlist %}

{% trans "What should your new wish list be called?" %}

        {% endif %}
        {% include "oscar/partials/form_fields.html" %}
        {% if product %}

                {% blocktrans with title=product.get_title %}
                    After your wishlist is created, {{ title }} will be added.
                {% endblocktrans %}

        {% endif %}

{% trans "Share wishlist" %}

                {% trans "If you want to share your wishlist with others, you can add their email addresses below. The visibility must be set to shared in order for this to work." %}

            {% for form in shared_emails_formset %}
                {% include "oscar/partials/form_fields.html" with form=form %}
            {% endfor %}

            <button class="btn btn-lg btn-primary" type="submit" data-loading-text="{% trans 'Saving...' %}">{% trans "Save" %}</button>
            {% trans "or" %} {% trans "cancel" %}.

    </form>
{% endblock tabcontent %}