text:
package org.apache.nifi.web.dao.impl;

import org.apache.nifi.connectable.Port;
import org.apache.nifi.connectable.Position;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.ScheduledState;
import org.apache.nifi.controller.exception.ValidationException;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.remote.RootGroupPort;
import org.apache.nifi.web.NiFiCoreException;
import org.apache.nifi.web.ResourceNotFoundException;
import org.apache.nifi.web.api.dto.PortDTO;
import org.apache.nifi.web.dao.PortDAO;

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

public class StandardOutputPortDAO extends ComponentDAO implements PortDAO {

    private FlowController flowController;

    private Port locatePort(final String portId) {
        final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
        final Port port = rootGroup.findOutputPort(portId);

        if (port == null) {
            throw new ResourceNotFoundException(String.format("Unable to find port with id '%s'.", portId));
        } else {
            return port;
        }
    }

    @Override
    public boolean hasPort(String portId) {
        final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
        return rootGroup.findOutputPort(portId) != null;
    }

    @Override
    public Port createPort(String groupId, PortDTO portDTO) {
        if (isNotNull(portDTO.getParentGroupId()) && !flowController.areGroupsSame(groupId, portDTO.getParentGroupId())) {
            throw new IllegalArgumentException("Cannot specify a different Parent Group ID than the Group to which the OutputPort is being added.");
        }

        // ensure the name has been specified
        if (portDTO.getName() == null) {
            throw new IllegalArgumentException("Port name must be specified.");
        }

        // get the desired group
        ProcessGroup group = locateProcessGroup(flowController, groupId);

        // determine if this is the root group
        Port port;
        if (group.getParent() == null) {
            port = flowController.createRemoteOutputPort(portDTO.getId(), portDTO.getName());
        } else {
            port = flowController.createLocalOutputPort(portDTO.getId(), portDTO.getName());
        }

        // ensure we can perform the update before we add the processor to the flow
        verifyUpdate(port, portDTO);

        // configure
        if (portDTO.getPosition() != null) {
            port.setPosition(new Position(portDTO.getPosition().getX(), portDTO.getPosition().getY()));
        }
        port.setComments(portDTO.getComments());

        // add the port
        group.addOutputPort(port);
        return port;
    }

    @Override
    public Port getPort(String portId) {
        return locatePort(portId);
    }

    @Override
    public Set<Port> getPorts(String groupId) {
        ProcessGroup group = locateProcessGroup(flowController, groupId);
        return group.getOutputPorts();
    }

    @Override
    public void verifyUpdate(PortDTO portDTO) {
        final Port outputPort = locatePort(portDTO.getId());
        verifyUpdate(outputPort, portDTO);
    }

    private void verifyUpdate(final Port outputPort, final PortDTO portDTO) {
        if (isNotNull(portDTO.getState())) {
            final ScheduledState purposedScheduledState = ScheduledState.valueOf(portDTO.getState());

            // only attempt an action if it is changing
            if (!purposedScheduledState.equals(outputPort.getScheduledState())) {
                // perform the appropriate action
                switch (purposedScheduledState) {
                    case RUNNING:
                        outputPort.verifyCanStart();
                        break;
                    case STOPPED:
                        switch (outputPort.getScheduledState()) {
                            case RUNNING:
                                outputPort.verifyCanStop();
                                break;
                            case DISABLED:
                                outputPort.verifyCanEnable();
                                break;
                        }
                        break;
                    case DISABLED:
                        outputPort.verifyCanDisable();
                        break;
                }
            }
        }

        // see what's be modified
        if (isAnyNotNull(portDTO.getUserAccessControl(),
                portDTO.getGroupAccessControl(),
                portDTO.getConcurrentlySchedulableTaskCount(),
                portDTO.getName(),
                portDTO.getComments())) {

            // validate the request
            final List<String> requestValidation = validateProposedConfiguration(portDTO);

            // ensure there was no validation errors
            if (!requestValidation.isEmpty()) {
                throw new ValidationException(requestValidation);
            }

            // ensure the port can be updated
            outputPort.verifyCanUpdate();
        }
    }

    private List<String> validateProposedConfiguration(PortDTO portDTO) {
        List<String> validationErrors = new ArrayList<>();

        if (isNotNull(portDTO.getName()) && portDTO.getName().trim().isEmpty()) {
            validationErrors.add("Port name cannot be blank.");
        }
        if (isNotNull(portDTO.getConcurrentlySchedulableTaskCount()) && portDTO.getConcurrentlySchedulableTaskCount() <= 0) {
            validationErrors.add("Concurrent tasks must be a positive integer.");
        }

        return validationErrors;
    }

    @Override
    public Port updatePort(PortDTO portDTO) {
        Port outputPort = locatePort(portDTO.getId());

        // ensure we can do this update
        verifyUpdate(outputPort, portDTO);

        // handle state transition
        if (portDTO.getState() != null) {
            final ScheduledState purposedScheduledState = ScheduledState.valueOf(portDTO.getState());

            // only attempt an action if it is changing
            if (!purposedScheduledState.equals(outputPort.getScheduledState())) {
                try {
                    // perform the appropriate action
                    switch (purposedScheduledState) {
                        case RUNNING:
                            outputPort.getProcessGroup().startOutputPort(outputPort);
                            break;
                        case STOPPED:
                            switch (outputPort.getScheduledState()) {
                                case RUNNING:
                                    outputPort.getProcessGroup().stopOutputPort(outputPort);
                                    break;
                                case DISABLED:
                                    outputPort.getProcessGroup().enableOutputPort(outputPort);
                                    break;
                            }
                            break;
                        case DISABLED:
                            outputPort.getProcessGroup().disableOutputPort(outputPort);
                            break;
                    }
                } catch (IllegalStateException ise) {
                    throw new NiFiCoreException(ise.getMessage(), ise);
                }
            }
        }

        if (outputPort instanceof RootGroupPort) {
            final RootGroupPort rootPort = (RootGroupPort) outputPort;
            if (isNotNull(portDTO.getGroupAccessControl())) {
                rootPort.setGroupAccessControl(portDTO.getGroupAccessControl());
            }
            if (isNotNull(portDTO.getUserAccessControl())) {
                rootPort.setUserAccessControl(portDTO.getUserAccessControl());
            }
        }

        // perform the configuration
        final String name = portDTO.getName();
        final String comments = portDTO.getComments();
        final Integer concurrentTasks = portDTO.getConcurrentlySchedulableTaskCount();
        if (isNotNull(portDTO.getPosition())) {
            outputPort.setPosition(new Position(portDTO.getPosition().getX(), portDTO.getPosition().getY()));
        }
        if (isNotNull(name)) {
            outputPort.setName(name);
        }
        if (isNotNull(comments)) {
            outputPort.setComments(comments);
        }
        if (isNotNull(concurrentTasks)) {
            outputPort.setMaxConcurrentTasks(concurrentTasks);
        }

        return outputPort;
    }

    @Override
    public void verifyDelete(final String portId) {
        final Port outputPort = locatePort(portId);
        outputPort.verifyCanDelete();
    }

    @Override
    public void deletePort(String portId) {
        Port outputPort = locatePort(portId);
        outputPort.getProcessGroup().removeOutputPort(outputPort);
    }

    /* setters */
    public void setFlowController(FlowController flowController) {
        this.flowController = flowController;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "include/core/SkRefCnt.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/gl/GrGLFunctions.h"
#include "include/gpu/gl/GrGLInterface.h"
#include "tools/gpu/gl/GLTestContext.h"

#include <EGL/egl.h>
#include <GLES2/gl2.h>

#include <sstream>

// create_direct_context implementation for EGL.
sk_sp<GrDirectContext> create_direct_context(
        std::ostringstream& driverinfo,
        std::unique_ptr<sk_gpu_test::GLTestContext>* glContext) {
    glContext->reset(sk_gpu_test::CreatePlatformGLTestContext(kGLES_GrGLStandard));
    if (!glContext) {
        return nullptr;
    }
    (*glContext)->makeCurrent();
    sk_sp<GrDirectContext> result = (*glContext)->makeContext(GrContextOptions());
    if (!result) {
        glContext->reset();
        return nullptr;
    }

    driverinfo << "GL Version: " << glGetString(GL_VERSION) << "\n";
    driverinfo << "GL Vendor: " << glGetString(GL_VENDOR) << "\n";
    driverinfo << "GL Renderer: " << glGetString(GL_RENDERER) << "\n";
    driverinfo << "GL Extensions: " << glGetString(GL_EXTENSIONS) << "\n";

    return result;
}


text:
<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

class DDC588Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->_schemaTool->createSchema(array(
            $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC588Site'),
        ));
    }

    public function testIssue()
    {
        $site = new DDC588Site('Foo');

        $this->_em->persist($site);
        $this->_em->flush();
        // Following should not result in exception
        $this->_em->refresh($site);
    }
}

/**
 * @Entity
 */
class DDC588Site
{
    /**
     * @Id
     * @Column(type="integer", name="site_id")
     * @GeneratedValue
     */
    public $id;

    /**
     * @Column(type="string", length=45)
     */
    protected $name = null;

    public function __construct($name = '')
    {
        $this->name = $name;
    }
}


text:
using System;

namespace Fort.Info
{
    [AttributeUsage(AttributeTargets.Property)]
    public class CustomExportAttribute:Attribute
    {
        public CustomExportAttribute()
        {
            AddType = true;
        }
        public string DisplayName { get; set; }
        public bool AddType { get; set; }
    }
}


text:
<!DOCTYPE html>

  <title>Demo DOM 014 - third scene</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="../docco.css" />

          Jump To …
          +

                  ./demo/canvas-001.js

                  ./demo/canvas-002.js

                  ./demo/canvas-003.js

                  ./demo/canvas-004.js

                  ./demo/canvas-005.js

                  ./demo/canvas-006.js

                  ./demo/canvas-007.js

                  ./demo/canvas-008.js

                  ./demo/canvas-009.js

                  ./demo/canvas-010.js

                  ./demo/canvas-011.js

                  ./demo/canvas-012.js

                  ./demo/canvas-013.js

                  ./demo/canvas-014.js

                  ./demo/canvas-015.js

                  ./demo/canvas-015a.js

                  ./demo/canvas-016.js

                  ./demo/canvas-017.js

                  ./demo/canvas-018.js

                  ./demo/canvas-019.js

                  ./demo/canvas-019a.js

                  ./demo/canvas-020.js

                  ./demo/canvas-021.js

                  ./demo/canvas-022.js

                  ./demo/canvas-023.js

                  ./demo/canvas-024.js

                  ./demo/canvas-025.js

                  ./demo/canvas-026.js

                  ./demo/canvas-027.js

                  ./demo/canvas-028.js

                  ./demo/canvas-029.js

                  ./demo/canvas-030.js

                  ./demo/canvas-031.js

                  ./demo/canvas-032.js

                  ./demo/canvas-033.js

                  ./demo/canvas-034.js

                  ./demo/canvas-035.js

                  ./demo/canvas-036.js

                  ./demo/canvas-037.js

                  ./demo/canvas-038.js

                  ./demo/canvas-039.js

                  ./demo/canvas-040.js

                  ./demo/canvas-041.js

                  ./demo/canvas-042.js

                  ./demo/canvas-043.js

                  ./demo/canvas-044.js

                  ./demo/canvas-045.js

                  ./demo/canvas-046.js

                  ./demo/canvas-047.js

                  ./demo/canvas-048.js

                  ./demo/canvas-049.js

                  ./demo/canvas-050.js

                  ./demo/canvas-051.js

                  ./demo/canvas-052.js

                  ./demo/canvas-053.js

                  ./demo/canvas-054.js

                  ./demo/canvas-055.js

                  ./demo/core-001.js

                  ./demo/delaunator-001.js

                  ./demo/delaunator-002.js

                  ./demo/dom-001.js

                  ./demo/dom-002.js

                  ./demo/dom-003.js

                  ./demo/dom-004.js

                  ./demo/dom-005.js

                  ./demo/dom-006.js

                  ./demo/dom-007.js

                  ./demo/dom-008.js

                  ./demo/dom-009.js

                  ./demo/dom-010.js

                  ./demo/dom-011.js

                  ./demo/dom-012.js

                  ./demo/dom-013.js

                  ./demo/dom-014a.js

                  ./demo/dom-014b.js

                  ./demo/dom-014c.js

                  ./demo/dom-015.js

                  ./demo/dom-016.js

                  ./demo/filters-001.js

                  ./demo/filters-002.js

                  ./demo/filters-002a.js

                  ./demo/filters-003.js

                  ./demo/filters-004.js

                  ./demo/filters-005.js

                  ./demo/filters-006.js

                  ./demo/filters-007.js

                  ./demo/filters-008.js

                  ./demo/filters-009.js

                  ./demo/filters-010.js

                  ./demo/filters-011.js

                  ./demo/filters-012.js

                  ./demo/filters-013.js

                  ./demo/filters-014.js

                  ./demo/filters-015.js

                  ./demo/filters-016.js

                  ./demo/filters-017.js

                  ./demo/filters-018.js

                  ./demo/filters-019.js

                  ./demo/filters-020.js

                  ./demo/filters-021.js

                  ./demo/filters-022.js

                  ./demo/filters-023.js

                  ./demo/filters-501.js

                  ./demo/filters-502.js

                  ./demo/filters-503.js

                  ./demo/filters-504.js

                  ./demo/filters-505.js

                  ./demo/mediapipe-001.js

                  ./demo/mediapipe-002.js

                  ./demo/mediapipe-003.js

                  ./demo/modules-001.js

                  ./demo/modules-002.js

                  ./demo/modules-003.js

                  ./demo/packets-001.js

                  ./demo/packets-002.js

                  ./demo/particles-001.js

                  ./demo/particles-002.js

                  ./demo/particles-003.js

                  ./demo/particles-004.js

                  ./demo/particles-005.js

                  ./demo/particles-006.js

                  ./demo/particles-007.js

                  ./demo/particles-008.js

                  ./demo/particles-009.js

                  ./demo/particles-010.js

                  ./demo/particles-011.js

                  ./demo/particles-012.js

                  ./demo/particles-013.js

                  ./demo/particles-014.js

                  ./demo/particles-015.js

                  ./demo/particles-016.js

                  ./demo/snippets-001.js

                  ./demo/snippets-002.js

                  ./demo/snippets-003.js

                  ./demo/snippets-004.js

                  ./demo/temp-001.js

                  ./demo/temp-002.js

                  ./demo/temp-003.js

                  ./demo/temp-inkscapeSvgFilters.js

                  ./demo/tensorflow-001.js

                  ./demo/tensorflow-002.js

                §

Demo DOM 014 - third scene

Load and run multiple scripts on same page

                §

Run code

import scrawl from '../source/scrawl.js'

let artefact = scrawl.library.artefact,
    stack = artefact.mystack,
    element = artefact.myelement,
    canvas = artefact.mycanvas3,
    cell = canvas.base;

canvas.setAsCurrentCanvas();

stack.set({
    width: 600,
    height:400,
    perspectiveZ: 1200,
});

canvas.set({
    width: '100%',
    height:'100%',
    backgroundColor: 'black',
});

cell.set({
    width: '100%',
    height:'100%',
});

let testers = scrawl.makeGroup({

    name: 'testers',
    host: 'mystack',
});

element.set({

    group: 'testers',

    startX: 300,
    startY: 200,
    handleX: 100,
    handleY: 100,

    width: 200,
    height: 200,

    roll: 10,
    pitch: 20,
    yaw: 30,

    css: {
        borderWidth: '6px',
    },

    collides: true,
});

let baseColor = 'aliceblue',
    highlightColor = 'red',
    gridSize = 40;

let grid = scrawl.makeGroup({

    name: 'grid',
    host: cell.name,
});

for (let y = 0; y < 400; y += gridSize) {

    for (let x = 0; x < 600; x += gridSize) {

        scrawl.makeBlock({

            name: `grid-<span class="hljs-subst">${x <span class="hljs-regexp">/ gridSize}-${y /</span> gridSize}</span>`,
            group: 'grid',

            width: gridSize - 0.5,
            height: gridSize - 0.5,
            startX: x,
            startY: y,

            fillStyle: baseColor,

            method: 'fill',
        });
    }
}

scrawl.makeDragZone({

    zone: stack,
    collisionGroup: testers,
    endOn: ['up', 'leave'],
});

let checkHits = function () {

    let hits = [];

    return function () {

        hits.forEach(hit => hit.artefact.set({
            fillStyle: baseColor
        }));

        hits = grid.getArtefactCollisions(element);

        hits.forEach(hit => hit.artefact.set({
            fillStyle: highlightColor
        }));
    };
}();

let report = function () {

    let testTicker = Date.now(),
        testTime, testNow,
        testMessage = document.querySelector('#reportmessage3');

    return function () {

        testNow = Date.now();
        testTime = testNow - testTicker;
        testTicker = testNow;

        testMessage.textContent = `Animation threshhold set to 0.0
- at least 1px of the stack must be visible for the animation to run
Screen refresh: ${Math.ceil(testTime)}ms; fps: ${Math.floor(1000 / testTime)}`;
    };
}();

let animations = scrawl.makeRender({

    name: 'demo-animation3',
    target: [stack, canvas],
    afterCreated: () => element.set({ roll: 10.001 }),
    commence: checkHits,
    afterShow: report,
});

scrawl.observeAndUpdate({

    event: ['input', 'change'],
    origin: '.controlItem',

    target: element,

    useNativeListener: true,
    preventDefault: true,

    updates: {
        handle_xAbsolute: ['handleX', 'round'],
        handle_yAbsolute: ['handleY', 'round'],

        offset_xAbsolute: ['offsetX', 'round'],
        offset_yAbsolute: ['offsetY', 'round'],

        roll: ['roll', 'float'],
        pitch: ['pitch', 'float'],
        yaw: ['yaw', 'float'],
        scale: ['scale', 'float'],

        sensitivity: ['sensorSpacing', 'round'],
    },
});

scrawl.observeAndUpdate({

    event: ['input', 'change'],
    origin: '.controlItem',

    target: stack,

    useNativeListener: true,
    preventDefault: true,

    updates: {
        perspective: ['perspectiveZ', 'round'],
    },
});

                §

Setup form

document.querySelector('#sensitivity').value = 50;
document.querySelector('#handle_xAbsolute').value = 100;
document.querySelector('#handle_yAbsolute').value = 100;
document.querySelector('#offset_xAbsolute').value = 0;
document.querySelector('#offset_yAbsolute').value = 0;
document.querySelector('#roll').value = 10;
document.querySelector('#pitch').value = 20;
document.querySelector('#yaw').value = 30;
document.querySelector('#scale').value = 1;
document.querySelector('#perspective').value = 1200;

                §

Switch animation on/off when at least 1px of stack is showing - this is standard ES16 Javascript, not part of Scrawl-canvas

let observer = new IntersectionObserver((entries, observer) => {

    console.log('observer C starts', animations[0].name, animations[0].isRunning());

                §

We're only observing the stack's DOM element here, but we need to switch both the stack and the canvas animation renders on or off

    entries.forEach(entry => {

        if (entry.isIntersecting) animations.forEach(anim => !anim.isRunning() && anim.run());
        else if (!entry.isIntersecting) animations.forEach(anim => anim.isRunning() && anim.halt());
    });

    console.log('observer C completes', animations[0].name, animations[0].isRunning());

                §

The second IntersectionObserver argument is the options object

passing an empty object will set the threshold value to 0.0

which means if > 0px of the stack DOM element is visible, the animations will run

}, {});
observer.observe(stack.domElement);

console.log('#014c', scrawl.library);


text:
{% extends 'base.html' %}

{% block title %}SSR Panel 网络加速{% endblock %}

{% block css %}
    <!-- Bootstrap 3.3.2 -->
    <!--<link href="/static/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>-->
    <link href="//cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome Icons -->
    <link href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <!-- Theme style -->
    <link href="/static/css/AdminLTE.min.css" rel="stylesheet" type="text/css"/>
    <link href="/static/css/blue.css" rel="stylesheet" type="text/css"/>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="//cdn.bootcss.com/html5shiv/3.7.0/html5shiv.min.js"></script>
    <script src="//cdn.bootcss.com/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
{% endblock %}


text:
"""
viscount.file.forms

File related forms
"""

from flask_wtf import Form
from wtforms import StringField, TextAreaField, FileField
from wtforms.validators import Required, Optional

from ..services import files

__all__ = ['NewFileForm', 'UpdateFileForm']

class NewFileForm(Form):
	name = StringField('Name', validators=[Required()])
	description = TextAreaField('Description', validators=[Required()])

class UpdateFileForm(Form):
	description = TextAreaField('Description', validators=[Optional()])


text:
package org.elasticsearch.repositories.blobstore;

import com.fasterxml.jackson.core.JsonParseException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import org.apache.lucene.store.RateLimiter;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.SnapshotId;
import org.elasticsearch.common.blobstore.BlobContainer;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.blobstore.BlobMetaData;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.BlobStore;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.index.shard.IndexShardException;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.snapshots.IndexShardRepository;
import org.elasticsearch.index.snapshots.blobstore.BlobStoreIndexShardRepository;
import org.elasticsearch.index.snapshots.blobstore.BlobStoreIndexShardRepository.RateLimiterListener;
import org.elasticsearch.repositories.Repository;
import org.elasticsearch.repositories.RepositoryException;
import org.elasticsearch.repositories.RepositorySettings;
import org.elasticsearch.repositories.RepositoryVerificationException;
import org.elasticsearch.snapshots.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.NoSuchFileException;
import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
 * BlobStore - based implementation of Snapshot Repository
 *

 * This repository works with any {@link BlobStore} implementation. The blobStore should be initialized in the derived
 * class before {@link #doStart()} is called.
 *

 *

 * BlobStoreRepository maintains the following structure in the blob store
 *

 * {@code
 *   STORE_ROOT
 *   |- index             - list of all snapshot name as JSON array
 *   |- snapshot-20131010 - JSON serialized Snapshot for snapshot "20131010"
 *   |- metadata-20131010 - JSON serialized MetaData for snapshot "20131010" (includes only global metadata)
 *   |- snapshot-20131011 - JSON serialized Snapshot for snapshot "20131011"
 *   |- metadata-20131011 - JSON serialized MetaData for snapshot "20131011"
 *   .....
 *   |- indices/ - data for all indices
 *      |- foo/ - data for index "foo"
 *      |  |- snapshot-20131010 - JSON Serialized IndexMetaData for index "foo"
 *      |  |- 0/ - data for shard "0" of index "foo"
 *      |  |  |- __1 \
 *      |  |  |- __2 |
 *      |  |  |- __3 |- files from different segments see snapshot-* for their mappings to real segment files
 *      |  |  |- __4 |
 *      |  |  |- __5 /
 *      |  |  .....
 *      |  |  |- snapshot-20131010 - JSON serialized BlobStoreIndexShardSnapshot for snapshot "20131010"
 *      |  |  |- snapshot-20131011 - JSON serialized BlobStoreIndexShardSnapshot for snapshot "20131011"
 *      |  |
 *      |  |- 1/ - data for shard "1" of index "foo"
 *      |  |  |- __1
 *      |  |  .....
 *      |  |
 *      |  |-2/
 *      |  ......
 *      |
 *      |- bar/ - data for index bar
 *      ......
 * }
 *

 */
public abstract class BlobStoreRepository extends AbstractLifecycleComponent<Repository> implements Repository, RateLimiterListener {

    private BlobContainer snapshotsBlobContainer;

    protected final String repositoryName;

    private static final String SNAPSHOT_PREFIX = "snapshot-";

    private static final String TEMP_SNAPSHOT_FILE_PREFIX = "pending-";

    private static final String SNAPSHOTS_FILE = "index";

    private static final String TESTS_FILE = "tests-";

    private static final String METADATA_PREFIX = "metadata-";

    private final BlobStoreIndexShardRepository indexShardRepository;

    private final ToXContent.Params snapshotOnlyFormatParams;

    private final RateLimiter snapshotRateLimiter;

    private final RateLimiter restoreRateLimiter;

    private final CounterMetric snapshotRateLimitingTimeInNanos = new CounterMetric();

    private final CounterMetric restoreRateLimitingTimeInNanos = new CounterMetric();

    /**
     * Constructs new BlobStoreRepository
     *
     * @param repositoryName       repository name
     * @param repositorySettings   repository settings
     * @param indexShardRepository an instance of IndexShardRepository
     */
    protected BlobStoreRepository(String repositoryName, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) {
        super(repositorySettings.globalSettings());
        this.repositoryName = repositoryName;
        this.indexShardRepository = (BlobStoreIndexShardRepository) indexShardRepository;
        Map<String, String> snpashotOnlyParams = Maps.newHashMap();
        snpashotOnlyParams.put(MetaData.CONTEXT_MODE_PARAM, MetaData.CONTEXT_MODE_SNAPSHOT);
        snapshotOnlyFormatParams = new ToXContent.MapParams(snpashotOnlyParams);
        snapshotRateLimiter = getRateLimiter(repositorySettings, "max_snapshot_bytes_per_sec", new ByteSizeValue(20, ByteSizeUnit.MB));
        restoreRateLimiter = getRateLimiter(repositorySettings, "max_restore_bytes_per_sec", new ByteSizeValue(20, ByteSizeUnit.MB));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doStart() throws ElasticsearchException {

        this.snapshotsBlobContainer = blobStore().blobContainer(basePath());
        indexShardRepository.initialize(blobStore(), basePath(), chunkSize(), snapshotRateLimiter, restoreRateLimiter, this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doStop() throws ElasticsearchException {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doClose() throws ElasticsearchException {
        try {
            blobStore().close();
        } catch (Throwable t) {
            logger.warn("cannot close blob store", t);
        }
    }

    /**
     * Returns initialized and ready to use BlobStore
     *

     * This method is first called in the {@link #doStart()} method.
     *
     * @return blob store
     */
    abstract protected BlobStore blobStore();

    /**
     * Returns base path of the repository
     */
    abstract protected BlobPath basePath();

    /**
     * Returns true if metadata and snapshot files should be compressed
     *
     * @return true if compression is needed
     */
    protected boolean isCompress() {
        return false;
    }

    /**
     * Returns data file chunk size.
     *

     * This method should return null if no chunking is needed.
     *
     * @return chunk size
     */
    protected ByteSizeValue chunkSize() {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initializeSnapshot(SnapshotId snapshotId, ImmutableList<String> indices, MetaData metaData) {
        try {
            String snapshotBlobName = snapshotBlobName(snapshotId);
            if (snapshotsBlobContainer.blobExists(snapshotBlobName)) {
                throw new InvalidSnapshotNameException(snapshotId, "snapshot with such name already exists");
            }
            // Write Global MetaData
            // TODO: Check if metadata needs to be written
            try (OutputStream output = snapshotsBlobContainer.createOutput(metaDataBlobName(snapshotId))) {
                writeGlobalMetaData(metaData, output);
            }
            for (String index : indices) {
                final IndexMetaData indexMetaData = metaData.index(index);
                final BlobPath indexPath = basePath().add("indices").add(index);
                final BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
                try (OutputStream output = indexMetaDataBlobContainer.createOutput(snapshotBlobName(snapshotId))) {
                    StreamOutput stream = new OutputStreamStreamOutput(output);
                    if (isCompress()) {
                        stream = CompressorFactory.defaultCompressor().streamOutput(stream);
                    }
                    XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
                    builder.startObject();
                    IndexMetaData.Builder.toXContent(indexMetaData, builder, ToXContent.EMPTY_PARAMS);
                    builder.endObject();
                    builder.close();
                }
            }
        } catch (IOException ex) {
            throw new SnapshotCreationException(snapshotId, ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteSnapshot(SnapshotId snapshotId) {
        ImmutableList<String> indices = ImmutableList.of();
        try {
            indices = readSnapshot(snapshotId).indices();
        } catch (SnapshotMissingException ex) {
            throw ex;
        } catch (SnapshotException | ElasticsearchParseException ex) {
            logger.warn("cannot read snapshot file [{}]", ex, snapshotId);
        }
        MetaData metaData = null;
        try {
            metaData = readSnapshotMetaData(snapshotId, indices, true);
        } catch (IOException | SnapshotException ex) {
            logger.warn("cannot read metadata for snapshot [{}]", ex, snapshotId);
        }
        try {
            String blobName = snapshotBlobName(snapshotId);
            // Delete snapshot file first so we wouldn't end up with partially deleted snapshot that looks OK
            snapshotsBlobContainer.deleteBlob(blobName);
            snapshotsBlobContainer.deleteBlob(metaDataBlobName(snapshotId));
            // Delete snapshot from the snapshot list
            ImmutableList<SnapshotId> snapshotIds = snapshots();
            if (snapshotIds.contains(snapshotId)) {
                ImmutableList.Builder<SnapshotId> builder = ImmutableList.builder();
                for (SnapshotId id : snapshotIds) {
                    if (!snapshotId.equals(id)) {
                        builder.add(id);
                    }
                }
                snapshotIds = builder.build();
            }
            writeSnapshotList(snapshotIds);
            // Now delete all indices
            for (String index : indices) {
                BlobPath indexPath = basePath().add("indices").add(index);
                BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
                try {
                    indexMetaDataBlobContainer.deleteBlob(blobName);
                } catch (IOException ex) {
                    logger.warn("[{}] failed to delete metadata for index [{}]", ex, snapshotId, index);
                }
                if (metaData != null) {
                    IndexMetaData indexMetaData = metaData.index(index);
                    if (indexMetaData != null) {
                        for (int i = 0; i < indexMetaData.getNumberOfShards(); i++) {
                            ShardId shardId = new ShardId(index, i);
                            try {
                                indexShardRepository.delete(snapshotId, shardId);
                            } catch (IndexShardException | SnapshotException ex) {
                                logger.warn("[{}] failed to delete shard data for shard [{}]", ex, snapshotId, shardId);
                            }
                        }
                    }
                }
            }
        } catch (IOException ex) {
            throw new RepositoryException(this.repositoryName, "failed to update snapshot in repository", ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Snapshot finalizeSnapshot(SnapshotId snapshotId, ImmutableList<String> indices, long startTime, String failure, int totalShards, ImmutableList<SnapshotShardFailure> shardFailures) {
        try {
            String tempBlobName = tempSnapshotBlobName(snapshotId);
            String blobName = snapshotBlobName(snapshotId);
            Snapshot blobStoreSnapshot = new Snapshot(snapshotId.getSnapshot(), indices, startTime, failure, System.currentTimeMillis(), totalShards, shardFailures);
            try (OutputStream output = snapshotsBlobContainer.createOutput(tempBlobName)) {
                writeSnapshot(blobStoreSnapshot, output);
            }
            snapshotsBlobContainer.move(tempBlobName, blobName);
            ImmutableList<SnapshotId> snapshotIds = snapshots();
            if (!snapshotIds.contains(snapshotId)) {
                snapshotIds = ImmutableList.<SnapshotId>builder().addAll(snapshotIds).add(snapshotId).build();
            }
            writeSnapshotList(snapshotIds);
            return blobStoreSnapshot;
        } catch (IOException ex) {
            throw new RepositoryException(this.repositoryName, "failed to update snapshot in repository", ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ImmutableList<SnapshotId> snapshots() {
        try {
            List<SnapshotId> snapshots = newArrayList();
            ImmutableMap<String, BlobMetaData> blobs;
            try {
                blobs = snapshotsBlobContainer.listBlobsByPrefix(SNAPSHOT_PREFIX);
            } catch (UnsupportedOperationException ex) {
                // Fall back in case listBlobsByPrefix isn't supported by the blob store
                return readSnapshotList();
            }
            int prefixLength = SNAPSHOT_PREFIX.length();
            for (BlobMetaData md : blobs.values()) {
                String name = md.name().substring(prefixLength);
                snapshots.add(new SnapshotId(repositoryName, name));
            }
            return ImmutableList.copyOf(snapshots);
        } catch (IOException ex) {
            throw new RepositoryException(repositoryName, "failed to list snapshots in repository", ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public MetaData readSnapshotMetaData(SnapshotId snapshotId, ImmutableList<String> indices) throws IOException {
        return readSnapshotMetaData(snapshotId, indices, false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Snapshot readSnapshot(SnapshotId snapshotId) {
        try {
            try (InputStream blob = snapshotsBlobContainer.openInput(snapshotBlobName(snapshotId))) {
                return readSnapshot(ByteStreams.toByteArray(blob));
            }
        } catch (FileNotFoundException | NoSuchFileException ex) {
            throw new SnapshotMissingException(snapshotId, ex);
        } catch (IOException ex) {
            throw new SnapshotException(snapshotId, "failed to get snapshots", ex);
        }
    }

    private MetaData readSnapshotMetaData(SnapshotId snapshotId, ImmutableList<String> indices, boolean ignoreIndexErrors) throws IOException {
        MetaData metaData;
        try (InputStream blob = snapshotsBlobContainer.openInput(metaDataBlobName(snapshotId))) {
            byte[] data = ByteStreams.toByteArray(blob);
            metaData = readMetaData(data);
        } catch (FileNotFoundException | NoSuchFileException ex) {
            throw new SnapshotMissingException(snapshotId, ex);
        } catch (IOException ex) {
            throw new SnapshotException(snapshotId, "failed to get snapshots", ex);
        }
        MetaData.Builder metaDataBuilder = MetaData.builder(metaData);
        for (String index : indices) {
            BlobPath indexPath = basePath().add("indices").add(index);
            BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
            try (InputStream blob = indexMetaDataBlobContainer.openInput(snapshotBlobName(snapshotId))) {
                byte[] data = ByteStreams.toByteArray(blob);
                try (XContentParser parser = XContentHelper.createParser(data, 0, data.length)) {
                    XContentParser.Token token;
                    if ((token = parser.nextToken()) == XContentParser.Token.START_OBJECT) {
                        IndexMetaData indexMetaData = IndexMetaData.Builder.fromXContent(parser);
                        if ((token = parser.nextToken()) == XContentParser.Token.END_OBJECT) {
                            metaDataBuilder.put(indexMetaData, false);
                            continue;
                        }
                    }
                    if (!ignoreIndexErrors) {
                        throw new ElasticsearchParseException("unexpected token  [" + token + "]");
                    } else {
                        logger.warn("[{}] [{}] unexpected token while reading snapshot metadata [{}]", snapshotId, index, token);
                    }
                }
            } catch (IOException ex) {
                if (!ignoreIndexErrors) {
                    throw new SnapshotException(snapshotId, "failed to read metadata", ex);
                } else {
                    logger.warn("[{}] [{}] failed to read metadata for index", snapshotId, index, ex);
                }
            }
        }
        return metaDataBuilder.build();
    }

    /**
     * Configures RateLimiter based on repository and global settings
     *
     * @param repositorySettings repository settings
     * @param setting            setting to use to configure rate limiter
     * @param defaultRate        default limiting rate
     * @return rate limiter or null of no throttling is needed
     */
    private RateLimiter getRateLimiter(RepositorySettings repositorySettings, String setting, ByteSizeValue defaultRate) {
        ByteSizeValue maxSnapshotBytesPerSec = repositorySettings.settings().getAsBytesSize(setting,
                settings.getAsBytesSize(setting, defaultRate));
        if (maxSnapshotBytesPerSec.bytes() <= 0) {
            return null;
        } else {
            return new RateLimiter.SimpleRateLimiter(maxSnapshotBytesPerSec.mbFrac());
        }
    }

    /**
     * Parses JSON containing snapshot description
     *
     * @param data snapshot description in JSON format
     * @return parsed snapshot description
     * @throws IOException parse exceptions
     */
    public Snapshot readSnapshot(byte[] data) throws IOException {
        try (XContentParser parser = XContentHelper.createParser(data, 0, data.length)) {
            XContentParser.Token token;
            if ((token = parser.nextToken()) == XContentParser.Token.START_OBJECT) {
                if ((token = parser.nextToken()) == XContentParser.Token.FIELD_NAME) {
                    parser.nextToken();
                    Snapshot snapshot = Snapshot.fromXContent(parser);
                    if ((token = parser.nextToken()) == XContentParser.Token.END_OBJECT) {
                        return snapshot;
                    }
                }
            }
            throw new ElasticsearchParseException("unexpected token  [" + token + "]");
        } catch (JsonParseException ex) {
            throw new ElasticsearchParseException("failed to read snapshot", ex);
        }
    }

    /**
     * Parses JSON containing cluster metadata
     *
     * @param data cluster metadata in JSON format
     * @return parsed metadata
     * @throws IOException parse exceptions
     */
    private MetaData readMetaData(byte[] data) throws IOException {
        try (XContentParser parser = XContentHelper.createParser(data, 0, data.length)) {
            XContentParser.Token token;
            if ((token = parser.nextToken()) == XContentParser.Token.START_OBJECT) {
                if ((token = parser.nextToken()) == XContentParser.Token.FIELD_NAME) {
                    parser.nextToken();
                    MetaData metaData = MetaData.Builder.fromXContent(parser);
                    if ((token = parser.nextToken()) == XContentParser.Token.END_OBJECT) {
                        return metaData;
                    }
                }
            }
            throw new ElasticsearchParseException("unexpected token  [" + token + "]");
        }
    }

    /**
     * Returns name of snapshot blob
     *
     * @param snapshotId snapshot id
     * @return name of snapshot blob
     */
    private String snapshotBlobName(SnapshotId snapshotId) {
        return SNAPSHOT_PREFIX + snapshotId.getSnapshot();
    }

    /**
     * Returns temporary name of snapshot blob
     *
     * @param snapshotId snapshot id
     * @return name of snapshot blob
     */
    private String tempSnapshotBlobName(SnapshotId snapshotId) {
        return TEMP_SNAPSHOT_FILE_PREFIX + snapshotId.getSnapshot();
    }

    /**
     * Returns name of metadata blob
     *
     * @param snapshotId snapshot id
     * @return name of metadata blob
     */
    private String metaDataBlobName(SnapshotId snapshotId) {
        return METADATA_PREFIX + snapshotId.getSnapshot();
    }

    /**
     * Serializes Snapshot into JSON
     *
     * @param snapshot - snapshot description
     * @return BytesStreamOutput representing JSON serialized Snapshot
     * @throws IOException
     */
    private void writeSnapshot(Snapshot snapshot, OutputStream outputStream) throws IOException {
        StreamOutput stream = new OutputStreamStreamOutput(outputStream);
        if (isCompress()) {
            stream = CompressorFactory.defaultCompressor().streamOutput(stream);
        }
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
        builder.startObject();
        snapshot.toXContent(builder, snapshotOnlyFormatParams);
        builder.endObject();
        builder.flush();
    }

    /**
     * Serializes global MetaData into JSON
     *
     * @param metaData - metaData
     * @return BytesStreamOutput representing JSON serialized global MetaData
     * @throws IOException
     */
    private void writeGlobalMetaData(MetaData metaData, OutputStream outputStream) throws IOException {
        StreamOutput stream = new OutputStreamStreamOutput(outputStream);
        if (isCompress()) {
            stream = CompressorFactory.defaultCompressor().streamOutput(stream);
        }
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
        builder.startObject();
        MetaData.Builder.toXContent(metaData, builder, snapshotOnlyFormatParams);
        builder.endObject();
        builder.flush();
    }

    /**
     * Writes snapshot index file
     *

     * This file can be used by read-only repositories that are unable to list files in the repository
     *
     * @param snapshots list of snapshot ids
     * @throws IOException I/O errors
     */
    protected void writeSnapshotList(ImmutableList<SnapshotId> snapshots) throws IOException {
        BytesStreamOutput bStream = new BytesStreamOutput();
        StreamOutput stream = bStream;
        if (isCompress()) {
            stream = CompressorFactory.defaultCompressor().streamOutput(stream);
        }
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON, stream);
        builder.startObject();
        builder.startArray("snapshots");
        for (SnapshotId snapshot : snapshots) {
            builder.value(snapshot.getSnapshot());
        }
        builder.endArray();
        builder.endObject();
        builder.close();
        BytesReference bRef = bStream.bytes();
        try (OutputStream output = snapshotsBlobContainer.createOutput(SNAPSHOTS_FILE)) {
            bRef.writeTo(output);
        }
    }

    /**
     * Reads snapshot index file
     *

     * This file can be used by read-only repositories that are unable to list files in the repository
     *
     * @return list of snapshots in the repository
     * @throws IOException I/O errors
     */
    protected ImmutableList<SnapshotId> readSnapshotList() throws IOException {
        try (InputStream blob = snapshotsBlobContainer.openInput(SNAPSHOTS_FILE)) {
            final byte[] data = ByteStreams.toByteArray(blob);
            ArrayList<SnapshotId> snapshots = new ArrayList<>();
            try (XContentParser parser = XContentHelper.createParser(data, 0, data.length)) {
                if (parser.nextToken() == XContentParser.Token.START_OBJECT) {
                    if (parser.nextToken() == XContentParser.Token.FIELD_NAME) {
                        String currentFieldName = parser.currentName();
                        if ("snapshots".equals(currentFieldName)) {
                            if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
                                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                                    snapshots.add(new SnapshotId(repositoryName, parser.text()));
                                }
                            }
                        }
                    }
                }
            }
            return ImmutableList.copyOf(snapshots);
        }
    }

    @Override
    public void onRestorePause(long nanos) {
        restoreRateLimitingTimeInNanos.inc(nanos);
    }

    @Override
    public void onSnapshotPause(long nanos) {
        snapshotRateLimitingTimeInNanos.inc(nanos);
    }

    @Override
    public long snapshotThrottleTimeInNanos() {
        return snapshotRateLimitingTimeInNanos.count();
    }

    @Override
    public long restoreThrottleTimeInNanos() {
        return restoreRateLimitingTimeInNanos.count();
    }

    @Override
    public String startVerification() {
        try {
            String seed = Strings.randomBase64UUID();
            byte[] testBytes = Strings.toUTF8Bytes(seed);
            String blobName = testBlobPrefix(seed) + "-master";
            try (OutputStream outputStream = snapshotsBlobContainer.createOutput(blobName + "-temp")) {
                outputStream.write(testBytes);
            }
            // Make sure that move is supported
            snapshotsBlobContainer.move(blobName + "-temp", blobName);
            return seed;
        } catch (IOException exp) {
            throw new RepositoryVerificationException(repositoryName, "path " + basePath() + " is not accessible on master node", exp);
        }
    }

    @Override
    public void endVerification(String seed) {
        try {
            snapshotsBlobContainer.deleteBlobsByPrefix(testBlobPrefix(seed));
        } catch (IOException exp) {
            throw new RepositoryVerificationException(repositoryName, "cannot delete test data at " + basePath(), exp);
        }
    }

    public static String testBlobPrefix(String seed) {
        return TESTS_FILE + seed;
    }
}


text:
{% extends 'layout/admin/base.html' %}
{% from 'macros/admin.html' import render_backlink %}
{% from 'macros/forms.html' import form_buttons, form_field %}
{% set current_page = 'orga_team_admin.teams' %}
{% set current_page_party = party %}
{% set page_title = _('Copy orga teams') %}

{% block before_body %}
{{ render_backlink(url_for('.teams_for_party', party_id=party.id), 'Teams "%s"'|format(party.title)) }}
{%- endblock %}

{% block body %}

{{ _('Copy orga teams from another party') }}

  <form action="{{ url_for('.teams_copy', target_party_id=party.id) }}" method="post">

      {{ form_field(form.party_id, autofocus='autofocus') }}

    {{ form_buttons(_('Copy')) }}
  </form>

{%- endblock %}


text:
package net.daw.dao.implementation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.implementation.PusuarioBean;
import net.daw.bean.implementation.TipomiembroBean;
import net.daw.dao.publicinterface.TableDaoInterface;
import net.daw.dao.publicinterface.ViewDaoInterface;
import net.daw.data.implementation.MysqlData;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.SqlBuilder;

public class TipomiembroDao implements ViewDaoInterface<TipomiembroBean>, TableDaoInterface<TipomiembroBean> {

    private String strTable = "tipomiembro";
//    private String strSQL = "select * from " + strTable + " where 1=1 ";
    private String strSQL = "SELECT *, (SELECT count(*) FROM miembro WHERE id_tipomiembro = tipomiembro.id) AS total FROM tipomiembro where 1=1 ";
    private String strSQLCount = "SELECT COUNT(*) FROM " + strTable + " WHERE 1=1 ";
    private MysqlData oMysql = null;
    private Connection oConnection = null;
    private PusuarioBean oPuserSecurity = null;

    public TipomiembroDao(Connection oPooledConnection, PusuarioBean oPuserBean_security, String strWhere) throws Exception {
        try {
            oConnection = oPooledConnection;
            oMysql = new MysqlData(oConnection);
            oPuserSecurity = oPuserBean_security;
            if (strWhere != null) {
                strSQL += strWhere;
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
    }

    @Override
    public Long getCount(ArrayList<FilterBeanHelper> hmFilter) throws Exception {
        strSQLCount += SqlBuilder.buildSqlWhere(hmFilter);
        Long pages = 0L;
        try {
            pages = oMysql.getCount(strSQLCount);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return pages;
    }

    @Override
    public ArrayList<TipomiembroBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        strSQL += SqlBuilder.buildSqlLimit(oMysql.getCount(strSQLCount), intRegsPerPag, intPage);
        ArrayList<TipomiembroBean> arrUsertype = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                TipomiembroBean oUsertypeBean = new TipomiembroBean();
                arrUsertype.add(oUsertypeBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
            if (oResultSet != null) {
                oResultSet.close();
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrUsertype;
    }

    @Override
    public ArrayList<TipomiembroBean> getAll(ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        ArrayList<TipomiembroBean> arrUsertype = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                TipomiembroBean oUsertypeBean = new TipomiembroBean();
                arrUsertype.add(oUsertypeBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrUsertype;
    }

    @Override
    public TipomiembroBean get(TipomiembroBean oUsertypeBean, Integer expand) throws Exception {
        if (oUsertypeBean.getId() > 0) {
            ResultSet oResultSet = null;
            try {
                oResultSet = oMysql.getAllSQL(strSQL + " And id= " + oUsertypeBean.getId() + " ");
                Boolean empty = true;
                while (oResultSet.next()) {
                    oUsertypeBean = oUsertypeBean.fill(oResultSet, oConnection, oPuserSecurity, expand);
                    empty = false;
                }
                if (empty) {
                    oUsertypeBean.setId(0);
                }
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oResultSet != null) {
                    oResultSet.close();
                }
            }
        } else {
            oUsertypeBean.setId(0);
        }
        return oUsertypeBean;
    }

    @Override
    public Integer set(TipomiembroBean oUsertypeBean) throws Exception {
        Integer iResult = null;
        try {
            if (oUsertypeBean.getId() == 0) {
                strSQL = "INSERT INTO " + strTable + " ";
                strSQL += "(" + oUsertypeBean.getColumns() + ")";
                strSQL += "VALUES(" + oUsertypeBean.getValues() + ")";
                iResult = oMysql.executeInsertSQL(strSQL);
            } else {
                strSQL = "UPDATE " + strTable + " ";
                strSQL += " SET " + oUsertypeBean.toPairs();
                strSQL += " WHERE id=" + oUsertypeBean.getId();
                iResult = oMysql.executeUpdateSQL(strSQL);
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return iResult;
    }

    @Override
    public Integer remove(Integer id) throws Exception {
        int result = 0;
        try {
            result = oMysql.removeOne(id, strTable);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return result;
    }

}


text:
package org.apache.commons.io.function;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.concurrent.atomic.AtomicReference;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Tests {@link IOSupplier}.
 */
public class IOSupplierTest {

    private AtomicReference<String> ref1;

    private String getThrows(final IOSupplier<String> supplier) throws IOException {
        return supplier.get();
    }

    private String getThrowsNone(final IOSupplier<String> supplier) {
        return supplier.asSupplier().get();
    }

    @BeforeEach
    public void initEach() {
        ref1 = new AtomicReference<>();
    }

    @Test
    public void testAsSupplier() {
        assertThrows(UncheckedIOException.class, () -> TestConstants.THROWING_IO_SUPPLIER.asSupplier().get());
        assertEquals("new1", getThrowsNone(() -> TestUtils.compareAndSetThrowsIO(ref1, "new1")));
        assertEquals("new1", ref1.get());
        assertNotEquals(TestConstants.THROWING_IO_SUPPLIER.asSupplier(), TestConstants.THROWING_IO_SUPPLIER.asSupplier());
    }

    @Test
    public void testGet() throws IOException {
        assertThrows(IOException.class, () -> TestConstants.THROWING_IO_SUPPLIER.get());
        assertThrows(IOException.class, () -> {
            throw new IOException();
        });
        assertEquals("new1", getThrows(() -> TestUtils.compareAndSetThrowsIO(ref1, "new1")));
        assertEquals("new1", ref1.get());
    }

}


text:
ts:=$(shell date '+%Y%m%d%H%M%S')
name=debian
vendor=tmaczukin
tag=jessie
imageName=$(vendor)/$(name)

build: Dockerfile
	@docker pull debian:jessie
	@docker build --rm -t $(imageName):$(tag) .
	@docker tag -f $(imageName):$(tag) $(imageName):latest

ubuild: update build

update: Dockerfile
	@sed -i 's/# update_[0-9]*/# update_$(ts)/' Dockerfile


text:
// Copyright (c) 2016 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using LfMerge.Core.LanguageForge.Infrastructure;
using System.Collections.Generic;

namespace LfMerge.Core.Tests
{
	public class LanguageForgeProxyMock: ILanguageForgeProxy
	{
		#region ILanguageForgeProxy implementation

		public string UpdateCustomFieldViews(string projectCode, List<CustomFieldSpec> customFieldSpecs)
		{
			return UpdateCustomFieldViews(projectCode, customFieldSpecs, false);
		}

		public string UpdateCustomFieldViews(string projectCode, List<CustomFieldSpec> customFieldSpecs, bool isTest)
		{
			return "true";
		}

		public string ListUsers()
		{
			return null;
		}

		#endregion
	}
}


text:
@implementation YBIBImageLayout

#pragma mark - life cycle

- (instancetype)init {
    self = [super init];
    if (self) {
        _verticalFillType = YBIBImageFillTypeCompletely;
        _horizontalFillType = YBIBImageFillTypeFullWidth;
        _zoomScaleSurplus = 1.5;
    }
    return self;
}

#pragma mark - private

- (YBIBImageFillType)fillTypeByOrientation:(UIDeviceOrientation)orientation {
    return UIDeviceOrientationIsLandscape(orientation) ? self.horizontalFillType : self.verticalFillType;
}

#pragma mark - <YBIBImageLayout>

- (CGRect)yb_imageViewFrameWithContainerSize:(CGSize)containerSize imageSize:(CGSize)imageSize orientation:(UIDeviceOrientation)orientation {
    if (containerSize.width <= 0 || containerSize.height <= 0 || imageSize.width <= 0 || imageSize.height <= 0) return CGRectZero;

    CGFloat x = 0, y = 0, width = 0, height = 0;
    switch ([self fillTypeByOrientation:orientation]) {
        case YBIBImageFillTypeFullWidth: {
            x = 0;
            width = containerSize.width;
            height = containerSize.width * (imageSize.height / imageSize.width);
            if (imageSize.width / imageSize.height >= containerSize.width / containerSize.height)
                y = (containerSize.height - height) / 2.0;
            else
                y = 0;
        }
            break;
        case YBIBImageFillTypeCompletely: {
            if (imageSize.width / imageSize.height >= containerSize.width / containerSize.height) {
                width = containerSize.width;
                height = containerSize.width * (imageSize.height / imageSize.width);
                x = 0;
                y = (containerSize.height - height) / 2.0;
            } else {
                height = containerSize.height;
                width = containerSize.height * (imageSize.width / imageSize.height);
                x = (containerSize.width - width) / 2.0;
                y = 0;
            }
        }
            break;
        default: return CGRectZero;
    }
    return CGRectMake(x, y, width, height);
}

- (CGFloat)yb_maximumZoomScaleWithContainerSize:(CGSize)containerSize imageSize:(CGSize)imageSize orientation:(UIDeviceOrientation)orientation {
    if (self.maxZoomScale >= 1) return self.maxZoomScale;

    if (containerSize.width <= 0 || containerSize.height <= 0) return 0;

    CGFloat scale = [UIScreen mainScreen].scale;
    if (scale <= 0) return 0;

    CGFloat widthScale = imageSize.width / scale / containerSize.width,
    heightScale = imageSize.height / scale / containerSize.height,
    maxScale = 1;
    switch ([self fillTypeByOrientation:orientation]) {
        case YBIBImageFillTypeFullWidth:
            maxScale = widthScale;
            break;
        case YBIBImageFillTypeCompletely:
            maxScale = MAX(widthScale, heightScale);
            break;
        default: return 0;
    }
    return MAX(maxScale, 1) * self.zoomScaleSurplus;
}

@end


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="finite.state_machine.class">Finite\StateMachine\StateMachine</parameter>
        <parameter key="finite.array_loader.class">Finite\Loader\ArrayLoader</parameter>
        <parameter key="finite.factory.class">Finite\Factory\SymfonyDependencyInjectionFactory</parameter>
        <parameter key="finite.context.class">Finite\Context</parameter>
        <parameter key="finite.twig_extension.class">Finite\Extension\Twig\FiniteExtension</parameter>
        <parameter key="finite.callback.handler.class">Finite\Event\CallbackHandler</parameter>
        <parameter key="finite.callback.builder.factory.class">Finite\Event\Callback\CallbackBuilderFactory</parameter>
        <parameter key="finite.state_machine_dispatcher.class">Finite\Event\StateMachineDispatcher</parameter>
    </parameters>

    <services>
        <service id="finite.callback.handler" class="%finite.callback.handler.class%">
            <argument type="service" id="finite.state_machine_dispatcher" />
        </service>
        <service id="finite.callback.builder.factory" class="%finite.callback.builder.factory.class%" />
        <service id="finite.array_loader" class="%finite.array_loader.class%" public="false">
            <argument type="collection" />
            <argument type="service" id="finite.callback.handler" />
            <argument type="service" id="finite.callback.builder.factory" />
        </service>
        <service id="finite.state_machine_dispatcher" class="%finite.state_machine_dispatcher.class%">
            <argument type="service" id="event_dispatcher" />
        </service>
        <service id="finite.state_machine" class="%finite.state_machine.class%" public="true">
            <!-- shared="false" is defined in DependencyInjection extension as Symfony < 2.8 needs scope="prototype" -->
            <call method="setDispatcher">
                <argument type="service" id="finite.state_machine_dispatcher" />
            </call>
        </service>
        <service id="finite.factory" class="%finite.factory.class%" public="true">
            <argument type="service" id="service_container" />
            <argument>finite.state_machine</argument>
        </service>
        <service id="finite.context" class="%finite.context.class%" public="true">
            <argument type="service" id="finite.factory" />
        </service>
        <service id="finite.twig_extension" class="%finite.twig_extension.class%" public="false">
            <argument type="service" id="finite.context" />
            <tag name="twig.extension" />
        </service>
    </services>

</container>


text:
package com.alibaba.wasp.ipc;

import java.io.IOException;

public class ServerNotRunningYetException extends IOException {

  private static final long serialVersionUID = -1037907015006723006L;

  public ServerNotRunningYetException(String s) {
    super(s);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

using DotNetNuke.Common;
using DotNetNuke.Entities.Controllers;

#endregion

namespace DotNetNuke.Entities.Urls
{
    public class RewriterUtils
    {
        internal static readonly Regex ServicesFrameworkRegex = new Regex("DesktopModules/.+/API/", RegexOptions.Compiled);

        internal static void RewriteUrl(HttpContext context, string sendToUrl)
        {
            //first strip the querystring, if any
            var queryString = string.Empty;
            string sendToUrlLessQString = sendToUrl;
            if ((sendToUrl.IndexOf("?", StringComparison.Ordinal) > 0))
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?", StringComparison.Ordinal));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf("?", StringComparison.Ordinal) + 1);

                //Encode querystring values to support unicode characters by M.Kermani
                var parameters = new List<string>();
                foreach (var parameter in queryString.Split('&'))
                {
                    var i = parameter.IndexOf('=');
                    if (i >= 0)
                    {
                        var value = HttpUtility.UrlEncode(HttpUtility.UrlDecode(parameter.Substring(i + 1)));
                        parameters.Add(parameter.Substring(0, i) + "=" + value);
                    }
                    else
                    {
                        parameters.Add(parameter);
                    }
                }
                queryString = String.Join("&", parameters);

            }

            //rewrite the path..
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
            //NOTE!  The above RewritePath() overload is only supported in the .NET Framework 1.1
            //If you are using .NET Framework 1.0, use the below form instead:
            //context.RewritePath(sendToUrl);
        }

        internal static string ResolveUrl(string appPath, string url)
        {
            //String is Empty, just return Url
            if (String.IsNullOrEmpty(url))
            {
                return url;
            }

            //String does not contain a ~, so just return Url
            if ((url.StartsWith("~") == false))
            {
                return url;
            }

            //There is just the ~ in the Url, return the appPath
            if ((url.Length == 1))
            {
                return appPath;
            }
            var seperatorChar = url.ToCharArray()[1];
            if (seperatorChar == '/' || seperatorChar == '\\')
            {
                //Url looks like ~/ or ~\
                if ((appPath.Length > 1))
                {
                    return appPath + "/" + url.Substring(2);
                }
                return "/" + url.Substring(2);
            }
            //Url look like ~something
            if ((appPath.Length > 1))
            {
                return appPath + "/" + url.Substring(1);
            }
            return appPath + url.Substring(1);
        }

        static internal bool OmitFromRewriteProcessing(string localPath)
        {
            var omitSettings = String.Empty;
            if (Globals.Status == Globals.UpgradeStatus.None)
            {
                omitSettings = HostController.Instance.GetString("OmitFromRewriteProcessing");
            }

            if (string.IsNullOrEmpty(omitSettings)) {
		        omitSettings = "scriptresource.axd|webresource.axd|gif|ico|jpg|jpeg|png|css|js";
	        }
	        omitSettings = omitSettings.ToLower();
	        localPath = localPath.ToLower();

	        var omissions = omitSettings.Split(new[] { '|' });

            bool shouldOmit = omissions.Any(x => localPath.EndsWith(x));

            if(!shouldOmit)
            {
                shouldOmit = ServicesFrameworkRegex.IsMatch(localPath);
            }

            return shouldOmit;
        }
    }
}


text:
import DefaultTheme from "vitepress/theme";
import {Tabs, Tab} from 'vue3-tabs-component';
import Codeblock from "./components/Codeblock.vue";
import "./tabs.css";
import "./custom.css";

export default {
    ...DefaultTheme,
    enhanceApp({ app, router, siteData }) {
        app.component('tabs', Tabs);
        app.component('tab', Tab);
        app.component('codeblock', Codeblock);
    },
};


text:
function [outputlabel, outputindex] = inputlabel2outputlabel(cfg, freq)

% INPUTLABEL2OUTPUTLABEL is a subfunction which outputs the cell-arrays
% outputlabel and the corresponding outputindex, and defines how the
% channels in the original data have to be combined, to provide the
% wished for combination of the channels, as defined in cfg.combinechan
%
% Configuration-options are:
%   cfg.combinechan = 'planar' combines the horizontal and vertical planar-gradients
%                     'pseudomeg' one gradiometer versus the rest
%   TODO: more flexible way of combining, e.g. by providing a cell-array

% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: inputlabel2outputlabel.m 7123 2012-12-06 21:21:38Z roboos $

if ~isfield(cfg, 'combinechan'), cfg.combinechan = 'no'; end;

if strcmp(cfg.combinechan, 'no')
  % the output labels are similar to the input labels
  outputlabel = {};
  outputindex = {};
  for i=1:length(freq.label)
    outputindex{i} = i;
    outputlabel(i) = freq.label(i);
  end
elseif strcmp(cfg.combinechan, 'planar')
  % find the combination of horizontal and vertical channels that should be combined
  planar      = planarchannelset(freq);
  [sel_dH, H] = match_str(freq.label, planar(:,1));  % indices of the horizontal channels
  [sel_dV, V] = match_str(freq.label, planar(:,2));  % indices of the vertical   channels
  lab_dH      = freq.label(sel_dH);
  lab_dV      = freq.label(sel_dV);

  if length(sel_dH)~=length(sel_dV)
    [int,ih,iv] = intersect(H,V);
    sel_dH = sel_dH(ih);
    sel_dV = sel_dV(iv);
    %error('not all planar channel combinations are complete')
  else
    ih  = 1:length(sel_dH);
    iv  = 1:length(sel_dV);
    int = 1:length(ih);
  end

  % find the other channels that are present in the data
  sel_other = setdiff(1:length(freq.label), [sel_dH(:)' sel_dV(:)']);
  lab_other = freq.label(sel_other);

  % define the channel names after combining the planar combinations
  % they should be sorted according to the order of the horizontal planar channels in the data
  [dum, sel_planar] = match_str(freq.label, planar(:,1));
  if exist('ih', 'var'), sel_planar = sel_planar(int); end
  lab_comb          = planar(sel_planar,3);
  [dum, sel_comb]   = match_str(planar(H(ih),3),planar(V(iv),3));

  outputlabel = {};
  outputindex = {};

  outputlabel = [outputlabel; lab_other];
  outputindex = [outputindex; mat2cell(sel_other', ones(length(sel_other),1), 1)];

  outputlabel = [outputlabel; lab_comb];
  outputindex = [outputindex; mat2cell([sel_dH sel_dV(sel_comb)], ones(length(sel_dH),1), 2)];

elseif strcmp(cfg.combinechan, 'pseudomeg'),
  outputlabel = {};
  outputindex = {};
  for i=1:length(freq.label)
    outputlabel{i} = ['all-',freq.label{i}];
    outputindex{i} = [setdiff(1:length(freq.label),i)];
  end
  for i=1:length(freq.label)
    outputlabel{end+1} = freq.label{i};
    outputindex{end+1} = i;
  end
elseif iscell(cfg.combinechan(1)),
  for i=1:length(cfg.combinechan)
    outputindex{i} = match_str(freq.label, cfg.combinechan{i});
    outputindex{i} = outputindex{i}(:)';
    outputlabel{i} = cell2mat(freq.label(outputindex{i})');
  end
else
  error('unknown combination method');
end


text:
var util = require('util');
var fs = require('fs');
var xml2js = require('xml2js');

var testFilePath = '/home/rasmus/nodegpxmariadb/public/uploads/3987-dh6yc5.gpx';

exports.fileForm = function(req, res) {
    res.render('upload', {
        title: 'Upload File'
    });
};

exports.fileUpload = function(req, res, next){
    console.log('file info: ',req.files.uploadedFile);

        //split the url into an array and then get the last chunk and render it out in the send req.
    // var pathArray = req.files.uploadedFile.path.split( '/' );
    req.session.uploadedFilePath = req.files.uploadedFile.path;

    res.send(util.format(' Task Complete \n uploaded %s (%d Kb) to %s as %s'
			 , req.files.uploadedFile.name
			 , req.files.uploadedFile.size / 1024 | 0
			 , req.session.uploadedFilePath
			 , req.body.title
			 , req.files.uploadedFile
			));

};

exports.readFile = function(req, res) {
    fs.readFile(testFilePath, 'ascii', function (err, data) {
	if (err) {
	    res.send(err);
	};
	res.send(data);
    });
};

exports.parseGPX = function(req, res) {
    var data = require('../data.js');
    var json = '';

    try {
	var fileData = fs.readFileSync(req.session.uploadedFilePath, 'ascii');
	var parser = new xml2js.Parser();
	parser.parseString(fileData.substring(0, fileData.length), function (err, result) {
	    json = result;
	});

	var debug = '';
	var lon = null;
	var lat = null;

	data.connect();

	for(var i in json.gpx.trk[0].trkseg[0].trkpt) {
	    lon = json.gpx.trk[0].trkseg[0].trkpt[i].$.lon;
	    lat = json.gpx.trk[0].trkseg[0].trkpt[i].$.lat;
	    data.insertPoint(lon, lat);

	    debug += "lon: " + lon + " - ";
	    debug += "lat: " + lat + "\n";
	}

	data.disconnect();

	res.send(debug);
    } catch (ex) {
	res.send(ex);
    };
};

exports.mariadb = function(req, res) {
    var data = require('../data.js');

    data.connect();
    data.disconnect();

    res.send("Connected and disconnected from MariaDB!");
};

exports.listPoints = function(req, res) {
    var data = require('../data.js');

    data.connect();
    data.getTrackPoints(1, res);
}

exports.xmlTracks = function(req, res) {
    var data = require('../data.js');

    data.connect();
    data.getXMLTracks(res);
}

exports.xmlTracksDuration = function(req, res) {
    var data = require('../data.js');

    data.connect();
    data.getXMLTracksDuration(res);
}

exports.trackInfo = function(req, res) {
    var data = require('../data.js');

    data.connect();
    console.log("trackId: " + req.param("trackId"));
    data.getDistance(req.param("trackId"), res);
}


text:
namespace FrameworkLibrary
{
    public enum AuthType
    {
        Forms,
        Windows
    }
}


text:
package br.com.mnix.mazinrpcaiser.client.proxy;

import br.com.mnix.mazinrpcaiser.client.web.IServiceClient;
import br.com.mnix.mazinrpcaiser.common.DistributedVersion;
import br.com.mnix.mazinrpcaiser.common.ITransmissible;
import br.com.mnix.mazinrpcaiser.common.ProxiedObject;
import br.com.mnix.mazinrpcaiser.common.SessionData;
import br.com.mnix.mazinrpcaiser.common.exception.ServerExecutionException;
import br.com.mnix.mazinrpcaiser.common.request.IReturn;
import br.com.mnix.mazinrpcaiser.common.request.MethodRequest;
import javassist.NotFoundException;
import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by mnix05 on 11/20/14.
 *
 * @author mnix05
 */
public class DistributedObjectProxyTest {
	private static final String DEFAULT_ID = "foo";

	@SuppressWarnings("ExpectedExceptionNeverThrown") // It IS thrown, dumbAss JUnit
	@Test(expected = IllegalAccessException.class)
	public void testGetProxy_ServerSideException() throws Throwable {
		// Arrange
		final IProxyFactory factory = new MockProxyFactory();
		final IServiceClient client = new MockServiceClient();
		final DistributedObjectProxy<IDistributedStub> proxy = new DistributedObjectProxy<>(
				IDistributedStub.class,
				DEFAULT_ID,
				factory,
				client
		);
		final IDistributedStub stub = proxy.proxyInterface();

		// Act & Assert
		try {
			stub.doStuff(Stuff.EXCEPTION);
		} catch (Exception e) {
			if(e instanceof IllegalAccessException) {
				throw e;
			}
		}
	}

	@Test
	public void testGetProxy_ServerSideCorrect() throws Exception {
		// Arrange
		final IProxyFactory factory = new MockProxyFactory();
		final IServiceClient client = new MockServiceClient();
		final DistributedObjectProxy<IDistributedStub> proxy = new DistributedObjectProxy<>(
				IDistributedStub.class,
				"bar",
				factory,
				client
		);
		final IDistributedStub stub = proxy.proxyInterface();

		// Act
		IDistributedStub result = stub.doStuff(Stuff.PROXY);
		IProxy proxy2 = factory.getProxyOfObject(result);

		// Assert
		Assert.assertEquals(DEFAULT_ID, proxy2.getId());
	}

	@Test
	public void testGetProxy_ObjectMethod() throws Exception {
		// Arrange
		final IProxyFactory factory = new MockProxyFactory();
		final IServiceClient client = new MockServiceClient();
		final DistributedObjectProxy<IDistributedStub> proxy = new DistributedObjectProxy<>(
				IDistributedStub.class,
				DEFAULT_ID,
				factory,
				client
		);
		final IDistributedStub stub = proxy.proxyInterface();

		// Assert
		Assert.assertEquals(proxy.hashCode(), stub.hashCode());
		Assert.assertEquals(proxy.toString(), stub.toString());
	}

	private enum Stuff implements ITransmissible {
		EXCEPTION,
		ERROR,
		RESULT,
		PROXY
	}

	public interface IStub extends Serializable {
		IStub doStuff(Stuff i);
	}
	@DistributedVersion(of = IStub.class) public interface IDistributedStub {
		IDistributedStub doStuff(Stuff i);
	}
	private class MockServiceClient implements IServiceClient {
		@Nonnull @Override public SessionData getSessionData() {
			throw new UnsupportedOperationException();
		}
		@Nullable @Override public Serializable makeRequest(@Nonnull Serializable request, int timeout) throws InterruptedException, ServerExecutionException {
			if(request instanceof MethodRequest) {
				MethodRequest method = (MethodRequest) request;
				assert method.getArgs() != null;
				switch((Stuff)method.getArgs()[0]) {
					case EXCEPTION:
						throw new ServerExecutionException(new IllegalAccessException());
					case ERROR:
						throw new ServerExecutionException(new Error());
					case RESULT:
						return DEFAULT_ID;
					case PROXY:
						return new ProxiedObject(DEFAULT_ID, IDistributedStub.class);
				}
			}
			throw new UnsupportedOperationException();
		}
		@Nullable @Override public Serializable makeRequest(@Nonnull Serializable request) throws ServerExecutionException, InterruptedException {
			return makeRequest(request, 1000);
		}
		@Nullable @Override public <T extends Serializable> T makeRequest(@Nonnull IReturn<T> request) throws ServerExecutionException, InterruptedException {
			// noinspection unchecked
			return (T) makeRequest(request, 1000);
		}
	}
	private static class MockProxyFactory implements IProxyFactory {
		private static final Class[] PARAM_TYPES = new Class[0];
		private static final Object[] ARGS = new Object[0];
		private IProxy mProxy = null;
		@Nonnull @Override public <T> T makeRemoteProxy(@Nonnull String id, boolean overwrites, @Nonnull Class<T> distributedInterface, Serializable... args) throws Exception {
			throw new UnsupportedOperationException();
		}
		@Nonnull @Override public <T> T makeProxy(@Nonnull final String id, @Nonnull final Class<T> distributedInterface) {
			mProxy = new IProxy() {
				@Nonnull @Override public Object proxyInterface() {
					throw new UnsupportedOperationException();
				}
				@Nonnull @Override public String getId() {
					return id;
				}
				@Nonnull @Override public Class<?> getBaseInterface() {
					return distributedInterface;
				}
				@Override public Object invoke(Object o, Method method, Method method2, Object[] objects) throws Throwable {
					throw new UnsupportedOperationException();
				}
			};

			javassist.util.proxy.ProxyFactory factory = new javassist.util.proxy.ProxyFactory();
			factory.setInterfaces(new Class[] {distributedInterface});
			try {
				// noinspection unchecked
				return (T) factory.create(PARAM_TYPES, ARGS, mProxy);
			} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
				throw new AssertionError(e);
			}
		}
		@Nonnull @Override public IProxy getProxyOfObject(@Nonnull Object obj) throws NotFoundException {
			return mProxy;
		}
	}
}


text:
/* General */
.filemap {
	padding: 2.2em;
	background: #f5f5f5;
	border: 1px solid #e0e0e0;
	font-size: 100%;
	font-family: 'Roboto', sans-serif;
}

/* Unordered List */
.filemap ul {
	margin: 0;
	padding: 0;
	list-style-type: none;
}
.filemap ul li {
	display: block;
	margin-bottom: 0.5em;
}
.filemap ul li:last-child {
	margin-bottom: 0;
}

/* Folders and Files */
.filemap .folder-wrap {
	margin-top: 0.5em;
}
.filemap .folder-wrap:first-child {
	margin-top: 0;
}
.folder-wrap .file, .folder-wrap .folder-wrap {
	margin-left: 1.5em;
}
.filemap .folder-name {
	padding-left: 2em;
	background: url('icons/folder-color.png') no-repeat;
	background-position: left center;
	-webkit-user-select: none;  /* Chrome all / Safari all */
	-moz-user-select: none;     /* Firefox all */
	-ms-user-select: none;      /* IE 10+ */
}
.filemap .file {
	padding-left: 1.8em;
	background: url('icons/file-color.png') no-repeat;
	background-position: left center;
	-webkit-user-select: none;  /* Chrome all / Safari all */
	-moz-user-select: none;     /* Firefox all */
	-ms-user-select: none;      /* IE 10+ */
}

/* Collapsible */
.collapsible .folder-name {
	cursor: pointer;
	position: relative;
}
.collapsible .folder-name::before {
	content: url('icons/dropdown-color.png');
	display: inline-block;
	position: absolute;
	left: -1.2em;
	top: -3px;
}

/* Tools */
.filemap-description {
	margin: -2.2em -2.2em 2.2em -2.2em;
	padding: 0.5em;
	background: #eeeeee;
	border-bottom: 1px solid #e0e0e0;
	color: #9e9e9e;
}
.folder-name span, .file span {
	font-size: 0.9em;
	color: #9e9e9e;
}
.folder-name span::before, .file span::before {
	content: " - ";
}