text:
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.GeometryUtils = {

	// Merge two geometries or geometry and geometry from object (using object's transform)

	merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {

		var matrix, normalMatrix,
		vertexOffset = geometry1.vertices.length,
		uvPosition = geometry1.faceVertexUvs[ 0 ].length,
		geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
		vertices1 = geometry1.vertices,
		vertices2 = geometry2.vertices,
		faces1 = geometry1.faces,
		faces2 = geometry2.faces,
		uvs1 = geometry1.faceVertexUvs[ 0 ],
		uvs2 = geometry2.faceVertexUvs[ 0 ];

		if ( materialIndexOffset === undefined ) materialIndexOffset = 0;

		if ( object2 instanceof THREE.Mesh ) {

			object2.matrixAutoUpdate && object2.updateMatrix();

			matrix = object2.matrix;

			normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );

		}

		// vertices

		for ( var i = 0, il = vertices2.length; i < il; i ++ ) {

			var vertex = vertices2[ i ];

			var vertexCopy = vertex.clone();

			if ( matrix ) vertexCopy.applyMatrix4( matrix );

			vertices1.push( vertexCopy );

		}

		// faces

		for ( i = 0, il = faces2.length; i < il; i ++ ) {

			var face = faces2[ i ], faceCopy, normal, color,
			faceVertexNormals = face.vertexNormals,
			faceVertexColors = face.vertexColors;

			faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
			faceCopy.normal.copy( face.normal );

			if ( normalMatrix ) {

				faceCopy.normal.applyMatrix3( normalMatrix ).normalize();

			}

			for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {

				normal = faceVertexNormals[ j ].clone();

				if ( normalMatrix ) {

					normal.applyMatrix3( normalMatrix ).normalize();

				}

				faceCopy.vertexNormals.push( normal );

			}

			faceCopy.color.copy( face.color );

			for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {

				color = faceVertexColors[ j ];
				faceCopy.vertexColors.push( color.clone() );

			}

			faceCopy.materialIndex = face.materialIndex + materialIndexOffset;

			faceCopy.centroid.copy( face.centroid );

			if ( matrix ) {

				faceCopy.centroid.applyMatrix4( matrix );

			}

			faces1.push( faceCopy );

		}

		// uvs

		for ( i = 0, il = uvs2.length; i < il; i ++ ) {

			var uv = uvs2[ i ], uvCopy = [];

			for ( var j = 0, jl = uv.length; j < jl; j ++ ) {

				uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );

			}

			uvs1.push( uvCopy );

		}

	},

	// Get random point in triangle (via barycentric coordinates)
	// 	(uniform distribution)
	// 	http://www.cgafaq.info/wiki/Random_Point_In_Triangle

	randomPointInTriangle: function () {

		var vector = new THREE.Vector3();

		return function ( vectorA, vectorB, vectorC ) {

			var point = new THREE.Vector3();

			var a = THREE.Math.random16();
			var b = THREE.Math.random16();

			if ( ( a + b ) > 1 ) {

				a = 1 - a;
				b = 1 - b;

			}

			var c = 1 - a - b;

			point.copy( vectorA );
			point.multiplyScalar( a );

			vector.copy( vectorB );
			vector.multiplyScalar( b );

			point.add( vector );

			vector.copy( vectorC );
			vector.multiplyScalar( c );

			point.add( vector );

			return point;

		};

	}(),

	// Get random point in face (triangle / quad)
	// (uniform distribution)

	randomPointInFace: function ( face, geometry, useCachedAreas ) {

		var vA, vB, vC, vD;

		vA = geometry.vertices[ face.a ];
		vB = geometry.vertices[ face.b ];
		vC = geometry.vertices[ face.c ];

		return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );

	},

	// Get uniformly distributed random points in mesh
	// 	- create array with cumulative sums of face areas
	//  - pick random number from 0 to total area
	//  - find corresponding place in area array by binary search
	//	- get random point in face

	randomPointsInGeometry: function ( geometry, n ) {

		var face, i,
			faces = geometry.faces,
			vertices = geometry.vertices,
			il = faces.length,
			totalArea = 0,
			cumulativeAreas = [],
			vA, vB, vC, vD;

		// precompute face areas

		for ( i = 0; i < il; i ++ ) {

			face = faces[ i ];

			vA = vertices[ face.a ];
			vB = vertices[ face.b ];
			vC = vertices[ face.c ];

			face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );

			totalArea += face._area;

			cumulativeAreas[ i ] = totalArea;

		}

		// binary search cumulative areas array

		function binarySearchIndices( value ) {

			function binarySearch( start, end ) {

				// return closest larger index
				// if exact number is not found

				if ( end < start )
					return start;

				var mid = start + Math.floor( ( end - start ) / 2 );

				if ( cumulativeAreas[ mid ] > value ) {

					return binarySearch( start, mid - 1 );

				} else if ( cumulativeAreas[ mid ] < value ) {

					return binarySearch( mid + 1, end );

				} else {

					return mid;

				}

			}

			var result = binarySearch( 0, cumulativeAreas.length - 1 )
			return result;

		}

		// pick random face weighted by face area

		var r, index,
			result = [];

		var stats = {};

		for ( i = 0; i < n; i ++ ) {

			r = THREE.Math.random16() * totalArea;

			index = binarySearchIndices( r );

			result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );

			if ( ! stats[ index ] ) {

				stats[ index ] = 1;

			} else {

				stats[ index ] += 1;

			}

		}

		return result;

	},

	// Get triangle area (half of parallelogram)
	//	http://mathworld.wolfram.com/TriangleArea.html

	triangleArea: function () {

		var vector1 = new THREE.Vector3();
		var vector2 = new THREE.Vector3();

		return function ( vectorA, vectorB, vectorC ) {

			vector1.subVectors( vectorB, vectorA );
			vector2.subVectors( vectorC, vectorA );
			vector1.cross( vector2 );

			return 0.5 * vector1.length();

		};

	}(),

	// Center geometry so that 0,0,0 is in center of bounding box

	center: function ( geometry ) {

		geometry.computeBoundingBox();

		var bb = geometry.boundingBox;

		var offset = new THREE.Vector3();

		offset.addVectors( bb.min, bb.max );
		offset.multiplyScalar( -0.5 );

		geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
		geometry.computeBoundingBox();

		return offset;

	},

	triangulateQuads: function ( geometry ) {

		var i, il, j, jl;

		var faces = [];
		var faceVertexUvs = [];

		for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {

			faceVertexUvs[ i ] = [];

		}

		for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {

			var face = geometry.faces[ i ];

			faces.push( face );

			for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

				faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );

			}

		}

		geometry.faces = faces;
		geometry.faceVertexUvs = faceVertexUvs;

		geometry.computeCentroids();
		geometry.computeFaceNormals();
		geometry.computeVertexNormals();

		if ( geometry.hasTangents ) geometry.computeTangents();

	}

};


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29217_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">A Gyrodata Directional Survey

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ConocoPhillips
Lease: CCU North Coast Well: 4-8-23MBH, 5" Drill Pipe Location: Precision #567, Dunn County, North Dakota Job Number: RM1014GDM591

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">MEASURED DEPTH feet

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">INCL
deg.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AZIMUTH
deg.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DOGLEG SEVERITY deg./ 100 fi.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">VERTICAL CLOSURE DEPTH DIST. AZIMUTH feet feet deg.

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5690.03 5783.66 5877.82 5971.78 6065.58
6159.43 6253.37 6347.40 6441.41 6535.37

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6629.17 6723.08 6816.88 6911.12 7004.81

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">7098.78 7192.96 7286.76 7380.63 7474.56
7568.60 7662.47

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Page 5 of 6

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HORIZONTAL COORDINATES

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">feet

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">20.02 20.15 20.17 20.04 20.16
19.90 20.01 20.05 20.15 20.25

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">20.21 20.17 20.19 19.67 20.13

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">20.24 20.26 20.33 20.32 20.34
20.29 20.38

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">95.35 95.55 95.84 98.31 100.61
100.39 98.64 96.44 95.11 96.13

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">98.25 93.68 92.83 95.60 95.58

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">97.94 100.14 102.78 102.10 100.33
97.04 91.71

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.24 0.16 0.11 0.91 0.85
0.29 0.65 0.80 0.50 0.39

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.78 1.68 0.31 1.14 0.49

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">0.87 0.81 0.98 0.25 0.66
1.22 1.97

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5544.46 5632.40 5720.79
5809.02 5897.11

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5985.29 6073.59 6161.93 6250.21 6338.40

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6426.41 6514.56 6602.60 6691.20 6779.29

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6867.49 6955.85 7043.83 7131.86 7219.94
7308.13 7396.16

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">909.6 941.7 974.2 1006.5 1038.6

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">95.0 95.0 95.1 95.1 95.3

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1070.6 1102.6 1134.8 1167.1 1199.5

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">95.4 95.5 95.6 95.6 95.6

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1231.9 1264.3 1296.7 1328.8 1360.7
1393.1 1425.6 1458.0 1490.4 1522.9
1555.5 1588.0

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">95.6 95.7 95.6 95.6 95.6
95.6 95.7 95.8 95.9 96.1
96.1 96.1

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">79.78 S 82.83 S 86.05 S 90.03 S 95.33 S

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">106.48 110.71 113.96 117.14

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">121.19 124.56 126.40 128.75 131.85
135.67 140.79 147.26 154.28 160.63
165.56 168.04

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">906.09 E 938.09 E 970.38 E 1002.43 E 1034.22 E

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1065.83 E 1097.44 E 1129.37 E 1161.51 E 1193.79 E

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1225.97 E 1258.18 E 1290.49 E 1322.52 E 1354.25 E
1386.45 E 1418.63 E 1450.51 E 1482.35 E 1514.36 E
1546.62 E 1579.11 E

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file is licensed to you under the BSD License, (the "License"); you may
 * not use this file except in compliance with the License. You may obtain a
 * copy of the License at
 *
 * http://www.opensource.org/licenses/bsd-license.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.h57.sample.service;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.h57.sample.domain.Identity;
import com.h57.sample.form.RegistrationForm;
import com.h57.sample.persistence.IdentityMapper;

/**
 * myBatis Identity Service for our Identity Domain object
 *
 * @author Bubba Hines (bubba@hines57.com)
 * @since 0.02
 */
@Service
@PropertySource("classpath:application.properties")
public class IdentityService {

  @Autowired
  private Environment env;

  public void setEnv(Environment env) {
    this.env = env;
  }

  @Autowired(required = true)
  private IdentityMapper identityMapper;

  private static final Logger logger = LoggerFactory.getLogger(IdentityService.class);

  public IdentityMapper getIdentityMapper() {
    return identityMapper;
  }

  public Identity registerIdentity(RegistrationForm registration) {

    registration.setSalt(getSalt());
    registration.setPassphrase(encodePassphrase(registration.getPassphrase(), registration.getSalt()));

    // Insert the Identity
    identityMapper.registerIdentity(registration);

    logger.trace("INSERTED ID = (" + registration.getId() + ")");
    // Get a new Identity object, fully populated from the DB
    return this.getIdentity(registration.getId());

  }

  public static String getSalt() {
    return new SecureRandomNumberGenerator().nextBytes().toBase64();
  }

  public String getApplicationSalt() {
    return env.getProperty("shiro.applicationSalt");
  }

  public String getCombinedSalt(String salt) {
    return env.getProperty("shiro.applicationSalt") + ":" + salt;
  }

  public String encodePassphrase(String rawPassphrase, String salt) {
    return new Sha512Hash(rawPassphrase, getCombinedSalt(salt), getIterations()).toBase64();
  }

  public Integer getIterations() {
    return Integer.parseInt(env.getProperty("shiro.hashIterations"));
  }

  public Identity getIdentity(int id) {
    logger.trace("Entering getIdentity(" + id + ")");
    if (identityMapper == null) {
      logger.debug("identityMapper didn't get autowired!");
    }
    return identityMapper.getIdentityById(id);
  }

  public Identity getIdentity(String userId) {
    logger.trace("Entering getIdentity(" + userId + ")");
    if (identityMapper == null) {
      logger.debug("identityMapper didn't get autowired!");
    }
    return identityMapper.getIdentityByUserId(userId);
  }

  public void setIdentityMapper(IdentityMapper identityMapper) {
    this.identityMapper = identityMapper;
  }
}


text:
import multiprocessing
import random

# http://stackoverflow.com/questions/28548414/python-quick-sort-parallel-sort-slower-than-sequential

class F(multiprocessing.Process):

    def __init__(self, items, wconn, depth=0):
        super(F, self).__init__()

        self.wconn = wconn
        self.items = items
        self.depth = depth

    def run(self):
        indent = '  ' * self.depth
        prefix = "{}{}:".format(indent, multiprocessing.current_process().name)
        print(prefix, "sorting {}".format(self.items))

        if len(self.items) <= 1:
            self.wconn.send([ self.items[0] ])
            return

        pivot = self.items[0]
        less = []
        pivotList = []
        more = []
        for x in self.items:
            if x < pivot:
                less.append(x)
            elif x > pivot:
                more.append(x)
            else:
                pivotList.append(x)

        print(prefix, "less", less)
        print(prefix, "pivot", pivotList)
        print(prefix, "more", more)

        # sometime we have a worst case pivot

        sortedLess = []
        t1 = None
        if len(less) > 0:
            t1_conn, wconn = multiprocessing.Pipe()
            t1 = F(less, wconn=wconn, depth=self.depth + 1)
            t1.start()

        sortedMore = []
        t2 = None
        if len(more) > 0:
            t2_conn, wconn = multiprocessing.Pipe()
            t2 = F(more, wconn=wconn, depth=self.depth + 1)
            t2.start()

        if t1 is not None:
            sortedLess = t1_conn.recv()
            t1.join()

        if t2 is not None:
            sortedMore = t2_conn.recv()
            t2.join()

        print(prefix, "sorted:", sortedLess, pivotList, sortedMore)

        self.wconn.send(sortedLess + pivotList + sortedMore)

sample = random.sample(range(100), 10)
print("->", sample)

rconn, wconn = multiprocessing.Pipe()
t = F(sample, wconn)
t.start()

x = rconn.recv()
print(x)

t.join()


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-form/iron-form.html">
<link rel="import" href="../../bower_components/app-route/app-location.html">
<link rel="import" href="../../bower_components/iron-icon/iron-icon.html">
<link rel="import" href="../../bower_components/iron-icons/editor-icons.html">
<link rel="import" href="../../bower_components/iron-icons/image-icons.html">
<link rel="import" href="../../bower_components/iron-icons/social-icons.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/paper-toggle-button/paper-toggle-button.html">

<link rel="import" href="../behaviors/data-pipe.behavior.html">
<link rel="import" href="../behaviors/form.behavior.html">
<link rel="import" href="../behaviors/navigation.behavior.html">
<link rel="import" href="../behaviors/toaster-control.behavior.html">

<link rel="import" href="button.component.html">
<link rel="import" href="standards-group.component.html">
<link rel="import" href="loading-layer.component.html">
<link rel="import" href="file-uploader.component.html">
<link rel="import" href="capsule-input.component.html">
<link rel="import" href="dashed-title.component.html">
<link rel="import" href="thumbnail.component.html">
<link rel="import" href="data-source.component.html">

<link rel="import" href="../styles/tile.style.html">
<link rel="import" href="../styles/form.style.html">
<link rel="import" href="../styles/shop-input.style.html">

<dom-module id="product-form">
      <template>

      <app-location route="{{route}}"></app-location>

            <loading-layer show="[[loading]]"></loading-layer>
            <form id="form" is="iron-form">

                              <dashed-title icon="editor:format-quote">Infos produit</dashed-title>

                              <shop-input>
                                    <input type="text" id="name" name="name" pattern=".{4,}" required="" placeholder="Nom" on-value-change="_updateHeading" autocomplete="off" value="{{product.name::input}}">
                                    <shop-md-decorator error-message="Champs requis" aria-hidden="true">
                                          Nom
                                          <shop-underline></shop-underline>
                                    </shop-md-decorator>
                              </shop-input>

                              <paper-textarea error-message="Champs requis" auto-validate name="description" label="Description" required="" value="[[product.description]]"></paper-textarea>

                              <capsule-input id="ingredients" name="ingredients" label="Ingrédients" data="[[product.ingredients]]"></capsule-input>

                              <paper-textarea error-message="Contenu invalide" auto-validate name="notice" label="Notice informative" value="[[product.notice]]"></paper-textarea>

                        <data-source path="/all_products/[[idProduct]]/banner/pictures" empty="{{noBanner}}" output="{{picsBanner}}"></data-source>

                              <dashed-title icon="image:landscape">Bannière</dashed-title>

                        <paper-toggle-button disabled="[[noBanner]]" name="bannerActive" checked="[[product.banner.active]]">
                              Faire apparaitre ce produit dans le kiosque dynamique
                        </paper-toggle-button>

                        <template is="dom-if" if="[[noBanner]]">

Aucune bannière uploadée

                        </template>

                        <template is="dom-if" if="[[!noBanner]]">

Bannière uploadée

                        </template>

                              <template is="dom-repeat" items="[[toArray(picsBanner, 'key')]]" as="oneBan">
                                    <upload-thumbnail on-remove-file="_removeBanner" index="[[index]]" data-key="[[oneBan.key]]" src="[[oneBan.url]]" name="Chargement"></upload-thumbnail>
                              </template>

                        <template is="dom-if" if="[[hasId]]">
                              <file-uploader
                              backend="[[appData.backend]]"
                              user="[[user]]"
                              context="[[idProduct]]"
                              property="banner"
                              paths="[[bannerPaths]]"></file-uploader>
                        </template>

                        <data-source path="/all_products/[[idProduct]]/pictures" empty="{{noPhotos}}" output="{{picsProduct}}"></data-source>

                              <dashed-title icon="image:photo-library">Photos</dashed-title>

                        <template is="dom-if" if="[[noPhotos]]">

Aucune photo uploadée

                        </template>

                        <template is="dom-if" if="[[!noPhotos]]">

Photos uploadées

                        </template>

                              <template is="dom-repeat" items="[[toArray(picsProduct, 'key')]]" as="onePic">
                                    <upload-thumbnail on-remove-file="_removePhoto" index="[[index]]" data-key="[[onePic.key]]" src="[[onePic.url]]" name="Chargement"></upload-thumbnail>
                              </template>

                        <template is="dom-if" if="[[hasId]]">
                              <file-uploader
                              backend="[[appData.backend]]"
                              user="[[user]]"
                              property="pictures"
                              paths="[[picturePaths]]"
                              context="[[idProduct]]"></file-uploader>
                        </template>

                              <dashed-title icon="editor:attach-money">Vente</dashed-title>

                              <paper-toggle-button name="active" checked="[[product.active]]">Activer le produit</paper-toggle-button>

                        <standards-group id="standards" selectors="[[toArrayFromKey(product.standards, 'std')]]" name="standards"></standards-group>

                        <app-button id="submit" icon="[[buttonIcon]]" raised on-tap="_submit">[[buttonText]]</app-button>

            </form>

</template>

</dom-module>


text:
#include <QDomElement>

#include "DataType.h"

DomVariant::DomVariant(const QVariant & var)
{
    DataType typ(var);
    QDomElement::operator = (typ.domVariant(var));
}

DomVariant::operator QDomElement (void)
{
    return QDomElement(*this);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diploschistes centrifugus Groenh.

### Remarks
null


text:
<?php

namespace LBanas\Components;

/**
 * interface TemplateEngine. Main idea for this interface is to enable future switch into different template engine
 * @category Theme
 * @package LBanasComponents
 * @author Lukasz Banas <lukaszbanas4@gmail.com>
 * @license MIT <http://opensource.org/licenses/MIT>
 * @link https://github.com/lukaszbanas/Theme
 * @since 0.0.1
 */
interface TemplateEngine
{
    /**
     * @param $templateDir
     * @param $options
     * @return mixed
     */
    public static function create($templateDir, $options);
}


text:
package org.apache.mxnet

import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

private[mxnet] class AddNDArrayFunctions(isContrib: Boolean) extends StaticAnnotation {
  private[mxnet] def macroTransform(annottees: Any*) = macro NDArrayMacro.addDefs
}

private[mxnet] class AddNDArrayAPIs(isContrib: Boolean) extends StaticAnnotation {
  private[mxnet] def macroTransform(annottees: Any*) = macro TypedNDArrayAPIMacro.typeSafeAPIDefs
}

private[mxnet] class AddNDArrayRandomAPIs(isContrib: Boolean) extends StaticAnnotation {
  private[mxnet] def macroTransform(annottees: Any*) =
  macro TypedNDArrayRandomAPIMacro.typeSafeAPIDefs
}

/**
  * For non-typed NDArray API
  */
private[mxnet] object NDArrayMacro extends GeneratorBase {

  def addDefs(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val isContrib: Boolean = c.prefix.tree match {
      case q"new AddNDArrayFunctions($b)" => c.eval[Boolean](c.Expr(b))
    }

    impl(c)(isContrib, annottees: _*)
  }

  private def impl(c: blackbox.Context)
                  (isContrib: Boolean, annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val functions = functionsToGenerate(isSymbol = false, isContrib)

    val functionDefs = functions.flatMap { NDArrayfunction =>
      val funcName = NDArrayfunction.name
      val termName = TermName(funcName)
      Seq(
        // e.g def transpose(kwargs: Map[String, Any] = null)(args: Any*)
        q"""
             def $termName(kwargs: Map[String, Any] = null)(args: Any*) = {
               genericNDArrayFunctionInvoke($funcName, args, kwargs)
             }
          """.asInstanceOf[DefDef],
        // e.g def transpose(args: Any*)
        q"""
             def $termName(args: Any*) = {
               genericNDArrayFunctionInvoke($funcName, args, null)
             }
          """.asInstanceOf[DefDef]
      )
    }

    structGeneration(c)(functionDefs, annottees: _*)
  }
}

/**
  * NDArray.api code generation
  */
private[mxnet] object TypedNDArrayAPIMacro extends GeneratorBase {

  def typeSafeAPIDefs(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val isContrib: Boolean = c.prefix.tree match {
      case q"new AddNDArrayAPIs($b)" => c.eval[Boolean](c.Expr(b))
    }

    val functionDefs = typeSafeFunctionsToGenerate(isSymbol = false, isContrib)
      .map(f => buildTypedFunction(c)(f))

    structGeneration(c)(functionDefs, annottees: _*)
  }

  protected def buildTypedFunction(c: blackbox.Context)
                                  (function: Func): c.universe.DefDef = {
    import c.universe._

    val returnType = "org.apache.mxnet.NDArrayFuncReturn"

    // Construct API arguments declaration
    val argDecl = super.typedFunctionCommonArgDef(function) :+ "out : Option[NDArray] = None"

    // Map API input args to backend args
    val backendArgsMapping =
      function.listOfArgs.map { arg =>
        // ndarrays go to args, other types go to kwargs
        if (arg.argType.equals(s"Array[org.apache.mxnet.NDArray]")) {
          s"args ++= ${arg.safeArgName}.toSeq"
        } else {
          val base = if (arg.argType.equals("org.apache.mxnet.NDArray")) {
            s"args += ${arg.safeArgName}"
          } else {
            s"""map("${arg.argName}") = ${arg.safeArgName}"""
          }
          if (arg.isOptional) s"if (!${arg.safeArgName}.isEmpty) $base.get"
          else base
        }
      }

    val impl =
      s"""
         |def ${function.name}
         |  (${argDecl.mkString(",")}): $returnType = {
         |
         |  val map = scala.collection.mutable.Map[String, Any]()
         |  val args = scala.collection.mutable.ArrayBuffer.empty[org.apache.mxnet.NDArray]
         |
         |  if (!out.isEmpty) map("out") = out.get
         |
         |  ${backendArgsMapping.mkString("\n")}
         |
         |  org.apache.mxnet.NDArray.genericNDArrayFunctionInvoke(
         |    "${function.name}", args.toSeq, map.toMap)
         |}
       """.stripMargin

    c.parse(impl).asInstanceOf[DefDef]
  }
}

/**
  * NDArray.random code generation
  */
private[mxnet] object TypedNDArrayRandomAPIMacro extends GeneratorBase
  with RandomHelpers {

  def typeSafeAPIDefs(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    // Note: no contrib managed in this module

    val functionDefs = typeSafeRandomFunctionsToGenerate(isSymbol = false)
      .map(f => buildTypedFunction(c)(f))

    structGeneration(c)(functionDefs, annottees: _*)
  }

  protected def buildTypedFunction(c: blackbox.Context)
                                  (function: Func): c.universe.DefDef = {
    import c.universe._

    val returnType = "org.apache.mxnet.NDArrayFuncReturn"

    // Construct API arguments declaration
    val argDecl = super.typedFunctionCommonArgDef(function) :+ "out : Option[NDArray] = None"

    // Map API input args to backend args
    val backendArgsMapping =
      function.listOfArgs.map { arg =>
        // ndarrays go to args, other types go to kwargs
        if (arg.argType.equals("Array[org.apache.mxnet.NDArray]")) {
          s"args ++= ${arg.safeArgName}.toSeq"
        } else {
          if (arg.argType.equals("T")) {
            if (arg.isOptional) {
              s"""if(${arg.safeArgName}.isDefined) {
                 |  if(isScalar) {
                 |    map("${arg.argName}") = ${arg.safeArgName}.get
                 |  } else {
                 |    args += ${arg.safeArgName}.get.asInstanceOf[org.apache.mxnet.NDArray]
                 |  }
                 |}
             """.stripMargin
            } else {
              s"""if(isScalar) {
                 |  map("${arg.argName}") = ${arg.safeArgName}
                 |} else {
                 |  args += ${arg.safeArgName}.asInstanceOf[org.apache.mxnet.NDArray]
                 |}
             """.stripMargin
            }
          } else {
            if (arg.isOptional) {
              s"""if (${arg.safeArgName}.isDefined) map("${arg.argName}")=${arg.safeArgName}.get"""
            } else {
              s"""map("${arg.argName}") = ${arg.safeArgName}"""
            }
          }
        }
      }

    val impl =
      s"""
         |def ${function.name}${randomGenericTypeSpec(false, true)}
         |  (${argDecl.mkString(",")}): $returnType = {
         |
         |  val map = scala.collection.mutable.Map[String, Any]()
         |  val args = scala.collection.mutable.ArrayBuffer.empty[org.apache.mxnet.NDArray]
         |  val isScalar = NDArrayOrScalar[T].isScalar
         |
         |  if(out.isDefined) map("out") = out.get
         |
         |  ${backendArgsMapping.mkString("\n")}
         |
         |  val target = if(isScalar) {
         |    "random_${function.name}"
         |  } else {
         |    "sample_${function.name}"
         |  }
         |
         |  ${unhackNormalFunc(function)}
         |
         |  org.apache.mxnet.NDArray.genericNDArrayFunctionInvoke(
         |    target, args.toSeq, map.toMap)
         |}
       """.stripMargin

    c.parse(impl).asInstanceOf[DefDef]
  }

}


text:
class Array

  # Clean up array
  #
  # @return [Array] Remove nil or ''-items from self
  def clean_up
    self.delete_if { |item| item.nil? or item == '' }
  end
end


text:
void B::ReceiveFromOtherClass(Room* room, const int& dataType, void* data, const string& otherClassName){
	printf("B receive message,dataType = %d,data = %s,otherClassName = %s\n",dataType,data,otherClassName.c_str());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.facebook.presto</groupId>
        <artifactId>presto-root</artifactId>
        <version>0.279-SNAPSHOT</version>
    </parent>

    <artifactId>presto-spark-package</artifactId>
    <name>presto-spark-package</name>

    <properties>
        <air.main.basedir>${project.parent.basedir}</air.main.basedir>

        <air.check.skip-enforcer>true</air.check.skip-enforcer>
        <air.check.skip-duplicate-finder>true</air.check.skip-duplicate-finder>
        <air.check.skip-findbugs>true</air.check.skip-findbugs>
        <air.check.skip-dependency>true</air.check.skip-dependency>
    </properties>

    <dependencies>
        <!-- lib -->
        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-spark</artifactId>
        </dependency>

        <!-- plugins -->

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-ml</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-teradata-functions</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-hive-hadoop2</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-tpch</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-tpcds</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-thrift-connector</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-mysql</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-postgresql</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-kafka</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-mongodb</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-pinot</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-redis</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-redshift</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-sqlserver</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.facebook.presto</groupId>
            <artifactId>presto-session-property-managers</artifactId>
            <version>${project.version}</version>
            <type>zip</type>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack-plugins</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>unpack-dependencies</goal>
                        </goals>
                        <configuration>
                            <skip>false</skip>
                            <!-- take care of all the plugin types -->
                            <includeTypes>zip</includeTypes>
                            <includeScope>provided</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <id>bin</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <formats>
                                <format>dir</format>
                                <format>tar.gz</format>
                            </formats>
                            <descriptors>
                                <descriptor>src/main/assembly/presto.xml</descriptor>
                            </descriptors>
                            <finalName>presto-spark-package-${project.version}</finalName>
                            <appendAssemblyId>false</appendAssemblyId>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
module Azure::Batch::Mgmt::V2017_05_01
  module Models
    #
    # Parameters for adding an Application.
    #
    class ApplicationCreateParameters

      include MsRestAzure

      # @return [Boolean] A value indicating whether packages within the
      # application may be overwritten using the same version string.
      attr_accessor :allow_updates

      # @return [String] The display name for the application.
      attr_accessor :display_name

      #
      # Mapper for ApplicationCreateParameters class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ApplicationCreateParameters',
          type: {
            name: 'Composite',
            class_name: 'ApplicationCreateParameters',
            model_properties: {
              allow_updates: {
                client_side_validation: true,
                required: false,
                serialized_name: 'allowUpdates',
                type: {
                  name: 'Boolean'
                }
              },
              display_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'displayName',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
/**
* @fileoverview Variable blocks for Blockly.
* @author fraser@google.com (Neil Fraser)
*/

/**
* Review by Pablo Caballero, Eugenio Rubio, Sergio Tamurejo and Jorge Blasco (guizos@gmail.com)
*/
'use strict';

goog.provide('Blockly.Blocks.z_edx_literals');

goog.require('Blockly.Blocks');

Blockly.Blocks['literal_text'] = {
  /**
   * Block for text value.
   * @this Blockly.Block
   */
  init: function() {
    this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
    this.setColour(30);
    this.appendDummyInput()
        .appendField(this.newQuote_(true))
        .appendField(new Blockly.FieldTextInput(''), 'TEXT')
        .appendField(this.newQuote_(false));
    this.setOutput(true, 'String');
    this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP);
  },
  /**
   * Create an image of an open or closed quote.
   * @param {boolean} open True if open quote, false if closed.
   * @return {!Blockly.FieldImage} The field image of the quote.
   * @private
   */
  newQuote_: function(open) {
    if (open == Blockly.RTL) {
      var file = 'quote1.png';
    } else {
      var file = 'quote0.png';
    }
    return new Blockly.FieldImage(Blockly.pathToMedia + file, 12, 12, '"');
  }
};

Blockly.Blocks['literal_integer'] = {
  /**
  * Block for numeric integer value.
  * @this Blockly.Block
  */
  init: function() {
    this.setHelpUrl(Blockly.Msg.MATH_NUMBER_HELPURL);
    this.setColour(60);
    this.appendDummyInput()
    .appendField(new Blockly.FieldTextInput('0',
    Blockly.FieldTextInput.integerValidator), 'NUM');
    this.setOutput(true, 'Number');
    this.setTooltip(Blockly.Msg.MATH_NUMBER_TOOLTIP);
  }
};

Blockly.Blocks['literal_boolean'] = {
  /**
   * Block for boolean data type: true and false.
   * @this Blockly.Block
   */
  init: function() {
    var BOOLEANS =
        [[Blockly.Msg.LOGIC_BOOLEAN_TRUE, 'TRUE'],
         [Blockly.Msg.LOGIC_BOOLEAN_FALSE, 'FALSE']];
    this.setHelpUrl(Blockly.Msg.LOGIC_BOOLEAN_HELPURL);
    this.setColour(90);
    this.setOutput(true, 'Boolean');
    this.appendDummyInput()
        .appendField(new Blockly.FieldDropdown(BOOLEANS), 'BOOL');
    this.setTooltip(Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP);
  }
};


text:
<form method="POST" action="index.php?app=desktop&ctl=dashboard&act=application" class="tableform" id="app_license">
<div class="table-action">
    <{button id='license_btn' label=$___b2c="立即申请"|t:'desktop' type="submit"}>
    <{button class="btn-secondary"  type="button" label=$___b2c="取消"|t:'desktop' isCloseDialogBtn="true"}>
</div>

</form>

<script>
(function(){
	var _form = $('app_license');
	var btn = $('license_btn');
	//var finder = finderGroup['<{$env.get._finder.finder_id}>'];

	_form.store('target',{
		onComplete:function(response){
			var hash_res_obj = JSON.decode(response);

			if (hash_res_obj.success != undefined && hash_res_obj.success != "")
			{
				try{
					var _dialogIns = btn.getParent('.dialog').retrieve('instance');
				}catch(e){}

				if(_dialogIns)
				{
					_dialogIns.close();
				}
			}

		}
	});
})();

</script>


text:
package io.imoji.sdk.internal;

import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import io.imoji.sdk.ApiTask;
import io.imoji.sdk.ImojiSDK;
import io.imoji.sdk.Session;
import io.imoji.sdk.StoragePolicy;
import io.imoji.sdk.objects.Artist;
import io.imoji.sdk.objects.Category;
import io.imoji.sdk.objects.Imoji;
import io.imoji.sdk.objects.json.ArtistDeserializer;
import io.imoji.sdk.objects.json.AttributionDeserializer;
import io.imoji.sdk.objects.json.CategoryDeserializer;
import io.imoji.sdk.objects.json.CategoryResultsDeserializer;
import io.imoji.sdk.objects.json.ErrorResponseDeserializer;
import io.imoji.sdk.objects.json.GenericNetworkResponsDeserializer;
import io.imoji.sdk.objects.json.ImojiAttributionsResponseDeserializer;
import io.imoji.sdk.objects.json.ImojiDeserializer;
import io.imoji.sdk.objects.json.ImojiResultsDeserializer;
import io.imoji.sdk.objects.json.ImojiUploadResponseDeserializer;
import io.imoji.sdk.objects.json.OAuthTokenDeserializer;
import io.imoji.sdk.response.ApiResponse;
import io.imoji.sdk.response.CategoriesResponse;
import io.imoji.sdk.response.ErrorResponse;
import io.imoji.sdk.response.GenericApiResponse;
import io.imoji.sdk.response.ImojiAttributionsResponse;
import io.imoji.sdk.response.ImojiUploadResponse;
import io.imoji.sdk.response.ImojisResponse;
import io.imoji.sdk.response.OAuthTokenResponse;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

public abstract class NetworkSession implements Session {

    private static final Gson GSON_INSTANCE = new GsonBuilder()
            .registerTypeAdapter(Artist.class, new ArtistDeserializer())
            .registerTypeAdapter(Category.class, new CategoryDeserializer())
            .registerTypeAdapter(CategoriesResponse.class, new CategoryResultsDeserializer())
            .registerTypeAdapter(GenericApiResponse.class, new GenericNetworkResponsDeserializer())
            .registerTypeAdapter(Imoji.class, new ImojiDeserializer())
            .registerTypeAdapter(ImojisResponse.class, new ImojiResultsDeserializer())
            .registerTypeAdapter(ImojiAttributionsResponse.class, new ImojiAttributionsResponseDeserializer())
            .registerTypeAdapter(Category.Attribution.class, new AttributionDeserializer())
            .registerTypeAdapter(OAuthTokenResponse.class, new OAuthTokenDeserializer())
            .registerTypeAdapter(ImojiUploadResponse.class, new ImojiUploadResponseDeserializer())
            .registerTypeAdapter(ErrorResponse.class, new ErrorResponseDeserializer())
            .create();

    @NonNull
    protected final StoragePolicy storagePolicy;

    protected NetworkSession(@NonNull StoragePolicy storagePolicy) {
        this.storagePolicy = storagePolicy;
    }

    protected <T extends ApiResponse> ApiTask<T> validatedGet(@NonNull String path,
                                                              @NonNull final Class<T> responseClass,
                                                              @Nullable Map<String, String> queryStrings,
                                                              @Nullable Map<String, String> headers) {
        return oauthValidatedQueryStringConnection(path, "GET", responseClass, checkedPairMap(queryStrings), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> validatedDelete(@NonNull String path,
                                                                 @NonNull final Class<T> responseClass,
                                                                 @Nullable Map<String, String> queryStrings,
                                                                 @Nullable Map<String, String> headers) {
        return oauthValidatedQueryStringConnection(path, "DELETE", responseClass, checkedPairMap(queryStrings), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> validatedPost(@NonNull String path,
                                                               @NonNull final Class<T> responseClass,
                                                               @Nullable Map<String, String> body,
                                                               @Nullable Map<String, String> headers) {
        return oauthValidatedFormEncodedConnection(path, "POST", responseClass, checkedPairMap(body), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> validatedPut(@NonNull String path,
                                                              @NonNull final Class<T> responseClass,
                                                              @Nullable Map<String, String> body,
                                                              @Nullable Map<String, String> headers) {
        return oauthValidatedFormEncodedConnection(path, "PUT", responseClass, checkedPairMap(body), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> makeGetRequest(@NonNull String path,
                                                                @NonNull final Class<T> responseClass,
                                                                @Nullable Map<String, String> queryStrings,
                                                                @Nullable Map<String, String> headers) {
        return queryStringConnection(path, "GET", responseClass, checkedPairMap(queryStrings), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> makeDeleteRequest(@NonNull String path,
                                                                   @NonNull final Class<T> responseClass,
                                                                   @Nullable Map<String, String> queryStrings,
                                                                   @Nullable Map<String, String> headers) {
        return queryStringConnection(path, "DELETE", responseClass, checkedPairMap(queryStrings), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> makePostRequest(@NonNull String path,
                                                                 @NonNull final Class<T> responseClass,
                                                                 @Nullable Map<String, String> body,
                                                                 @Nullable Map<String, String> headers) {
        return formEncodedConnection(path, "POST", responseClass, checkedPairMap(body), checkedPairMap(headers));
    }

    protected <T extends ApiResponse> ApiTask<T> makePutRequest(@NonNull String path,
                                                                @NonNull final Class<T> responseClass,
                                                                @Nullable Map<String, String> body,
                                                                @Nullable Map<String, String> headers) {
        return formEncodedConnection(path, "PUT", responseClass, checkedPairMap(body), checkedPairMap(headers));
    }

    protected ApiTask<GenericApiResponse> makePutDataRequest(@NonNull Uri uri,
                                                             @NonNull byte[] body,
                                                             @Nullable Map<String, String> headers) {
        return dataUploadFormEncodedConnection(uri, "PUT", body, checkedPairMap(headers));
    }

    protected String oauthCredentialsHeader() {
        return "Basic " +
                Base64.encodeToString((ImojiSDK.getInstance().getClientId().toString() + ":" + ImojiSDK.getInstance().getApiToken()).getBytes(),
                        Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE
                );
    }

    private ApiTask<OAuthTokenResponse> validateSession() {
        return new ApiTask<>(new Callable<OAuthTokenResponse>() {

            @Override
            public OAuthTokenResponse call() throws Exception {
                String clientId = NetworkSession.this.storagePolicy.getString(ImojiSDKConstants.PREFERENCES_OAUTH_CLIENT_ID_KEY, null);
                String clientToken = NetworkSession.this.storagePolicy.getString(ImojiSDKConstants.PREFERENCES_OAUTH_CLIENT_TOKEN_KEY, null);

                // if the client credentials changed, the oauth info is no longer valid
                boolean validClientInfo =
                        ImojiSDK.getInstance().getApiToken().equals(clientToken) && ImojiSDK.getInstance().getClientId().toString().equals(clientId);

                String accessToken = NetworkSession.this.storagePolicy.getString(ImojiSDKConstants.PREFERENCES_OAUTH_ACCESS_TOKEN_KEY, null);
                String refreshToken = NetworkSession.this.storagePolicy.getString(ImojiSDKConstants.PREFERENCES_OAUTH_REFRESH_TOKEN_KEY, null);
                long expiration = NetworkSession.this.storagePolicy.getLong(ImojiSDKConstants.PREFERENCES_OAUTH_EXPIRATION_KEY, 0);
                boolean refreshTokenExpired = new Date(expiration).before(new Date());
                if (validClientInfo && accessToken != null && refreshToken != null && !refreshTokenExpired) {
                    return new OAuthTokenResponse(accessToken, expiration, refreshToken);
                }

                Map<String, String> headers = new HashMap<>(2);
                Map<String, String> body = new HashMap<>(1);

                headers.put(ImojiSDKConstants.Headers.SDK_VERSION, ImojiSDKConstants.SERVER_SDK_VERSION);
                headers.put(ImojiSDKConstants.Headers.AUTHORIZATION, oauthCredentialsHeader());

                // refresh token expired, use the refresh_token grant type to get a new one
                OAuthTokenResponse oAuthTokenResponse;
                if (refreshTokenExpired && refreshToken != null) {
                    body.put("grant_type", "refresh_token");
                    body.put("refresh_token", refreshToken);
                    oAuthTokenResponse = makePostRequest(ImojiSDKConstants.Paths.OAUTH_REGISTER, OAuthTokenResponse.class, body, headers).executeImmediately();
                } else {
                    // get a new one all together
                    body.put("grant_type", "client_credentials");
                    oAuthTokenResponse = makePostRequest(ImojiSDKConstants.Paths.OAUTH_REGISTER, OAuthTokenResponse.class, body, headers).executeImmediately();
                }

                if (oAuthTokenResponse != null) {
                    NetworkSession.this.storagePolicy.putString(ImojiSDKConstants.PREFERENCES_OAUTH_CLIENT_ID_KEY, ImojiSDK.getInstance().getClientId().toString());
                    NetworkSession.this.storagePolicy.putString(ImojiSDKConstants.PREFERENCES_OAUTH_CLIENT_TOKEN_KEY, ImojiSDK.getInstance().getApiToken());
                    NetworkSession.this.storagePolicy.putString(ImojiSDKConstants.PREFERENCES_OAUTH_ACCESS_TOKEN_KEY, oAuthTokenResponse.getAccessToken());
                    NetworkSession.this.storagePolicy.putString(ImojiSDKConstants.PREFERENCES_OAUTH_REFRESH_TOKEN_KEY, oAuthTokenResponse.getRefreshToken());
                    NetworkSession.this.storagePolicy.putLong(ImojiSDKConstants.PREFERENCES_OAUTH_EXPIRATION_KEY, oAuthTokenResponse.getExpiration());
                }

                return oAuthTokenResponse;
            }
        });
    }

    private <T extends ApiResponse> ApiTask<T> queryStringConnection(@NonNull final String path,
                                                                     @NonNull final String method,
                                                                     @NonNull final Class<T> responseClass,
                                                                     @NonNull final Map<String, String> queryStrings,
                                                                     @NonNull final Map<String, String> headers) {
        return new ApiTask<>(new Callable<T>() {
            @Override
            public T call() throws Exception {
                HttpURLConnection connection = null;
                try {
                    Uri.Builder uriBuilder = ImojiSDKConstants.SERVER_URL.buildUpon().appendEncodedPath(path);

                    for (Map.Entry<String, String> query : queryStrings.entrySet()) {
                        uriBuilder.appendQueryParameter(query.getKey(), query.getValue());
                    }

                    URL url = new URL(uriBuilder.build().toString());
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod(method);

                    //set headers
                    for (Map.Entry<String, String> header : headers.entrySet()) {
                        connection.setRequestProperty(header.getKey(), header.getValue());
                    }

                    connection.connect();

                    return readJsonResponse(connection, responseClass);

                } catch (Throwable t) {
                    Log.e(NetworkSession.class.getName(), "Unable to perform network request", t);
                    throw t;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        });
    }

    private <T extends ApiResponse> ApiTask<T> formEncodedConnection(@NonNull final String path,
                                                                     @NonNull final String method,
                                                                     @NonNull final Class<T> responseClass,
                                                                     @NonNull final Map<String, String> body,
                                                                     @NonNull final Map<String, String> headers) {
        return new ApiTask<>(new Callable<T>() {
            @Override
            public T call() throws Exception {
                HttpURLConnection connection = null;
                OutputStream outputStream = null;
                try {
                    Uri.Builder uriBuilder = ImojiSDKConstants.SERVER_URL.buildUpon().appendEncodedPath(path);
                    URL url = new URL(uriBuilder.build().toString());

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod(method);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);

                    //set headers
                    for (Map.Entry<String, String> header : headers.entrySet()) {
                        connection.setRequestProperty(header.getKey(), header.getValue());
                    }

                    Uri.Builder bodyBuilder = new Uri.Builder();
                    for (Map.Entry<String, String> query : body.entrySet()) {
                        bodyBuilder.appendQueryParameter(query.getKey(), query.getValue());
                    }
                    String query = bodyBuilder.build().getEncodedQuery();
                    outputStream = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(outputStream, Xml.Encoding.UTF_8.name())
                    );

                    writer.write(query);
                    writer.flush();
                    writer.close();

                    connection.connect();

                    return readJsonResponse(connection, responseClass);

                } catch (Throwable t) {
                    Log.e(NetworkSession.class.getName(), "Unable to perform network request", t);
                    throw t;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }

                    if (outputStream != null) {
                        outputStream.close();
                    }
                }
            }
        });
    }

    private ApiTask<GenericApiResponse> dataUploadFormEncodedConnection(@NonNull final Uri uri,
                                                                        @NonNull final String method,
                                                                        @NonNull final byte[] body,
                                                                        @NonNull final Map<String, String> headers) {
        return new ApiTask<>(new Callable<GenericApiResponse>() {
            @Override
            public GenericApiResponse call() throws Exception {
                HttpURLConnection connection = null;
                OutputStream outputStream;
                try {
                    URL url = new URL(uri.toString());

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setRequestMethod(method);

                    //set headers
                    for (Map.Entry<String, String> header : headers.entrySet()) {
                        connection.setRequestProperty(header.getKey(), header.getValue());
                    }

                    outputStream = connection.getOutputStream();
                    outputStream.write(body, 0, body.length);
                    outputStream.flush();
                    outputStream.close();

                    if (connection.getResponseCode() == 200) {
                        return new GenericApiResponse();
                    }

                    throw new IOException("Data upload failed to " + url);

                } catch (Throwable t) {
                    Log.e(NetworkSession.class.getName(), "Unable to perform network request", t);
                    throw t;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        });
    }

    private <T extends ApiResponse> ApiTask<T> oauthValidatedQueryStringConnection(@NonNull final String path,
                                                                                @NonNull final String method,
                                                                                @NonNull final Class<T> responseClass,
                                                                                @NonNull final Map<String, String> queryStrings,
                                                                                @NonNull final Map<String, String> headers) {
        return new ApiTask<>(new Callable<T>() {
            @Override
            public T call() throws Exception {
                OAuthTokenResponse oAuthTokenResponse;
                try {
                    oAuthTokenResponse = validateSession().executeImmediately(ApiTask.THREAD_POOL_EXECUTOR_VALIDATE);
                    Map<String, String> headersWithOauth = new HashMap<>(headers);
                    Map<String, String> queryStringsWithOauth = new HashMap<>(queryStrings);

                    headersWithOauth.put(ImojiSDKConstants.Headers.SDK_VERSION, ImojiSDKConstants.SERVER_SDK_VERSION);
                    headersWithOauth.put(ImojiSDKConstants.Headers.LOCALE, Locale.getDefault().toString());
                    queryStringsWithOauth.put(ImojiSDKConstants.Params.AUTH_TOKEN, oAuthTokenResponse.getAccessToken());

                    return queryStringConnection(path, method, responseClass, queryStringsWithOauth, headersWithOauth).executeImmediately();

                } catch (InterruptedException | ExecutionException e) {
                    if (e.getCause().getClass().isAssignableFrom(ApiException.class)) {
                        ApiException apiException = (ApiException) e.getCause();
                        ErrorResponse errorResponse = apiException.getErrorResponse();

                        // OAuth token verification error occurred, reset the token settings,
                        // generate a new token and call the same method again
                        if (errorResponse != null && ImojiSDKConstants.Errors.OAUTH_VERIFICATION_ERROR_STATUS.equals(errorResponse.getServerStatus())) {
                            clearOauthSettings();
                            oAuthTokenResponse = validateSession().executeImmediately(ApiTask.THREAD_POOL_EXECUTOR_VALIDATE);

                            if (oAuthTokenResponse != null) {
                                return oauthValidatedQueryStringConnection(
                                        path, method, responseClass, queryStrings, headers
                                ).executeImmediately();
                            }
                        }
                    }

                    throw e;
                }
            }
        });
    }

    private <T extends ApiResponse> ApiTask<T> oauthValidatedFormEncodedConnection(@NonNull final String path,
                                                                                @NonNull final String method,
                                                                                @NonNull final Class<T> responseClass,
                                                                                @NonNull final Map<String, String> body,
                                                                                @NonNull final Map<String, String> headers) {
        return new ApiTask<>(new Callable<T>() {
            @Override
            public T call() throws Exception {
                OAuthTokenResponse oAuthTokenResponse;
                try {
                    oAuthTokenResponse = validateSession().executeImmediately(ApiTask.THREAD_POOL_EXECUTOR_VALIDATE);
                    Map<String, String> headersWithOauth = new HashMap<>(headers);
                    Map<String, String> bodyWithOauth = new HashMap<>(body);

                    headersWithOauth.put(ImojiSDKConstants.Headers.SDK_VERSION, ImojiSDKConstants.SERVER_SDK_VERSION);
                    headersWithOauth.put(ImojiSDKConstants.Headers.LOCALE, Locale.getDefault().toString());
                    bodyWithOauth.put(ImojiSDKConstants.Params.AUTH_TOKEN, oAuthTokenResponse.getAccessToken());

                    return formEncodedConnection(path, method, responseClass, bodyWithOauth, headersWithOauth).executeImmediately();

                } catch (InterruptedException | ExecutionException e) {
                    if (e.getCause().getClass().isAssignableFrom(ApiException.class)) {
                        ApiException apiException = (ApiException) e.getCause();
                        ErrorResponse errorResponse = apiException.getErrorResponse();

                        // OAuth token verification error occurred, reset the token settings,
                        // generate a new token and call the same method again
                        if (errorResponse != null && ImojiSDKConstants.Errors.OAUTH_VERIFICATION_ERROR_STATUS.equals(errorResponse.getServerStatus())) {
                            clearOauthSettings();
                            oAuthTokenResponse = validateSession().executeImmediately(ApiTask.THREAD_POOL_EXECUTOR_VALIDATE);

                            if (oAuthTokenResponse != null) {
                                return oauthValidatedFormEncodedConnection(
                                        path, method, responseClass, body, headers
                                ).executeImmediately();
                            }
                        }
                    }

                    throw e;
                }
            }
        });
    }

    private <T extends ApiResponse> T readJsonResponse(@NonNull HttpURLConnection connection,
                                                       @NonNull Class<T> responseClass) throws IOException, ApiException {

        boolean succeeded = connection.getResponseCode() == HttpURLConnection.HTTP_OK ||
                connection.getResponseCode() == HttpURLConnection.HTTP_CREATED ||
                connection.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED;
        BufferedReader inputReader;
        if (succeeded) {
            inputReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            inputReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }
        StringWriter stringWriter = new StringWriter();

        String line;
        while ((line = inputReader.readLine()) != null) {
            stringWriter.append(line);
        }

        String contents = stringWriter.toString();
        if (succeeded) {
            return deserializeJsonResponse(responseClass, contents);
        } else {
            try {
                throw new ApiException(GSON_INSTANCE.fromJson(contents, ErrorResponse.class));
            } catch (JsonParseException e) {
                throw new ApiException("Unable to parse server response", new ErrorResponse("server_error", contents));
            }
        }
    }

    protected  <T extends ApiResponse> T deserializeJsonResponse(@NonNull Class<T> responseClass,
                                                                 @NonNull String jsonContents) {
        return GSON_INSTANCE.fromJson(jsonContents, responseClass);
    }

    private void clearOauthSettings() {
        this.storagePolicy.remove(ImojiSDKConstants.PREFERENCES_OAUTH_ACCESS_TOKEN_KEY);
        this.storagePolicy.remove(ImojiSDKConstants.PREFERENCES_OAUTH_REFRESH_TOKEN_KEY);
        this.storagePolicy.remove(ImojiSDKConstants.PREFERENCES_OAUTH_EXPIRATION_KEY);
    }

    @NonNull
    private static Map<String, String> checkedPairMap(@Nullable Map<String, String> map) {
        return map != null ? map : Collections.<String, String>emptyMap();
    }
}


text:
namespace dropkick.Configuration.Dsl.MsSql
{
    using DeploymentModel;
    using Tasks;
    using Tasks.MsSql;

    public class ProtoOutputSqlTask :
        BaseTask
    {
        readonly string _databaseName;

        public ProtoOutputSqlTask(string databaseName)
        {
            _databaseName = databaseName;
        }

        public string OutputSql { get; set; }

        public override Task ConstructTasksForServer(DeploymentServer server)
        {
            return new OutputSqlTask(server.Name, _databaseName)
                   {
                       OutputSql = OutputSql
                   };
        }
    }
}


text:
..
      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

Contributing to Poppy
=====================

First steps
-----------

Interested in contributing to Poppy? That's great to hear!

First of all, make sure to join our communication forums:

* Subscribe to our [[MailingLists|mailing lists]].
* Join us on IRC! You can chat with us directly in the '''#openstack-poppy''' channel on '''irc.freenode.org'''. Don't know to use IRC? You can find some directions in [[UsingIRC]] wiki page.
* Answer and ask questions on [https://ask.openstack.org/ Ask OpenStack].

How can I contribute?
---------------------

You can contribute to Poppy in many ways. Of course, coding is one, but you can also contribute as a tester, documenter, designer, or translator.

Coding
~~~~~~

Bug fixing and triaging
~~~~~~~~~~~~~~~~~~~~~~~

The first area where you can help is bug fixing. ''Confirmed'' bugs are usually your best choice. ''Triaged bugs'' should even contain tips on how you can fix them.

Once you selected the bug you want to work on, go ahead and assign it to yourself, branch the code, implement the fix, and propose your change for merging into trunk!

Some easy-to-fix bugs may be marked with the '''low-hanging-fruit''' tag. Those are good targets for a beginner.

Reported bugs need care: prioritizing them correctly, confirming them, making sure they don't go stale... All those tasks help immensely. If you want to start contributing in coding but you are not a hardcore developer, consider helping in this area!

Bugs can be marked with different tags according to their status, as follows:
* ''New'' bugs are those bugs that have been reported by a user but haven't been verified by the community yet.
* ''Confirmed'' bugs are those bugs that have been reproduced by someone else than the reporter.
* ''Triaged'' bugs are those bugs that have been reproduced by a core developer.
* ''Incomplete'' bugs are those bugs that don't have enough information to be reproduced.
* ''In Progress'' bugs are those bugs that are being fixed by a developer.
* ''Invalid'' bugs are those bugs that don't qualify as a bug. These usually stem from a support request or something unrelated to the project.

You can learn more, see Launchpad's [http://blog.launchpad.net/general/of-bugs-and-statuses Of Bugs and Statuses].

You only have to worry about ''New'' bugs. If you can reproduce them, you can mark them as ''Confirmed''. If you cannot reproduce them, you can ask the reporter to provide more information and mark them as ''Incomplete''. If you think that they aren't bugs, mark them as "Invalid". (Be careful! Asking someone else in Poppy is always a good idea.)

Also, you can contribute instructions about how to fix a given bug.

Check out the [[BugTriage|Bug Triage]] wiki for more information.

Reviewing
~~~~~~~~~

Every patch submitted to OpenStack gets reviewed before it can be approved and merged. We get a lot of contributions and everyone can - and is encouraged! [https://review.openstack.org/#/q/status:open+project:stackforge/poppy,n,z Review Poppy's existing patches]. Pick an open review and go through it. Test it if possible, and leave a comment with a +1 or -1 vote describing what you discovered. If you're planning to submit patches of your own, this is a great way to learn about what the community cares about and to learn about the code base.

Feature development
~~~~~~~~~~~~~~~~~~~

Once you get familiar with the code, you can start to contribute new features. New features get implemented every 6 months in a [[ReleaseCycle|development cycle]]. We use Launchpad [[Blueprints]] to track the design and implementation of significant features, and we use Design Summits every 6 months to discuss them in public. Code should be proposed for inclusion before we reach the final feature milestone of the development cycle.

Testing
~~~~~~~

Testing efforts are highly related to coding. If you find that there are test cases missing or that some tests could be improved, you are encouraged to report it as a bug, and then provide your fix. Learn more about this in Write The Tests!

Documenting
~~~~~~~~~~~

You can contribute to Poppy's Users Guide and Poppy's Wiki. See Documentation/HowTo for details, as well as Documentation/HowTo/FirstTimers, which has some other info that may be useful.

To fix a documentation bug, check the bugs marked with the 'doc' tag in Poppy's [https://bugs.launchpad.net/poppy/+bugs?field.tag=doc bug list]. In case that you want to report a documentation bug, then don't forget to add the 'doc' tag to it :)

You can also start by reading the developer documentation which is created using Sphinx as part of the code in the /doc/source/ directory and published to [https://poppy.readthedocs.org Read The Docs].

Also, monitor [http://ask.openstack.org Ask OpenStack] to curate the best answers that can be folded into the documentation.


text:
package de.akquinet.gomobile.deploymentadmin.tests;

import static org.ops4j.pax.exam.CoreOptions.felix;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import junit.framework.Assert;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.deploymentadmin.DeploymentAdmin;
import org.osgi.service.deploymentadmin.DeploymentException;
import org.osgi.service.deploymentadmin.DeploymentPackage;

import de.akquinet.gomobile.deployment.api.BundleResource;
import de.akquinet.gomobile.deployment.api.CheckingException;

@RunWith(JUnit4TestRunner.class)
public class InstallTest extends Helper {

    @Inject
    private BundleContext context;

    @Configuration
    public static Option[] configure() throws Exception {

        String dp1 = createDPWithOneBundle().toExternalForm();
        String dp11 = createDPWithAPath().toExternalForm();
        String dp2 = createDPWithTwoBundles().toExternalForm();
        String dp3 = createDPWithAResource().toExternalForm();
        String dp31 = createDPWithAResourceInAPath().toExternalForm();
        String empty = createEmptyDP().toExternalForm();
        String dp4 = createDPWithACustomizer().toExternalForm();

           Option[] opt =  options(
                   felix(),
                   systemProperty( "org.osgi.framework.storage.clean" ).value( "onFirstInit" ),
                   systemProperty("dp1").value(dp1),
                   systemProperty("dp11").value(dp11),
                   systemProperty("dp2").value(dp2),
                   systemProperty("dp3").value(dp3),
                   systemProperty("dp31").value(dp31),
                   systemProperty("empty").value(empty),
                   systemProperty("dp4").value(dp4),
                   Helper.getDPBundles()
                   );
           return opt;
       }

    @Test
    public void installSimpleDP() throws DeploymentException, IOException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        URL d = new URL((String)context.getProperty("dp1"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        dp.uninstall();

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);
    }

    @Test
    public void installDPWithPath() throws DeploymentException, IOException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        URL d = new URL((String)context.getProperty("dp11"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        dp.uninstall();

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);
    }

    @Test
    public void installWithTwoBundles() throws DeploymentException, IOException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        URL d = new URL((String)context.getProperty("dp2"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b1 = getBundleByName("org.apache.felix.log");
        Assert.assertNotNull(b1);
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());
        Assert.assertEquals(Bundle.ACTIVE, b1.getState());

        dp.uninstall();

        b1 = getBundleByName("org.apache.felix.log");
        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b1);
        Assert.assertNull(b2);
    }

    @Test
    public void installWithAResource() throws DeploymentException, Exception, InvalidSyntaxException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(context.getServiceReference(ConfigurationAdmin.class.getName()));
        Assert.assertNotNull(ca);

        URL d = new URL((String)context.getProperty("dp3"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        org.osgi.service.cm.Configuration[] configurations = ca.listConfigurations(null);
        boolean found = false;
        for(org.osgi.service.cm.Configuration c : configurations) {
            if (c.getPid().equals("de.akquinet.gomobile.x")) {
                found = true;
            }
        }

        if (! found) {
            Assert.fail("Configuration not found...");
        }

        dp.uninstall();

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);

        configurations = ca.listConfigurations(null);
        if (configurations != null) { // Must be removed...
            Assert.fail("Unexpected Configuration found...");
        }
    }

    @Test
    public void installWithAResourceWithAPath() throws DeploymentException, Exception, InvalidSyntaxException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(context.getServiceReference(ConfigurationAdmin.class.getName()));
        Assert.assertNotNull(ca);

        URL d = new URL((String)context.getProperty("dp31"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        org.osgi.service.cm.Configuration[] configurations = ca.listConfigurations(null);
        boolean found = false;
        for(org.osgi.service.cm.Configuration c : configurations) {
            if (c.getPid().equals("de.akquinet.gomobile.x")) {
                found = true;
            }
        }

        if (! found) {
            Assert.fail("Configuration not found...");
        }

        dp.uninstall();

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);

        configurations = ca.listConfigurations(null);
        if (configurations != null) { // Must be removed...
            Assert.fail("Unexpected Configuration found...");
        }
    }

    @Test
    public void installWithAResourceWithoutCA() throws DeploymentException, Exception, InvalidSyntaxException {
        // Stop CA:
        Bundle b = getBundleByName("org.apache.felix.configadmin");
        Assert.assertNotNull(b);
        b.stop();

        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ServiceReference ca = context.getServiceReference(ConfigurationAdmin.class.getName());
        Assert.assertNull(ca); // Uninstalled...

        URL d = new URL((String)context.getProperty("dp31"));

        try {
            admin.installDeploymentPackage(d.openStream());
            Assert.fail("Must fail : No CA");
        } catch (DeploymentException exp) {
            // Ok
        }

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);
        Bundle b1 = getBundleByName("de.akquinet.gomobile.configurable");
        Assert.assertNull(b1);

    }

    @Test
    public void installEmptyDP() throws DeploymentException, Exception, InvalidSyntaxException {
        int count = context.getBundles().length;
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

       URL d = new URL((String)context.getProperty("empty"));

        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        Assert.assertEquals(count, context.getBundles().length);

        dp.uninstall();

        Assert.assertEquals(count, context.getBundles().length);
    }

    @Test
    public void uninstallForcedOK() throws DeploymentException, Exception, InvalidSyntaxException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(context.getServiceReference(ConfigurationAdmin.class.getName()));
        Assert.assertNotNull(ca);

        URL d = new URL((String)context.getProperty("dp3"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        org.osgi.service.cm.Configuration[] configurations = ca.listConfigurations(null);
        boolean found = false;
        for(org.osgi.service.cm.Configuration c : configurations) {
            if (c.getPid().equals("de.akquinet.gomobile.x")) {
                found = true;
            }
        }

        if (! found) {
            Assert.fail("Configuration not found...");
        }

        boolean result = dp.uninstallForced();

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);

        configurations = ca.listConfigurations(null);
        if (configurations != null) { // Must be removed...
            Assert.fail("Unexpected Configuration found...");
        }

        // No problem expected, result = true
        Assert.assertTrue(result);
    }

    @Test
    public void uninstallForcedKO() throws DeploymentException, Exception, InvalidSyntaxException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(context.getServiceReference(ConfigurationAdmin.class.getName()));
        Assert.assertNotNull(ca);

        URL d = new URL((String)context.getProperty("dp3"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        org.osgi.service.cm.Configuration[] configurations = ca.listConfigurations(null);
        boolean found = false;
        for(org.osgi.service.cm.Configuration c : configurations) {
            if (c.getPid().equals("de.akquinet.gomobile.x")) {
                found = true;
            }
        }

        if (! found) {
            Assert.fail("Configuration not found...");
        }

        // Stop the CA
        Bundle b = getBundleByName("org.apache.felix.configadmin");
        Assert.assertNotNull(b);
        b.stop();

        boolean result = dp.uninstallForced();

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);

        // Problem expected (no CA), result = false
        Assert.assertFalse(result);
    }

    @Test
    public void installWithACustomizer() throws DeploymentException, Exception, InvalidSyntaxException {
        DeploymentAdmin admin = (DeploymentAdmin) context.getService(context.getServiceReference(DeploymentAdmin.class.getName()));
        Assert.assertNotNull(admin);

        ConfigurationAdmin ca = (ConfigurationAdmin) context.getService(context.getServiceReference(ConfigurationAdmin.class.getName()));
        Assert.assertNotNull(ca);

        URL d = new URL((String)context.getProperty("dp4"));
        DeploymentPackage dp = admin.installDeploymentPackage(d.openStream());

        // Check installed bundle
        Bundle b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNotNull(b2);

        Assert.assertEquals(Bundle.ACTIVE, b2.getState());

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        org.osgi.service.cm.Configuration[] configurations = ca.listConfigurations(null);
        boolean found = false;
        for(org.osgi.service.cm.Configuration c : configurations) {
            if (c.getPid().equals("de.akquinet.gomobile.x")) {
                found = true;
            }
        }

        if (! found) {
            Assert.fail("Configuration not found...");
        }

        dp.uninstall();

        Thread.sleep(1000); // Wait for processing.
        //TODO Change that by a waitForConfiguration...

        b2 = getBundleByName("org.apache.felix.bundlerepository");
        Assert.assertNull(b2);

        configurations = ca.listConfigurations(null);
        if (configurations != null) { // Must be removed...
            Assert.fail("Unexpected Configuration found...");
        }
    }

    private Bundle getBundleByName(String n) {
        Bundle[] bundles = context.getBundles();
        for(Bundle b : bundles) {
            if(b.getSymbolicName().contains(n)) {
                return b;
            }
        }
        return null;
    }

    public static URL createDPWithOneBundle() throws IOException, CheckingException {
        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
            = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp.addBundle(BUNDLE1).setSymbolicName("my.first.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp1.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createDPWithTwoBundles() throws Exception {
        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
        = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp.addBundle(BUNDLE1).addBundle(BUNDLE2)
            .setSymbolicName("my.second.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp2.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createDPWithAPath() throws Exception {
        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
        = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp.addBundle(BUNDLE1, "bundle/b1.jar").setSymbolicName("my.first2.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp1-1.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createDPWithAResource() throws IOException, CheckingException {
        File bundle = createConfigurableBundle();

        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
            = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp
            .addResource(RESOURCE, RESOURCE_PROCESSOR)
            .addBundle(BUNDLE1)
            .addBundle(bundle.toURI().toURL())
            .setSymbolicName("my.third.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp3.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createDPWithAResourceInAPath() throws IOException, CheckingException {
        File bundle = createConfigurableBundle();

        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
            = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp
            .addResource(RESOURCE, RESOURCE_PROCESSOR, "conf/ms.xml")
            .addBundle(BUNDLE1)
            .addBundle(bundle.toURI().toURL())
            .setSymbolicName("my.third.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp3-1.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createEmptyDP() throws IOException, CheckingException {
        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
            = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp
            .setSymbolicName("empty-dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/empty.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

    public static URL createDPWithACustomizer() throws IOException, CheckingException {
        File bundle = createConfigurableBundle();
        File rp = createRPBundle();
        de.akquinet.gomobile.deployment.api.DeploymentPackage dp
            = new de.akquinet.gomobile.deployment.api.DeploymentPackage();

        dp
            .addResource(RESOURCE, RESOURCE_PROCESSOR, "conf/ms.xml")
            .addResource(MY_RESOURCE, MY_RESOURCE_PROCESSOR, "props/prop.properties")
            .addBundle(BUNDLE1)
            .addBundle(new BundleResource().setURL(rp.toURI().toURL()).setCustomizer(true))
            .addBundle(bundle.toURI().toURL())
            .setSymbolicName("my.third.dp").setVersion("1.0.0");

        File dpf = new File("target/dp-test/dp3-1.dp");

        dp.build(dpf);

        return dpf.toURI().toURL();
    }

}


text:
from puzzle.constraints import constraints, validator

class DecomposeConstraints(constraints.Constraints):
  erase_border_percentile: (
      validator.NumberInRange(min_value=0, max_value=100)) = 25
  erase_border_distance: (
      validator.NumberInRange(min_value=0, max_value=5)) = 2
  erase_border_size:(
      validator.NumberInRange(min_value=1, max_value=5)) = 2
  required_color_band_retention: (
      validator.NumberInRange(min_value=0.01, max_value=1.0)) = 0.5