text:
package org.gavrog.joss.pgraphs.embed;

import java.io.PrintWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.gavrog.box.collections.Pair;
import org.gavrog.box.simple.Strings;
import org.gavrog.jane.compounds.Matrix;
import org.gavrog.jane.numbers.IArithmetic;
import org.gavrog.jane.numbers.Real;
import org.gavrog.joss.geometry.CellCorrection;
import org.gavrog.joss.geometry.CoordinateChange;
import org.gavrog.joss.geometry.Lattices;
import org.gavrog.joss.geometry.Operator;
import org.gavrog.joss.geometry.Point;
import org.gavrog.joss.geometry.SpaceGroupFinder;
import org.gavrog.joss.geometry.Vector;
import org.gavrog.joss.pgraphs.basic.Cover;
import org.gavrog.joss.pgraphs.basic.IEdge;
import org.gavrog.joss.pgraphs.basic.INode;
import org.gavrog.joss.pgraphs.basic.PeriodicGraph;

/**
 * Stores and prints a graph with its name, embedding and space group symmetry.
 */
public class ProcessedNet {
    private static DecimalFormatSymbols fmt = new DecimalFormatSymbols();

    static {
        fmt.setInfinity("inf");
        fmt.setNaN("nan");
    }

    private static DecimalFormat fmtReal4 = new DecimalFormat("0.0000", fmt);
    private static DecimalFormat fmtReal5 = new DecimalFormat("0.00000", fmt);

    final static boolean DEBUG = false;

    /*
     * Auxiliary type.
     */
    private class PlacedNode implements Comparable<PlacedNode> {
        final public INode v;
        final public Point p;

        public PlacedNode(final INode v, final Point p) {
            this.v = v;
            this.p = p;
        }

        /* (non-Javadoc)
         * @see java.lang.Comparable#compareTo(java.lang.Object)
         */
        public int compareTo(final PlacedNode other) {
            final Point p = this.p;
            final Point q = other.p;
            final int dim = p.getDimension();
            final Point o = Point.origin(dim);
            final Vector s = (Vector) p.minus(o);
            final Vector t = (Vector) q.minus(o);
            if (s.isNegative()) {
                if (t.isNonNegative()) {
                    return 1;
                }
            } else if (t.isNegative()) {
                return -1;
            }
            int diff = count_zeroes(t) - count_zeroes(s);
            if (diff != 0) {
                return diff;
            }
            diff = cmpCoords(Vector.dot(s, s), Vector.dot(t, t));
            if (diff != 0) {
                return diff;
            }
            for (int i = 0; i < dim; ++i) {
                diff = cmpCoords(p.get(i), q.get(i));
                if (diff != 0) {
                    return diff;
                }
            }
            return 0;
        }

		private int count_zeroes(final Vector s) {
			int n = 0;
			for (int i = 0; i < s.getDimension(); ++i) {
				if (((Real) s.get(i).abs()).doubleValue() < 1e-6) {
					++n;
				}
			}
			return n;
		}

		private int cmpCoords(final IArithmetic a, final IArithmetic b) {
            final double x = ((Real) a).doubleValue();
            final double y = ((Real) b).doubleValue();
            if (x < 0) {
                if (y > 0) {
                    return 1;
                }
            } else if (y < 0) {
                return -1;
            }
            final double d = Math.abs(x) - Math.abs(y);
            if (Math.abs(d) < 1e-6) {
                return 0;
            } else {
                return Double.compare(Math.abs(x), Math.abs(y));
            }
        }
    };

    private boolean verified = false;
    private final PeriodicGraph graph;
    private final String name;
    private final Map<INode, String> node2name;
    private final SpaceGroupFinder finder;
    private final Embedder embedder;

    public ProcessedNet(
			final PeriodicGraph G,
			final String name,
			final Map<INode, String> node2name,
			final SpaceGroupFinder finder,
			final Embedder embedder)
    {
        this.graph = G;
        this.name = name;
        this.node2name = node2name;
        this.finder = finder;
        this.embedder = embedder;
    }

    public void writeEmbedding(
            final Writer stream,
            final boolean cgdFormat,
			final boolean fullCell,
			final String posType)
    {
		final PrintWriter out = new PrintWriter(stream);

        // --- extract some data from the arguments
        if (DEBUG) {
        	System.out.println("\t\t@@@ In writeEmbedding(): preliminaries...");
        }

        final int d = graph.getDimension();
        final CoordinateChange toStd = finder.getToStd();
        final Matrix gram = embedder.getGramMatrix();

        // --- process unit cell parameters (possibly correcting settings)
        if (DEBUG) {
        	System.out.println("\t\t@@@ Computing cell parameters...");
        }

        CoordinateChange correction = processCellParameters(out,
				cgdFormat, fullCell);

        // --- compute orbit graph with respect to a conventional unit cell
        if (DEBUG) {
        	System.out.println("\t\t@@@ Computing full unit cell...");
        }

        final Cover cov = graph.conventionalCellCover();

        // --- lift relaxed node positions to the conventional unit cell
        if (DEBUG) {
        	System.out.println("\t\t@@@ Computing full list of node positions...");
        }

        final Map<INode, Point> pos = embedder.getPositions();
		final INode v0 = cov.nodes().next();
		final Vector shift = (Vector) pos.get(cov.image(v0)).times(
				toStd).minus(cov.liftedPosition(v0, pos));
		final Map<INode, Point> lifted = new HashMap<INode, Point>();
		for (final INode v: cov.nodes()) {
			lifted.put(v, (Point) cov.liftedPosition(v, pos).plus(shift)
			        .times(correction));
		}

        // --- if there's translational freedom, shift some node to a nice place
		final Vector tmp[] = graph.getSpaceGroup().shiftSpace();
		if (tmp.length > 0) {
			for (int i = 0; i < tmp.length; ++i) {
				tmp[i] = (Vector) tmp[i].times(toStd).times(correction);
			}
			final Matrix shiftSpace = Vector.toMatrix(tmp);
			final Operator proj = Operator.orthogonalProjection(shiftSpace,
					Matrix.one(d));
			final INode v = lifted.keySet().iterator().next();
			final Point p = lifted.get(v);
			final Vector s = (Vector) Point.origin(d).minus(p.times(proj));
			final CoordinateChange corrective_shift = new CoordinateChange(
					new Operator(s));
			for (final INode w: lifted.keySet()) {
				lifted.put(w, (Point) lifted.get(w).times(corrective_shift));
			}
			correction = (CoordinateChange) correction.times(corrective_shift);
		}

		// --- find the node representatives to print
        final boolean allNodes = fullCell;
        if (DEBUG) {
        	System.out.println("\t\t@@@ Computing node representatives...");
        }

        final Map<INode, Point> reps = nodeReps(cov, lifted, allNodes);

        // --- print the node positions
        if (!cgdFormat) {
			out.println("   " + posType	+ " positions:");
		}
        if (DEBUG) {
        	System.out.println("\t\t@@@ Printing node positions...");
        }
        int last = 0;
        for (final INode v: reps.keySet()) {
			final Point p = reps.get(v);
			final String name;
			if (allNodes) {
				name = "" + (++last);
			} else {
				name = Strings.parsable(this.node2name.get(cov.image(v)),
				        false);
			}

			// --- print them
			if (cgdFormat) {
				out.print("  NODE " + name + " "
						+ cov.new CoverNode(v).degree() + " ");
			} else {
				out.print("      Node " + name + ":   ");
			}
			for (int i = 0; i < d; ++i) {
				out.print(" "
				        + fmtReal5.format(((Real) p.get(i)).doubleValue()));
			}
			out.println();
		}

        // --- print the edges
        if (DEBUG) {
        	System.out.println("\t\t@@@ Printing edges...");
        }

        if (!cgdFormat) {
            out.println("   Edges:");
        }
        final List<Pair<PlacedNode, PlacedNode>> ereps =
                edgeReps(cov, reps, lifted, correction, fullCell);
        for (final Pair<PlacedNode, PlacedNode> pair: ereps) {
            final Point p = pair.getFirst().p;
            final Point q = pair.getSecond().p;

            // --- print its start and end positions
            if (cgdFormat) {
                out.print("  EDGE ");
            } else {
                out.print("     ");
            }
            for (int i = 0; i < d; ++i) {
                out.print(" " + fmtReal5.format(((Real) p.get(i)).doubleValue()));
            }
            if (cgdFormat) {
                out.print("  ");
            } else {
                out.print("  <-> ");
            }
            for (int i = 0; i < d; ++i) {
                out.print(" " + fmtReal5.format(((Real) q.get(i)).doubleValue()));
            }
            out.println();
        }

        // --- print the edge centers
        if (DEBUG) {
        	System.out.println("\t\t@@@ Printing edge centers...");
        }

        if (!cgdFormat) {
            out.println("   Edge centers:");
        }
        for (final Pair<PlacedNode, PlacedNode> pair: ereps) {
            final Point p = pair.getFirst().p;
            final Point q = pair.getSecond().p;

            if (cgdFormat) {
                out.print("# EDGE_CENTER ");
            } else {
                out.print("     ");
            }
            for (int i = 0; i < d; ++i) {
            	final double s = ((Real) p.get(i)).doubleValue();
            	final double t = ((Real) q.get(i)).doubleValue();
                out.print(" " + fmtReal5.format((s + t) / 2));
            }
            out.println();
        }

        // --- finish up
        writeStatistics(out, gram, pos, cgdFormat);
        if (cgdFormat) {
            out.println("END");
            out.println();
        }
        out.flush();
        if (DEBUG) {
        	System.out.println("\t\t@@@ In writeEmbedding(): done!");
        }

    }

	/**
	 * @param out
	 * @param gram
	 * @param pos
	 */
	private void writeStatistics(
	        final PrintWriter out,
	        final Matrix gram,
			final Map<INode, Point> pos,
            final boolean cgdFormat) {
		// --- write edge statistics
		if (DEBUG) {
			System.out.println("\t\t@@@ Computing edge statistics...");
		}

		final String min = fmtReal5.format(embedder.minimalEdgeLength());
		final String max = fmtReal5.format(embedder.maximalEdgeLength());
		final String avg = fmtReal5.format(embedder.averageEdgeLength());

        if (cgdFormat) {
            out.println("# EDGE_MIN " + min);
            out.println("# EDGE_AVG " + avg);
            out.println("# EDGE_MAX " + max);
        }
        else {
            out.println();
            out.println("   Edge statistics: minimum = " + min + ", maximum = "
                        + max + ", average = " + avg);
        }

		// --- compute and write angle statistics
		if (DEBUG) {
			System.out.println("\t\t@@@ Computing angle statistics...");
		}

		double minAngle = Double.MAX_VALUE;
		double maxAngle = 0.0;
		double sumAngle = 0.0;
		int count = 0;

		for (final INode v: graph.nodes()) {
		    final Point p = pos.get(v);
		    final List<IEdge> incidences = graph.allIncidences(v);
		    final List<Vector> vectors = new ArrayList<Vector>();
		    for (final IEdge e: incidences) {
		        final INode w = e.target();
		        final Point q = (Point) pos.get(w);
		        vectors.add((Vector) q.plus(graph.getShift(e)).minus(p));
		    }
		    final int m = vectors.size();
		    for (int i = 0; i < m; ++i) {
		        final Vector s = vectors.get(i);
		        final double ls =
		                ((Real) Vector.dot(s, s, gram)).sqrt().doubleValue();
		        for (int j = i + 1; j < m; ++j) {
		            final Vector t = vectors.get(j);
		            final double lt = ((Real) Vector.dot(t, t, gram)).sqrt()
		                    .doubleValue();
		            final double dot =
		                    ((Real) Vector.dot(s, t, gram)).doubleValue();
                    double angle = 0.0;
                    if (ls * lt > 1e-8) {
                        final double arg =
                            Math.max(-1, Math.min(1, dot / (ls * lt)));
                        angle = Math.acos(arg) / Math.PI * 180;
                    }
		            minAngle = Math.min(minAngle, angle);
		            maxAngle = Math.max(maxAngle, angle);
		            sumAngle += angle;
		            ++count;
		        }
		    }
		}

        if (cgdFormat) {
            out.println("# ANGLE_MIN " + fmtReal5.format(minAngle));
            out.println("# ANGLE_AVG " + fmtReal5.format(sumAngle / count));
            out.println("# ANGLE_MAX " + fmtReal5.format(maxAngle));
        }
        else {
            out.println("   Angle statistics: minimum = " + fmtReal5.format(minAngle)
                        + ", maximum = " + fmtReal5.format(maxAngle) + ", average = "
                        + fmtReal5.format(sumAngle / count));
        }
        out.flush();

		// --- write the shortest non-bonded distance
		if (DEBUG) {
			System.out.println("\t\t@@@ Computing shortest non-bonded distance...");
		}

		final double dist = smallestNonBondedDistance(graph, pos, gram);
		if (dist < 0) {
			out.println("   Shortest non-bonded distance not determined.");
        }
        else if (cgdFormat) {
            out.println("# SMALLEST_SEPARATION " + fmtReal5.format(dist));
		}
        else {
			out.println("   Shortest non-bonded distance = "
                        + fmtReal5.format(dist));
		}

		// --- write the degrees of freedom as found by the embedder
        if (DEBUG) {
            System.out.println("\t\t@@@ Computing degrees of freedom...");
        }

        int dof = embedder.degreesOfFreedom();
        if (cgdFormat) {
            out.println("# DEGREES_OF_FREEDOM " + dof);
        }
        else {
            out.println();
            out.println("   Degrees of freedom: " + dof);
        }
	}

	/**
	 * @param out
	 * @param cgdFormat
	 * @param fullCell
	 * @return
	 */
	private CoordinateChange processCellParameters(final PrintWriter out,
			final boolean cgdFormat, boolean fullCell) {
        final int d = graph.getDimension();
        final String extendedGroupName = finder.getExtendedGroupName();
        final CoordinateChange toStd = finder.getToStd();
        final CoordinateChange fromStd = (CoordinateChange) toStd.inverse();
        final boolean cellRelaxed = embedder.cellRelaxed();
        final Matrix gram = embedder.getGramMatrix();

		final CoordinateChange correction;
		if (d == 3) {
			// --- correct to a reduced cell for monoclinic and triclinic groups
        	final CellCorrection cc = new CellCorrection(finder, gram);
			correction = cc.getCoordinateChange();
			final String correctedGroupName;
			if (cc.getGroupName().equals(finder.getGroupName())) {
				correctedGroupName = extendedGroupName;
			} else {
				correctedGroupName = cc.getGroupName();
			}

			if (DEBUG) {
				System.out.println("\t\t@@@   cell correction = " + correction);
			}
			final CoordinateChange ctmp = (CoordinateChange) correction
					.inverse().times(fromStd);
			final Vector x = (Vector) Vector.unit(3, 0).times(ctmp);
			final Vector y = (Vector) Vector.unit(3, 1).times(ctmp);
			final Vector z = (Vector) Vector.unit(3, 2).times(ctmp);

			// --- compute the cell parameters
			if (DEBUG) {
				System.out.println("\t\t\t x = " + x);
				System.out.println("\t\t\t y = " + y);
				System.out.println("\t\t\t z = " + z);
				System.out.println("\t\t\t Gram = " + gram);
				System.out.println("\t\t\t\t determinant = " + gram.determinant());
			}
			final double a = Math.sqrt(((Real) Vector.dot(x, x, gram))
					.doubleValue());
			final double b = Math.sqrt(((Real) Vector.dot(y, y, gram))
					.doubleValue());
			final double c = Math.sqrt(((Real) Vector.dot(z, z, gram))
					.doubleValue());
			final double f = 180.0 / Math.PI;

			final double alpha = b * c < 1e-8 ? 0.0 :
                f * Math.acos(((Real) Vector.dot(y, z, gram)).doubleValue()
                              / (b * c));
			final double beta = a * c < 1e-8 ? 0.0 :
                f * Math.acos(((Real) Vector.dot(x, z, gram)).doubleValue()
                              / (a * c));
			final double gamma = a * b < 1e-8 ? 0.0 :
                f * Math.acos(((Real) Vector.dot(x, y, gram)).doubleValue()
                              / (a * b));

			// --- print the cell parameters
			if (DEBUG) {
				System.out.println("\t\t@@@ Writing cell parameters...");
			}

	        // --- print a header if necessary
	        if (DEBUG) {
	        	System.out.println("\t\t@@@ Writing header...");
	        }

	        if (cgdFormat) {
	            out.println("CRYSTAL");
	            out.println("  NAME " + Strings.parsable(name, false));
	            if (fullCell) {
	            		out.println("  GROUP P1");
	            } else {
	                out.println("  GROUP " + correctedGroupName);
	            }
	        } else if (correctedGroupName != extendedGroupName && ! fullCell) {
	        	out.println("   Group setting modified to " + correctedGroupName);
	        }

            final double cellVolume =
                ((Real) Vector.volume3D(x, y, z)).doubleValue()
                * Math.sqrt(((Real) gram.determinant()).doubleValue());

	        // --- print the cell info
			if (cgdFormat) {
				out.println("  CELL " + fmtReal5.format(a) + " "
                        + fmtReal5.format(b) + " " + fmtReal5.format(c) + " "
                        + fmtReal4.format(alpha) + " " + fmtReal4.format(beta)
                        + " " + fmtReal4.format(gamma));
                out.println("  CELL_VOLUME " + fmtReal5.format(cellVolume));
			} else {
				if (fullCell) {
					out.println("   Coordinates below are given for a full "
                            + "conventional cell.");
				}
				out.println("   " + (cellRelaxed ? "R" : "Unr")
                        + "elaxed cell parameters:");
                out.println("       a = " + fmtReal5.format(a) + ", b = "
                        + fmtReal5.format(b) + ", c = " + fmtReal5.format(c));
                out.println("       alpha = " + fmtReal4.format(alpha)
                        + ", beta = " + fmtReal4.format(beta) + ", gamma = "
                        + fmtReal4.format(gamma));
				out.println("   Cell volume: " + fmtReal5.format(cellVolume));
			}
		} else if (d == 2){
			// --- the cell vectors in the embedder's coordinate system
			Vector x = (Vector) Vector.unit(2, 0).times(fromStd);
			Vector y = (Vector) Vector.unit(2, 1).times(fromStd);

			// --- correct to a reduced cell for monoclinic and triclinic groups
			correction = new CoordinateChange(Operator.identity(d));

			// --- compute the cell parameters
			final double a = Math.sqrt(((Real) Vector.dot(x, x, gram))
					.doubleValue());
			final double b = Math.sqrt(((Real) Vector.dot(y, y, gram))
					.doubleValue());
			final double f = 180.0 / Math.PI;
			final double gamma = a * b < 1e-8 ? 0.0 :
                f * Math.acos(((Real) Vector.dot(x, y, gram)).doubleValue()
                              / (a * b));

	        // --- print a header if necessary
	        if (DEBUG) {
	        	System.out.println("\t\t@@@ Writing header...");
	        }

	        if (cgdFormat) {
	            out.println("CRYSTAL");
	            out.println("  NAME " + Strings.parsable(name, false));
	            if (fullCell) {
	            	out.println("  GROUP p1");
	            } else {
	                out.println("  GROUP " + extendedGroupName);
	            }
	        }

            final double cellVolume =
                ((Real) Vector.area2D(x, y)).doubleValue()
                * Math.sqrt(((Real) gram.determinant()).doubleValue());

			// --- print the cell parameters
			if (DEBUG) {
				System.out.println("\t\t@@@ Writing cell parameters...");
			}

			if (cgdFormat) {
				out.println("  CELL " + fmtReal5.format(a) + " "
						+ fmtReal5.format(b) + " " + fmtReal4.format(gamma));
                out.println("  CELL_VOLUME " + fmtReal5.format(cellVolume));
			} else {
				if (fullCell) {
					out.println("   Coordinates are for a full conventional cell.");
				}
				out.println("   " + (cellRelaxed ? "R" : "Unr")
						+ "elaxed cell parameters:");
				out.println("       a = " + fmtReal5.format(a) + ", b = "
						+ fmtReal5.format(b) + ", gamma = "
						+ fmtReal4.format(gamma));
				out.println("   Cell volume: " + fmtReal5.format(cellVolume));
			}
		} else if (d == 1) {
            correction = new CoordinateChange(Operator.identity(d));

            if (DEBUG) {
                System.out.println("\t\t@@@ Writing header...");
            }

            if (cgdFormat) {
                out.println("CRYSTAL");
                out.println("  NAME " + Strings.parsable(name, false));
                if (fullCell) {
                    out.println("  GROUP op1");
                } else {
                    out.println("  GROUP " + extendedGroupName);
                }
            }
		} else {
			throw new RuntimeException("dimension must be 2 or 3");
		}
		return correction;
	}

    private Map<INode, Point> nodeReps(
            final PeriodicGraph cov,
            final Map<INode, Point> lifted,
			final boolean allNodes)
	{
		final Map<INode, Point> reps = new LinkedHashMap<INode, Point>();
        for (final Iterator<Set<INode>> orbits = cov.nodeOrbits();
                orbits.hasNext();) {
            // --- grab the next node orbit
            final Set<INode> orbit = orbits.next();

            // --- find positions for all nodes
            final List<PlacedNode> tmp = new ArrayList<PlacedNode>();
            for (final INode v: orbit) {
                final Point p = lifted.get(v).modZ();
                tmp.add(new PlacedNode(v, p));
            }

            // --- sort by position
            Collections.sort(tmp);

            // --- extract the node (or nodes) to use
            if (allNodes) {
                for (int i = 0; i < tmp.size(); ++i) {
                    final PlacedNode pn = tmp.get(i);
                    reps.put(pn.v, pn.p);
                }
            } else {
                final PlacedNode pn = tmp.get(0);
                reps.put(pn.v, pn.p);
            }
        }

        return reps;
    }

    private List<Pair<PlacedNode, PlacedNode>> edgeReps(
            final PeriodicGraph cov,
            final Map<INode, Point> reps,
			final Map<INode, Point> lifted,
			final CoordinateChange correction,
			final boolean allEdges)
	{
        final List<Pair<PlacedNode, PlacedNode>> result =
                new LinkedList<Pair<PlacedNode, PlacedNode>>();

        for (final Iterator<Set<IEdge>> orbits = cov.edgeOrbits();
                orbits.hasNext();) {
            // --- grab the next edge orbit
            final Set<IEdge> orbit = orbits.next();

            // --- extract edges starting or ending in a node in reps
            final List<IEdge> edges = new ArrayList<IEdge>();
            for (final IEdge e: orbit) {
                if (reps.containsKey(e.source())) {
                    edges.add(e);
                }
                if (reps.containsKey(e.target())) {
                    edges.add(e.reverse());
                }
            }

            // --- find positions for all the end points
            final List<Pair<PlacedNode, PlacedNode>> candidates =
                    new ArrayList<Pair<PlacedNode, PlacedNode>>();
            for (final IEdge e: edges) {
                final INode v = e.source();
                final INode w = e.target();
                final Point p = lifted.get(v);
                final Point q = (Point) lifted.get(w)
                        .plus(cov.getShift(e).times(correction));
				final Point p0 = p.modZ();
				final Point q0 = (Point) q.minus(p.minus(p0));
				candidates.add(new Pair<PlacedNode, PlacedNode>(
				        new PlacedNode(v, p0), new PlacedNode(w, q0)));
            }

            // --- sort edges by end point positions
            Collections.sort(candidates,
                    Pair.<PlacedNode, PlacedNode>defaultComparator());

            // --- extract the edge (or edges) to use
            if (allEdges) {
                result.addAll(candidates);
            } else {
                result.add(candidates.get(0));
            }
        }
        return result;
    }

    /**
     * Computes angle sizes.
     *
     * @param G    a periodic graph.
     * @param pos  positions for the vertices of G.
     * @param gram a Gram matrix representing the chosen unit cell parameters
     * @return the list of all angle sizes in degrees.
     */
    public static List<Double> angleSizes(
            final PeriodicGraph G,
            final Map<INode, Point> pos,
            final Matrix gram) {

        final List<Double> angles = new ArrayList<Double>();;

		for (final INode v: G.nodes()) {
		    final Point p = pos.get(v);
		    final List<IEdge> incidences = G.allIncidences(v);
		    final List<Vector> vectors = new ArrayList<Vector>();
		    for (final IEdge e: incidences) {
		        final INode w = e.target();
		        final Point q = (Point) pos.get(w);
		        vectors.add((Vector) q.plus(G.getShift(e)).minus(p));
		    }
		    final int m = vectors.size();
		    for (int i = 0; i < m; ++i) {
		        final Vector s = vectors.get(i);
		        final double ls =
		                ((Real) Vector.dot(s, s, gram)).sqrt().doubleValue();
		        for (int j = i + 1; j < m; ++j) {
		            final Vector t = vectors.get(j);
		            final double lt = ((Real) Vector.dot(t, t, gram)).sqrt()
		                    .doubleValue();
		            final double dot =
		                    ((Real) Vector.dot(s, t, gram)).doubleValue();
                    double angle = 0.0;
                    if (ls * lt > 1e-8) {
                        final double arg =
                            Math.max(-1, Math.min(1, dot / (ls * lt)));
                        angle = Math.acos(arg) / Math.PI * 180;
                    }
                    angles.add(angle);
		        }
		    }
		}

        return angles;
    }

    /**
     * Does what it says.
     *
     * @param G         a periodic graph.
     * @param embedder  an embedding for G.
     * @return the smallest distance between nodes that are not connected.
     */
    public static double smallestNonBondedDistance(
            final PeriodicGraph G,
            final Map<INode, Point> pos,
            final Matrix gram) {
        // --- get some data about the graph and embedding
    	final int dim = G.getDimension();

        // --- compute a Dirichlet domain for the translation lattice
        final Vector basis[] = Vector.rowVectors(Matrix.one(G.getDimension()));
		if (DEBUG) {
			System.out.println("\t\t\t@@@ Computing dirichlet vectors...");
		}
        final Vector dirichlet[] = Lattices.dirichletVectors(basis, gram);
		if (DEBUG) {
			System.out.println("\t\t\t@@@ Computing reduced basis...");
		}
        final Vector reduced[] = Lattices.reducedLatticeBasis(basis, gram);

        // --- find vectors that address neighborhood of dirichlet domain
		if (DEBUG) {
			System.out.println("\t\t\t@@@ Computing neighborhood vectors...");
		}
        final Matrix M = Vector.toMatrix(reduced);
        final List<Vector> cellNeighbors = new ArrayList<Vector>();
        final int f[] = new int[dim];
        for (int i = 0; i < dim; ++i) f[i] = -1;
        while (true) {
        	final Vector v = new Vector(f);
        	cellNeighbors.add(new Vector((Matrix) v.getCoordinates().times(M)));
        	int i = dim-1;
        	while (i >= 0 && f[i] == 1) --i;
        	if (i < 0) {
        		break;
        	} else {
        		++f[i++];
        		while (i < dim) f[i++] = -1;
        	}
        }

        // --- smallest distance seen so far
        double minDist = Double.MAX_VALUE;

        // --- loop over all pairs of points in the repeat unit
		if (DEBUG) {
			System.out.println("\t\t\t@@@ Looping over node pairs...");
		}
        for (final INode v: G.nodes()) {
            final Point p = pos.get(v);
            for (final INode w: G.nodes()) {
                final Point q = pos.get(w);

                // --- find a closest translate of w
                final Point d = (Point) q.minus(p).plus(Point.origin(dim));
                final Vector s =
                	Lattices.dirichletShifts(d, dirichlet, gram, 1)[0];

                // --- determine excluded translates and seeds
                final Set<Vector> excluded = new HashSet<Vector>();
                if (v.equals(w)) {
                	excluded.add(Vector.zero(dim));
                }
                final Set<Vector> seeds = new HashSet<Vector>();
                seeds.add(Vector.zero(dim));
                for (final IEdge e: G.allIncidences(v)) {
                	final INode u = e.target();
                	if (u.equals(w)) {
                		excluded.add(G.getShift(e));
                		seeds.add(G.getShift(e));
                	}
                }

                // --- find closest translate that isn't a neighbor of v
                for (final Vector seed: seeds) {
					for (final Vector n: cellNeighbors) {
						final Vector t = (Vector) n.plus(s).plus(seed);
						if (!excluded.contains(t)) {
							final Point r = (Point) q.plus(t);
							final Vector x = (Vector) r.minus(p);
							final double dist = ((Real) Vector.dot(x, x, gram))
									.doubleValue();
							if (dist < minDist) {
								minDist = dist;
							}
						}
					}
				}
            }
        }

        // --- return the result
        if (minDist == Double.MAX_VALUE) {
        	return -1.0;
        } else {
        	return Math.sqrt(minDist);
        }
    }

    /**
     * @return the graph.
     */
    public PeriodicGraph getGraph() {
        return this.graph;
    }

    /**
     * @return the name.
     */
    public String getName() {
        return this.name;
    }

    /**
     * @return the current value of verified.
     */
    public boolean getVerified() {
        return this.verified;
    }

    /**
     * @param verified The new value for verified.
     */
    public void setVerified(boolean verified) {
        this.verified = verified;
    }

    public boolean hasEmbedding() {
        return this.embedder != null;
    }
}


text:
require 'spec_helper'

describe Projects::AvatarsController do
  let(:project) { create(:project, :repository) }

  before do
    controller.instance_variable_set(:@project, project)
  end

  describe 'GET #show' do
    subject { get :show, namespace_id: project.namespace, project_id: project }

    context 'when repository has no avatar' do
      it 'shows 404' do
        subject

        expect(response).to have_gitlab_http_status(404)
      end
    end

    context 'when repository has an avatar' do
      before do
        allow(project).to receive(:avatar_in_git).and_return(filepath)
      end

      context 'when the avatar is stored in the repository' do
        let(:filepath) { 'files/images/logo-white.png' }

        it 'sends the avatar' do
          subject

          expect(response).to have_gitlab_http_status(200)
          expect(response.header['Content-Type']).to eq('image/png')
          expect(response.header[Gitlab::Workhorse::SEND_DATA_HEADER]).to start_with('git-blob:')
        end
      end

      context 'when the avatar is stored in lfs' do
        it_behaves_like 'repository lfs file load' do
          let(:filename) { 'lfs_object.iso' }
          let(:filepath) { "files/lfs/#{filename}" }
        end
      end
    end
  end

  describe 'DELETE #destroy' do
    it 'removes avatar from DB by calling destroy' do
      delete :destroy, namespace_id: project.namespace.id, project_id: project.id

      expect(project.avatar.present?).to be_falsey
      expect(project).to be_valid
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import * as vscode from 'vscode';

export interface IStylefmtOptions {
	rules: object;
	configBasedir: string;
	configFile: string;
}

export interface IStylefmtSettings {
	configBasedir?: string;
	config?: string | object;
	useStylelintConfigOverrides?: boolean;
	showErrorMessages?: boolean;
}

export interface IStylelintSettings {
	configOverrides?: any;
}

export interface IVSCodeSettings {
	formatOnSave?: boolean;
}

export type ISettings = IStylelintSettings & IStylefmtSettings & IVSCodeSettings;

export interface IResult {
	css: string;
	range: vscode.Range;
}


text:
<virtual-sensor name="EmailScriptlet" priority="10">
    <processing-class>
        <class-name>gsn.processor.ScriptletProcessor</class-name>
        <init-params>
            <param name="persistant">false</param>
            <param name="scriptlet">
                <![CDATA[
                    // This script sends an email to alert that the heap value (from the local wrapper)
                    // has reached a new maxima.
                    // Please set your SMTP configuration (in the conf/emails.properties) prior to use this script.

                    // Initialize the stateful variable maxima
                    if ( ! isdef('maxima'))
                        maxima = 0;

                    // Comparing the new heap size with the maxima
                    if (maxima < HEAP) {

                        maxima = HEAP;

                        // Notify by email
                        def emailTitle = "GSN Notification - New HEAP maxima reached: " + HEAP;
                        def emailContent = "Warning, the HEAP maxima has been reached: " + HEAP;
                        def recipients = ["recipient1@server.com", "recipient2@server.com", "recipientn@server.com"]; // Define one or more recipients

                        sendEmail(recipients, emailTitle, emailContent); // note that the sendMail method is, by default, imported statically to the script.
                    }
                ]]>
            </param>
        </init-params>
        <output-structure/>
    </processing-class>
    <description>
        This Virtual Sensor demonstrates the use of the scriplet processor (gsn.processor.ScriptletProcessor) for email
        notifications. It gets its data from the MemoryMonitorVS and sends a new email each time the MemoryMonitorVS.HEAP field reached a new maxima.
    </description>
    <addressing/>
    <storage history-size="1"/>
    <streams>
        <stream name="stream1">
            <source alias="source1" storage-size="1" sampling-rate="1">
                <address wrapper="local">
                    <predicate key="name">MemoryMonitorVS</predicate>
                </address>
                <query>select * from wrapper</query>
            </source>
            <query>select * from source1</query>
        </stream>
    </streams>
</virtual-sensor>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/eventarc/v1/eventarc.proto

package com.google.cloud.eventarc.v1;

public interface GetProviderRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.eventarc.v1.GetProviderRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the provider to get.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. The name of the provider to get.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.facebook.samples.hellofacebook" android:versionCode="1" android:versionName="1.0">
	<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="29" />
	<application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar">
	</application>
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>


text:
import {
	assert,
	html,
	fixtureSync,
	oneEvent,
	nextFrame,
} from '@open-wc/testing';
import { mock } from 'sinon';

import { createElement, navigate, documentUrl } from '../src/use-routes';
import { hashbang } from '../src/match';
import { Route } from '../src/router';

/* eslint-disable max-lines-per-function */
suite('cosmoz-page-router', () => {
	const routes: Route[] = [
		{
			rule: /^\/$/u,
			handle: () =>
				import('../stories/views/home.js').then(() =>
					createElement('demo-home')
				),
		},
		{
			rule: hashbang(/^\/view-1/u),
			handle: () =>
				import('../stories/views/view-1.js').then(() =>
					createElement('view-1')
				),
		},
		{
			rule: hashbang(/^\/param-reading-view/u),
			handle: (result) =>
				import('../stories/views/param-reading-view.js').then(() => {
					const entries = result.match.url?.searchParams?.entries();
					return createElement(
						'param-reading-view',
						entries ? Object.fromEntries(entries) : {}
					);
				}),
		},
		{
			rule: hashbang(/^\/error/u),
			handle: () => Promise.reject(new Error('testing')),
		},
	];
	let url: string;

	suiteSetup(async () => {
		url = documentUrl();
		await import('../src/router');
	});
	suiteTeardown(() => navigate(url, null, { notify: false }));

	test('renders home', async () => {
		navigate('/');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`);
		await oneEvent(router, 'route-loaded');
		await nextFrame();
		assert.shadowDom.equal(router, '<demo-home></demo-home>');
	});

	test('renders view-1', async () => {
		navigate('#!/view-1');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`);
		await oneEvent(router, 'route-loaded');
		await nextFrame();
		assert.shadowDom.equal(router, '<view-1></view-1>');
	});

	test('renders not-found', async () => {
		navigate('#/not-found');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`);
		await oneEvent(router, 'route-not-found');
		await nextFrame();
		assert.shadowDom.equal(router, '');
	});

	test('renders home, then view-1', async () => {
		navigate('/');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`);
		await oneEvent(router, 'route-loaded');
		await nextFrame();
		assert.shadowDom.equal(router, '<demo-home></demo-home>');

		navigate('#!/view-1');
		await oneEvent(router, 'route-loaded');
		await nextFrame();
		assert.shadowDom.equal(router, '<view-1></view-1>');
	});

	test('error', async () => {
		navigate('#!/error');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`),
			{ detail } = await oneEvent(router, 'route-error');
		assert.equal(detail.error.message, 'testing');
	});

	test('params', async () => {
		navigate('#!/param-reading-view?p1=1&p2=2');
		const router = fixtureSync(html`<cosmoz-router .routes=${routes} />`);
		await oneEvent(router, 'route-loaded');
		await nextFrame();
		assert.shadowDom.equal(
			router.shadowRoot?.querySelector('param-reading-view'),
			'p1: 1; p2: 2'
		);
	});
});

suite('use-routes', () => {
	test('createElement', () => {
		assert.throws(() => createElement('definetly-undefined'));
	});

	test('navigate', () => {
		const historyMock = mock(history),
			replaceState = historyMock.expects('replaceState'),
			pushState = historyMock.expects('pushState');

		navigate('/asd');
		assert(replaceState.withArgs(null, '', '/asd'));

		navigate('/das', null, {
			replace: false,
			notify: false,
		});
		assert(pushState.withArgs(null, '', '/das'));

		historyMock.restore();
	});
});


text:
import json
import requests
import argparse
import os

SERVER_URL = 'https://patchwork.kernel.org/api/1.1'

USERNAME = 'kvalo'
PROJECT = 'linux-wireless'

# set patchwork token in PATCHWORK_TOKEN enviroment variable, but most
# of the commands will work without the token anyway

def get_auth_headers():
    headers = {}

    # if only set the token
    if 'PATCHWORK_TOKEN' in os.environ:
        headers['Authorization'] = 'Token %s' % (os.environ['PATCHWORK_TOKEN'])

    return headers

# state names listed in patchwork/fixtures/default_states.xml

def rest_get(args, url, params=None):
    if not url.startswith(SERVER_URL):
        url = '%s%s' % (SERVER_URL, url)

    r = requests.get(url, headers=get_auth_headers(), params=params)

    if args.dump:
        print('----------------------------------------------------------------------')
        print('%s:' % url)
        print(json.dumps(r.json(), indent=2))
        print('----------------------------------------------------------------------')

    r.raise_for_status()

    return r

def rest_patch(args, url, json):
    if not url.startswith(SERVER_URL):
        url = '%s%s' % (SERVER_URL, url)

    headers = get_auth_headers()
    headers['Content-Type'] = 'application/json'
    r = requests.patch(url, json=json, headers=headers)

    if args.dump:
        print('----------------------------------------------------------------------')
        print('%s:' % url)
        print(json.dumps(r.json(), indent=2))
        print('----------------------------------------------------------------------')

    r.raise_for_status()

    return r

def cmd_root(args):
    rest_get(args, '/')

def cmd_patch1(args):
    # Formatting: remove leading space
    r = rest_get(args, '/patches/11484825/')
    j = r.json()
    print(type(j['submitter']['name']))

    # Weird, this print causes an exception with --dump:
    #
    # $ ./rest-test-1.py --dump patch1 1>/dev/null
    # Traceback (most recent call last):
    #   File "./rest-test-1.py", line 111, in <module>
    #     main()
    #   File "./rest-test-1.py", line 108, in main
    #     args.func(args)
    #   File "./rest-test-1.py", line 45, in cmd_patch1
    #     print(j['submitter']['name'])
    # UnicodeEncodeError: 'ascii' codec can't encode character u'\xc9' in position 9: ordinal not in range(128)
    #
    # Also like this:
    #
    # $ ./rest-test-1.py patch1 1>/dev/null
    # Traceback (most recent call last):
    #   File "./rest-test-1.py", line 119, in <module>
    #     main()
    #   File "./rest-test-1.py", line 116, in main
    #     args.func(args)
    #   File "./rest-test-1.py", line 53, in cmd_patch1
    #     print(j['submitter']['name'])
    # UnicodeEncodeError: 'ascii' codec can't encode character u'\xc9' in position 9: ordinal not in range(128)
    print(j['submitter']['name'])

    rest_get(args, '/patches/11484825/comments/')

def cmd_patch2(args):
    # rtw88: add support for 802.11n RTL8723DE devices
    r = rest_get(args, '/patches/11494413/')
    j = r.json()
    print(j['submitter']['name'], type(j['submitter']['name']))

    rest_get(args, '/series/272629/')
    rest_get(args, '/covers/11494407/')
    rest_get(args, '/covers/11494407/comments/')

def cmd_auth1(args):
    pass

def cmd_users1(args):
    rest_get(args, '/users/?q=kvalo')

def cmd_patches1(args):
    r = rest_get(args, '/patches/', { 'project' : PROJECT,
                                      'delegate' : USERNAME,
                                      'state' : [ 'new', 'under-review' ] })
    j = r.json()
    print('%s patches' % (len(j)))

    for patch in j:
        print(patch['submitter']['name'], patch['name'], patch['state'],
              patch['date'])

def cmd_patches2(args):
    r = rest_get(args, '/patches/', { 'project' : PROJECT,
                                      'delegate' : USERNAME,
                                      'state' : 'deferred' })
    while True:
        j = r.json()
        print('%s patches' % (len(j)))

        if 'next' not in r.links:
            # no more pages
            break

        r = rest_get(args, r.links['next']['url'])

def cmd_events1(args):
    r = rest_get(args, '/events/', { 'patch': '11484825' } )
    j = r.json()

    for event in j:
        print(event['category'], event['date'])

def cmd_set_state1(args):
    # [v2] ath10k: add retry mechanism for ath10k_start
    r = rest_patch(args, '/patches/11340881/', { 'state': 'new' })
    j = r.json()
    print(j['name'], j['state'], j['delegate']['username'])

def cmd_set_delegate1(args):
    # kvalo's id is 25621
    r = rest_patch(args, '/patches/11340881/', { 'delegate': 25621 })
    j = r.json()
    print(j['name'], j['state'], j['delegate']['username'])

def cmd_mbox1(args):
    # rtw88: add support for 802.11n RTL8723DE devices
    r = rest_get(args, '/patches/11494413/')
    j = r.json()
    print(j['mbox'])

    r = requests.get(j['mbox'], headers=get_auth_headers())
    print(r.text)

def cmd_tags1(args):
    # [v2,06/18] mt76: add mac80211 driver for MT7915 PCIe-based chipsets
    r = rest_get(args, '/patches/11489259/')
    j = r.json()
    print('%s: tags %r' % (j['name'], j['tags']))
    print(j['content'])

def cmd_series1(args):
    r = rest_get(args, '/series/', { 'project' : PROJECT })
    j = r.json()
    print('%s series' % (len(j)))

    for series in j:
        print(series['submitter']['name'], series['name'], series['date'],
              '%d patches' % len(series['patches']))

def cmd_series2(args):
    # [PATCHv2,1/4] ath10k: Add wmi command support for station specific TID config
    r = rest_get(args, '/patches/11643791/')
    patch = r.json()

    # note: for some reason series is an array, just use the first one
    # and ignore the rest
    print(patch['series'][0]['id'], patch['series'][0]['name'])

    # fetch the full series
    r = rest_get(args, '/series/%d/' % (patch['series'][0]['id']))
    series = r.json()

    print(series['cover_letter']['id'], series['cover_letter']['web_url'])

def cmd_utf1(args):
    # carl9170: remove P2P_GO support
    r = rest_get(args, '/patches/11509803/')
    j = r.json()
    print(j['mbox'])

    r = requests.get(j['mbox'], headers=get_auth_headers())
    print(r.encoding)
    r.encoding = 'utf-8'
    text = r.text
    print(type(text))

    s = []
    for l in text.splitlines():
        s.append(ascii(l))
        if l.startswith('Reported-by:'):
            print(type(l))
            print(l)
            print(ascii(l))

    #print('\n'.join(s))

def cmd_pull1(args):
    r = rest_get(args, '/patches/11507893/')
    j = r.json()
    print(repr(j['pull_url']))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dump', action='store_true')

    subparsers = parser.add_subparsers()
    subparsers.add_parser('root').set_defaults(func=cmd_root)
    subparsers.add_parser('patch1').set_defaults(func=cmd_patch1)
    subparsers.add_parser('patch2').set_defaults(func=cmd_patch2)
    subparsers.add_parser('auth1').set_defaults(func=cmd_auth1)
    subparsers.add_parser('users1').set_defaults(func=cmd_users1)
    subparsers.add_parser('patches1').set_defaults(func=cmd_patches1)
    subparsers.add_parser('patches2').set_defaults(func=cmd_patches2)
    subparsers.add_parser('events1').set_defaults(func=cmd_events1)
    subparsers.add_parser('set-state1').set_defaults(func=cmd_set_state1)
    subparsers.add_parser('set-delegate1').set_defaults(func=cmd_set_delegate1)
    subparsers.add_parser('mbox1').set_defaults(func=cmd_mbox1)
    subparsers.add_parser('tags1').set_defaults(func=cmd_tags1)
    subparsers.add_parser('series1').set_defaults(func=cmd_series1)
    subparsers.add_parser('series2').set_defaults(func=cmd_series2)
    subparsers.add_parser('utf1').set_defaults(func=cmd_utf1)
    subparsers.add_parser('pull1').set_defaults(func=cmd_pull1)

    args = parser.parse_args()
    args.func(args)

if __name__ == "__main__":
    main()


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef DEBUG
static const char CVS_ID[] = "@(#) $RCSfile: instance.c,v $ $Revision: 1.5 $ $Date: 2012/04/25 14:49:30 $";
#endif /* DEBUG */

#include "ckdbm.h"

static CK_RV
nss_dbm_mdInstance_Initialize
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance,
  NSSUTF8 *configurationData
)
{
  CK_RV rv = CKR_OK;
  NSSArena *arena;
  nss_dbm_instance_t *instance;

  arena = NSSCKFWInstance_GetArena(fwInstance, &rv);
  if( ((NSSArena *)NULL == arena) && (CKR_OK != rv) ) {
    return rv;
  }

  instance = nss_ZNEW(arena, nss_dbm_instance_t);
  if( (nss_dbm_instance_t *)NULL == instance ) {
    return CKR_HOST_MEMORY;
  }

  instance->arena = arena;

  /*
   * This should parse the configuration data for information on
   * number and locations of databases, modes (e.g. readonly), etc.
   * But for now, we'll have one slot with a creatable read-write
   * database called "cert8.db."
   */

  instance->nSlots = 1;
  instance->filenames = nss_ZNEWARRAY(arena, char *, instance->nSlots);
  if( (char **)NULL == instance->filenames ) {
    return CKR_HOST_MEMORY;
  }

  instance->flags = nss_ZNEWARRAY(arena, int, instance->nSlots);
  if( (int *)NULL == instance->flags ) {
    return CKR_HOST_MEMORY;
  }

  instance->filenames[0] = "cert8.db";
  instance->flags[0] = O_RDWR|O_CREAT;

  mdInstance->etc = (void *)instance;
  return CKR_OK;
}

/* nss_dbm_mdInstance_Finalize is not required */

static CK_ULONG
nss_dbm_mdInstance_GetNSlots
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance,
  CK_RV *pError
)
{
  nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
  return instance->nSlots;
}

static CK_VERSION
nss_dbm_mdInstance_GetCryptokiVersion
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance
)
{
  static CK_VERSION rv = { 2, 1 };
  return rv;
}

static NSSUTF8 *
nss_dbm_mdInstance_GetManufacturerID
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance,
  CK_RV *pError
)
{
  return "Mozilla Foundation";
}

static NSSUTF8 *
nss_dbm_mdInstance_GetLibraryDescription
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance,
  CK_RV *pError
)
{
  return "Berkeley Database Module";
}

static CK_VERSION
nss_dbm_mdInstance_GetLibraryVersion
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance
)
{
  static CK_VERSION rv = { 1, 0 }; /* My own version number */
  return rv;
}

static CK_BBOOL
nss_dbm_mdInstance_ModuleHandlesSessionObjects
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance
)
{
  return CK_TRUE;
}

static CK_RV
nss_dbm_mdInstance_GetSlots
(
  NSSCKMDInstance *mdInstance,
  NSSCKFWInstance *fwInstance,
  NSSCKMDSlot *slots[]
)
{
  nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
  CK_ULONG i;
  CK_RV rv = CKR_OK;

  for( i = 0; i < instance->nSlots; i++ ) {
    slots[i] = nss_dbm_mdSlot_factory(instance, instance->filenames[i],
                                      instance->flags[i], &rv);
    if( (NSSCKMDSlot *)NULL == slots[i] ) {
      return rv;
    }
  }

  return rv;
}

/* nss_dbm_mdInstance_WaitForSlotEvent is not relevant */

NSS_IMPLEMENT_DATA NSSCKMDInstance
nss_dbm_mdInstance = {
  NULL, /* etc; filled in later */
  nss_dbm_mdInstance_Initialize,
  NULL, /* nss_dbm_mdInstance_Finalize */
  nss_dbm_mdInstance_GetNSlots,
  nss_dbm_mdInstance_GetCryptokiVersion,
  nss_dbm_mdInstance_GetManufacturerID,
  nss_dbm_mdInstance_GetLibraryDescription,
  nss_dbm_mdInstance_GetLibraryVersion,
  nss_dbm_mdInstance_ModuleHandlesSessionObjects,
  nss_dbm_mdInstance_GetSlots,
  NULL, /* nss_dbm_mdInstance_WaitForSlotEvent */
  NULL /* terminator */
};


text:
(function(){

    "use strict";

    /** This controller brings together the touch control and XML3D.tools.FlyBehavior
     *  to provide fly mode navigation using touch.
     *
     *  @constructor
     */
    XML3D.tools.TouchFlyController = new XML3D.tools.Class(XML3D.tools.util.Attachable, {

        /**
         *  @this {XML3D.tools.TouchFlyController}
         *  @param {Element|Transformable} targetViewGroup
         *  @param {Object} options
         *
         *  options:
         *  o behavior: options to be passed to XML3D.tools.FlyBehavior
         *  o touch: options to be passed to XML3D.tools.TouchController
         *
         *  By default, the view can be rotated using the movement of a single finger,
         *  and movement can be done using zoom/pinch gestures.
         */
        initialize: function(targetViewGroup, options) {

            this.callSuper();

            var options = options || {};
            options.behavior = options.behavior || {};
            options.touch = options.touch || {};

            this.target = XML3D.tools.util.getOrCreateTransformable(targetViewGroup);

            this._behavior = new XML3D.tools.FlyBehavior(this.target, options.behavior);

            this._touchCtrl = new XML3D.tools.TouchController(this.target, options.touch);
            this._touchCtrl.onDrag = this.callback("_onDrag");
        },

        lookAt: function(point) {
            this._behavior.lookAt(point);
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        setPosition: function(position) {
            this._behavior.setPosition(position);
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        setOrientation: function(orientation) {
            this._behavior.setOrientation(orientation);
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        getPosition: function() {
            return this._behavior.getPosition();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        getOrientation: function() {
            return this._behavior.getOrientation();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        getMoveSpeed: function() {
            return this._behavior.getMoveSpeed();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        setMoveSpeed: function(speed) {
            this._behavior.setMoveSpeed(speed);
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        getRotationSpeed: function() {
            return this._behavior.getRotationSpeed();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         */
        setRotationSpeed: function(speed) {
            this._behavior.setRotationSpeed(speed);
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         *  @protected
         *  @override
         */
        onAttach: function() {
            this._touchCtrl.attach();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         *  @protected
         *  @override
         */
        onDetach: function() {
            this._touchCtrl.detach();
        },

        /**
         *  @this {XML3D.tools.TouchFlyController}
         *  @private
         */
        _onDrag: function(action) {
            if (action.evt.touches.length > 1) {
                if (action.zoom > 1.0) { this._behavior.moveForward(); }
                if (action.zoom < 1.0) { this._behavior.moveBackward(); }
            } else {
                //invert delta to represent touch-"dragging" of a point
                this._behavior.rotate(-action.deltas[0].y, -action.deltas[0].x);
            }
        }
    });
}());


text:
describe('OneOrMore', function () {

	it('should produce a token with a child for each time its subexpression matches', function () {
		var ctx = new Iambic.ParseContext('appapple'),
			expr = new Iambic.OneOrMore(new Iambic.LiteralPattern('app'));

		ctx.beginParse();

		expect(expr.evaluate(ctx)).toEqual(new Iambic.Token().adoptChild('app').adoptChild('app'));
	});

	it('should produce an error token when its subexpression doesn\'t match', function () {
		var ctx = new Iambic.ParseContext('snapple'),
			expr = new Iambic.OneOrMore(new Iambic.LiteralPattern('app'));

		ctx.beginParse();

		expect(expr.evaluate(ctx).error).toBeTruthy();
		expect(ctx.offset).toEqual(0);
	});

	it('should produce a non-empty token when its subexpression makes a zero length match', function () {
		var ctx = new Iambic.ParseContext('apple'),
			expr = new Iambic.OneOrMore(new Iambic.LiteralPattern(''));

		ctx.beginParse();

		expect(expr.evaluate(ctx)).toEqual(new Iambic.Token().adoptChild(''));
	});

	it('should compile to itself', function () {
		var expr = new Iambic.OneOrMore(new Iambic.LiteralPattern('a'));
		expect(expr.compile()).toBe(expr);
	});

	it('should compile its subexpression when compiled', function () {
		var replacement = {},
			child = { 'compile': function () { return replacement; } },
			expr = new Iambic.OneOrMore(child),
			parser = {};

		spyOn(child, 'compile').andCallThrough();

		expr.compile(parser);

		expect(child.compile).toHaveBeenCalledWith(parser);
		expect(expr.expression).toBe(replacement);
	});

	it('should serialise to a standard grammar form', function () {
		var expr = new Iambic.OneOrMore(new Iambic.LiteralPattern('apple'));
		expect(expr.toString()).toEqual("'apple'+");
	});

	it('should delegate to its subexpression when checking for well-formedness', function () {
		var child = { 'checkWellFormed': function (b,p) { return 'childReturnValue'; } },
			expr = new Iambic.OneOrMore(child);

		spyOn(child, 'checkWellFormed').andCallThrough();

		expect(expr.checkWellFormed('baseProductionName', 'productionNames')).toEqual('childReturnValue');
		expect(child.checkWellFormed).toHaveBeenCalledWith('baseProductionName', 'productionNames');
	});
});


text:
package org.microbule.core;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.microbule.config.api.Config;
import org.microbule.scheduler.api.RefreshableReference;
import org.microbule.scheduler.api.SchedulerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class JaxrsProxyCache<T> implements RemovalListener<String, RefreshableReference<CachedJaxrsProxy<T>>>, AutoCloseable {
//----------------------------------------------------------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------------------------------------------------------

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
    private static final String TIMEOUT_PROP = "timeout";
    private static final String TIMEOUT_UNIT_PROP = "timeoutUnit";
    private static final String REFRESH_DELAY_PROP = "refreshDelay";
    private static final String REFRESH_DELAY_UNIT_PROP = "refreshDelayUnit";
    private static final long DEFAULT_TIMEOUT = 5;
    private static final TimeUnit DEFAULT_UNIT = TimeUnit.MINUTES;
    private static final long DEFAULT_REFRESH_DELAY = 1;
    private static final Logger LOGGER = LoggerFactory.getLogger(JaxrsProxyCache.class);
    private final LoadingCache<String, RefreshableReference<CachedJaxrsProxy<T>>> cache;
    private final String serviceName;

//----------------------------------------------------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------------------------------------------------

    JaxrsProxyCache(Function<String, CachedJaxrsProxy<T>> factory, SchedulerService schedulerService, String serviceName, Config cacheConfig) {
        this.serviceName = serviceName;
        final long timeout = cacheConfig.longValue(TIMEOUT_PROP).orElse(DEFAULT_TIMEOUT);
        final TimeUnit timeoutUnit = cacheConfig.enumValue(TIMEOUT_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT);
        final long refreshDelay = cacheConfig.longValue(REFRESH_DELAY_PROP).orElse(DEFAULT_REFRESH_DELAY);
        final TimeUnit refreshDelayUnit = cacheConfig.enumValue(REFRESH_DELAY_UNIT_PROP, TimeUnit.class).orElse(DEFAULT_UNIT);
        this.cache = CacheBuilder.newBuilder()
                .removalListener(this)
                .expireAfterAccess(timeout, timeoutUnit)
                .build(new CacheLoader<String, RefreshableReference<CachedJaxrsProxy<T>>>() {
                    @Override
                    public RefreshableReference<CachedJaxrsProxy<T>> load(String address) throws Exception {
                        return schedulerService.createRefreshableReference(currentValue -> {
                            final CachedJaxrsProxy<T> newValue = factory.apply(address);
                            if (currentValue == null) {
                                if (LOGGER.isInfoEnabled()) {
                                    LOGGER.info("Created dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig()));
                                }
                                return newValue;
                            } else if (currentValue.getConfig().equals(newValue.getConfig())) {
                                LOGGER.debug("Retained current dynamic proxy for \"{}\" service at address: {}", serviceName, address);
                                return currentValue;
                            } else {
                                if (LOGGER.isInfoEnabled()) {
                                    LOGGER.info("Refreshed dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig()));
                                }
                                return newValue;
                            }
                        }, refreshDelay, refreshDelayUnit);
                    }
                });
    }

//----------------------------------------------------------------------------------------------------------------------
// AutoCloseable Implementation
//----------------------------------------------------------------------------------------------------------------------

    @Override
    public void close() {
        cache.invalidateAll();
    }

//----------------------------------------------------------------------------------------------------------------------
// RemovalListener Implementation
//----------------------------------------------------------------------------------------------------------------------

    @Override
    public void onRemoval(RemovalNotification<String, RefreshableReference<CachedJaxrsProxy<T>>> notification) {
        LOGGER.debug("Canceling dynamic proxy refresh for \"{}\" service.", serviceName);
        notification.getValue().cancel();
    }

//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------

    T getTarget(String address) {
        return cache.getUnchecked(address).get().getProxy();
    }
}


text:
<resources>
    <string name="app_name">Chicago Speed Cams</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>


text:
const gulp = require('gulp');

function scriptRunner(src, outputFilename, config, plugins) {
    return function () {
        let promise = gulp.src(src)
            .pipe(plugins.plumber())
            .pipe(config.debug ? plugins.debug() : plugins.noop())
            .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
            .pipe(plugins.concat(config.jsPath + outputFilename))
            .pipe(config.production ? plugins.uglify() : plugins.noop());

        if (config.revManifest) {
            promise = promise.pipe(plugins.rev());
        }

        promise = promise
            .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
            .pipe(gulp.dest(config.publicPath));

        if (config.revManifest) {
            // Write the rev-manifest.json file for gulp-rev
            promise = promise.pipe(plugins.rev.manifest(config.revManifestPath, {
                merge: true
            }));
        }
        promise = promise.pipe(gulp.dest('.'));

        return promise;
    }
}

module.exports = scriptRunner;


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="graph_text_size">20dp</dimen>
    <dimen name="offset">40dp</dimen>
</resources>


text: Documentation is here.


text:
var gulp = require('gulp');
var paths = require('../paths');
var browserSync = require('browser-sync');

// outputs changes to files to the console
function reportChange(event){
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
}

// this task wil watch for changes
// to js, html, and css files and call the
// reportChange method. Also, by depending on the
// serve task, it will instantiate a browserSync session
gulp.task('watch', ['serve'], function() {
  var source = [paths.source , paths.demo.source];
  var html = [paths.html , paths.demo.html  ];

  gulp.watch(paths.stylus.all, ['demo:styles' , browserSync.reload]).on('change', reportChange);
  gulp.watch(source          , ['demo:system' , browserSync.reload]).on('change', reportChange);
  gulp.watch(html            , ['demo:html'   , browserSync.reload]).on('change', reportChange);
  gulp.watch(paths.style     , browserSync.reload).on('change', reportChange);
});


text:
import * as React from 'react';
import { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import Select, { AbstractSelectProps, SelectValue, OptionProps, OptGroupProps } from '../select';
import Input from '../input';
import InputElement from './InputElement';

export interface DataSourceItemObject { value: string; text: string; }
export type DataSourceItemType = string | DataSourceItemObject;

export interface InputProps {
  onChange?: React.FormEventHandler<any>;
  value: any;
}

export type ValidInputElement =
  HTMLInputElement |
  HTMLTextAreaElement |
  React.ReactElement<InputProps>;

export interface AutoCompleteProps extends AbstractSelectProps {
  value?: SelectValue;
  defaultValue?: SelectValue;
  dataSource: DataSourceItemType[];
  optionLabelProp?: string;
  onChange?: (value: SelectValue) => void;
  onSelect?: (value: SelectValue, option: Object) => any;
  children?: ValidInputElement |
    React.ReactElement<OptionProps> |
    Array<React.ReactElement<OptionProps>>;
}

function isSelectOptionOrSelectOptGroup(child: any): Boolean {
  return child && child.type && (child.type.isSelectOption || child.type.isSelectOptGroup);
}

export default class AutoComplete extends React.Component<AutoCompleteProps, {}> {
  static Option = Option as React.ClassicComponentClass<OptionProps>;
  static OptGroup = OptGroup as React.ClassicComponentClass<OptGroupProps>;

  static defaultProps = {
    prefixCls: 'ant-select',
    transitionName: 'slide-up',
    optionLabelProp: 'children',
    choiceTransitionName: 'zoom',
    showSearch: false,
    filterOption: false,
  };

  private select: any;

  getInputElement = () => {
    const { children } = this.props;
    const element = children && React.isValidElement(children) && children.type !== Option ?
      React.Children.only(this.props.children) : <Input />;
    const elementProps = { ...element.props };
    // https://github.com/ant-design/ant-design/pull/7742
    delete elementProps.children;
    return (
      <InputElement {...elementProps}>{element}</InputElement>
    );
  }

  focus() {
    this.select.focus();
  }

  blur() {
    this.select.blur();
  }

  saveSelect = (node: any) => {
    this.select = node;
  }

  render() {
    let {
      size, className = '', notFoundContent, prefixCls, optionLabelProp, dataSource, children,
    } = this.props;

    const cls = classNames({
      [`${prefixCls}-lg`]: size === 'large',
      [`${prefixCls}-sm`]: size === 'small',
      [className]: !!className,
      [`${prefixCls}-show-search`]: true,
      [`${prefixCls}-auto-complete`]: true,
    });

    let options;
    const childArray = React.Children.toArray(children);
    if (childArray.length &&
        isSelectOptionOrSelectOptGroup(childArray[0])
      ) {
      options = children;
    } else {
      options = dataSource ? dataSource.map((item) => {
        if (React.isValidElement(item)) {
          return item;
        }
        switch (typeof item) {
          case 'string':
            return <Option key={item}>{item}</Option>;
          case 'object':
            return (
              <Option key={(item as DataSourceItemObject).value}>
                {(item as DataSourceItemObject).text}
              </Option>
            );
          default:
            throw new Error('AutoComplete[dataSource] only supports type `string[] | Object[]`.');
        }
      }) : [];
    }

    return (
      <Select
        {...this.props}
        className={cls}
        mode="combobox"
        optionLabelProp={optionLabelProp}
        getInputElement={this.getInputElement}
        notFoundContent={notFoundContent}
        ref={this.saveSelect}
      >
        {options}
      </Select>
    );
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.hamcrest.core (JUnit API)
</TITLE>

<META NAME="keywords" CONTENT="org.hamcrest.core package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

org.hamcrest.core

Classes

AllOf

AnyOf

DescribedAs

Is

IsAnything

IsEqual

IsInstanceOf

IsNot

IsNull

IsSame


text:
<?php $presenter = new KT_WP_FW_Components_Page_Presenter($post); ?>

<?php echo $presenter->getModel()->getTitle(); ?>

                <?php
                echo $presenter->getExcerpt();
                echo $presenter->getModel()->getContent();
                ?>

        <?php get_sidebar(); ?>


text:
@__experimental_modules_import Module.Sub;

void test_Module_Sub() {
  int *ip = Module_Sub;
}

@__experimental_modules_import Module.Buried.Treasure;

void dig() {
  unsigned *up = Buried_Treasure;
}


text:
#pragma once

#include "MainPage.g.h"
#include "RgbViewModel.h"
#include "DoubleToStringHexByteConverter.h"

namespace ColorScrollWithDataContext
{
    public ref class MainPage sealed
    {
    public:
        MainPage();
    };
}


text:
require 'configliere'

require_relative '../lib/weavr'

# config

Settings.use :commandline

Settings.define :ambari_cluster_name, default: 'hwx'
Settings.define :ambari_host, default: 'hdp-nn'
Settings.define :ambari_port, default: 8080, type: Integer
Settings.define :ambari_username, default: 'admin'
Settings.define :ambari_password, default: 'admin'
Settings.define :ambari_wait_sec, default: 5.0

Settings.resolve!

Weavr.configure(
  host: Settings.ambari_host,
  port: Settings.ambari_port,
  username: Settings.ambari_username,
  password: Settings.ambari_password,
)

# weavr cluster

w = Weavr.cluster(Settings.ambari_cluster_name)

# go!

Weavr::CLI.new(w).repl


text:
require 'rails_helper'

RSpec.describe 'New artist', type: :system do
  before { test_sign_in }

  it 'Open form from songs index' do
    visit artists_path
    click_on '歌手追加'

    expect(current_path).to eq new_artist_path
  end

  context 'valid artist' do
    it 'register a artist' do
      visit new_artist_path
      fill_in '歌手名', with: 'The Artist'
      click_on '追加'

      artist = Artist.order(created_at: :desc).take
      expect(current_path).to eq artist_path(artist)
      expect(page).to have_content 'The Artist'
    end
  end

  context 'invalid artist' do
    it 'show error messages' do
      visit new_artist_path
      click_on '追加'

      expect(page).to have_content '歌手名 を入力してください'
    end
  end
end


text:
module PagSeguro
  class Sender
    include Extensions::MassAssignment
    include Extensions::EnsureType

    # Get the sender phone.
    attr_reader :phone

    # Get the sender document
    attr_reader :document

    # Get the sender address
    attr_reader :address

    # Set the sender name.
    attr_accessor :name

    # Set the sender e-mail.
    attr_accessor :email

    # Set the sender ip
    attr_accessor :ip

    # Set sender hash.
    # It's used to identify the sender.
    attr_accessor :hash

    # Set the sender phone.
    def phone=(phone)
      @phone = ensure_type(Phone, phone)
    end

    def documents
      @documents ||= Documents.new
    end

    def documents=(_documents=[])
      _documents.each do |document|
        documents << document
      end
    end

    # Set the sender document.
    def document=(document)
      documents << ensure_type(Document, document)
    end

    # Set the sender address.
    def address=(address)
      @address = ensure_type(Address, address)
    end
  end
end


text:
module Kernel
  def __DIR_REL__(called_from = nil)
    called_from ||= caller.first
    caller_path = called_from[/(.*?(?=:\d+(:|$)))/, 1]
    caller_path = '.' if caller_path == ''
    File.expand_path(File.dirname(caller_path))
  end

  unless method_defined?(:__DIR__)
    alias_method :__DIR__, :__DIR_REL__
  end

  unless method_defined?(:require_relative)
    def require_relative(path)
      require File.join(__DIR_REL__(caller.first), path)
    end
  end
end

class Module
  unless method_defined?(:autoload_relative)
    def autoload_relative(name, filename)
      autoload name, File.join(__DIR_REL__(caller.first), filename)
    end
  end
end

class String
  unless method_defined?(:~@)
    def ~@
      File.expand_path(File.join(__DIR_REL__(caller.first), self))
    end
  end
end


text:
package com.dremio.exec.expr.fn.impl.conv;

import javax.inject.Inject;

import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.vector.holders.DateMilliHolder;
import org.apache.arrow.vector.holders.VarBinaryHolder;

import com.dremio.exec.expr.SimpleFunction;
import com.dremio.exec.expr.annotations.FunctionTemplate;
import com.dremio.exec.expr.annotations.FunctionTemplate.FunctionScope;
import com.dremio.exec.expr.annotations.FunctionTemplate.NullHandling;
import com.dremio.exec.expr.annotations.Output;
import com.dremio.exec.expr.annotations.Param;

@FunctionTemplate(name = "convert_toDATE_EPOCH_BE", scope = FunctionScope.SIMPLE, nulls = NullHandling.NULL_IF_NULL)
@SuppressWarnings("unused") // found through classpath search
public class DateEpochBEConvertTo implements SimpleFunction {

  @Param DateMilliHolder in;
  @Output VarBinaryHolder out;
  @Inject ArrowBuf buffer;

  @Override
  public void setup() {
    buffer = buffer.reallocIfNeeded(8);
  }

  @Override
  public void eval() {
    buffer.clear();
    buffer.writeLong(Long.reverseBytes(in.value));
    out.buffer = buffer;
    out.start = 0;
    out.end = 8;
  }
}


text:
<?php

namespace spec\Cmp\Monitoring;

use Cmp\Monitoring\Monitor;
use Cmp\Monitoring\MonitorFactory;
use PhpSpec\ObjectBehavior;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

class MonitorFactorySpec extends ObjectBehavior
{
    function it_can_be_initialized()
    {
        $this->shouldHaveType(MonitorFactory::class);
    }

    function it_can_built_an_empty_monitor()
    {
        $monitor = $this->create();
        $monitor->shouldBeAnInstanceOf(Monitor::class);
    }

    function it_can_built_an_working_monitor(LoggerInterface $logger)
    {
        $monitor = $this->create([
            'hostname'     => 'fooserver',
            'default_tags' => ['foo' => 'bar'],
            'prefix'       => 'my-app.',
            'logger'       => [
                'instance' => $logger,
                'debug'    => true,
                'level'    => LogLevel::WARNING,
                'metrics'  => true,
                'events'   => true,
            ],
            'datadog'      => [
                'metrics'  => true,
                'events'   => true,
                'host'     => '10.0.0.1',
                'port'     => 8822,
            ],
        ]);

        $monitor->shouldBeAnInstanceOf(Monitor::class);
    }

    function it_can_built_an_working_monitor_from_half_config(LoggerInterface $logger)
    {
        $monitor = $this->create([
            'hostname'     => 'fooserver',
            'default_tags' => ['foo' => 'bar'],
            'prefix'       => 'my-app.',
            'logger'       => [
                'instance' => $logger,
                'debug'    => true,
                'metrics'  => true,
                'events'   => true,
            ],
            'datadog'      => [
                'metrics'  => true,
                'events'   => true,
                'host'     => '10.0.0.1'
            ],
        ]);

        $monitor->shouldBeAnInstanceOf(Monitor::class);
    }
}


text:
r'''
from __future__ import absolute_import, division, print_function
import sys
import traceback
from utool.Preferences import Pref
# Qt
from guitool.__PyQt__ import QtCore, QtGui
from guitool.__PyQt__.Qt import (QAbstractItemModel, QModelIndex, QVariant, QWidget,
                      QString, Qt, QObject, pyqtSlot)

# Decorator to help catch errors that QT wont report
def report_thread_error(fn):
    def report_thread_error_wrapper(*args, **kwargs):
        try:
            ret = fn(*args, **kwargs)
            return ret
        except Exception as ex:
            print('\n\n *!!* Thread Raised Exception: ' + str(ex))
            print('\n\n *!!* Thread Exception Traceback: \n\n' + traceback.format_exc())
            sys.stdout.flush()
            et, ei, tb = sys.exc_info()
            raise
    return report_thread_error_wrapper

# ---
# Functions
# ---
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s
try:
    _encoding = QtWidgets.QApplication.UnicodeUTF8

    def _translate(context, text, disambig):
        return QtWidgets.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtWidgets.QApplication.translate(context, text, disambig)

# ---
# THE ABSTRACT ITEM MODEL
# ---
#QComboBox
class QPreferenceModel(QAbstractItemModel):
    """ Convention states only items with column index 0 can have children """
    @report_thread_error
    def __init__(self, pref_struct, parent=None):
        super(QPreferenceModel, self).__init__(parent)
        self.rootPref  = pref_struct

    @report_thread_error
    def index2Pref(self, index=QModelIndex()):
        """ Internal helper method """
        if index.isValid():
            item = index.internalPointer()
            if item:
                return item
        return self.rootPref

    #-----------
    # Overloaded ItemModel Read Functions
    @report_thread_error
    def rowCount(self, parent=QModelIndex()):
        parentPref = self.index2Pref(parent)
        return parentPref.qt_row_count()

    @report_thread_error
    def columnCount(self, parent=QModelIndex()):
        parentPref = self.index2Pref(parent)
        return parentPref.qt_col_count()

    @report_thread_error
    def data(self, index, role=Qt.DisplayRole):
        """ Returns the data stored under the given role
        for the item referred to by the index. """
        if not index.isValid():
            return QVariant()
        if role != Qt.DisplayRole and role != Qt.EditRole:
            return QVariant()
        nodePref = self.index2Pref(index)
        data = nodePref.qt_get_data(index.column())
        var = QVariant(data)
        #print('--- data() ---')
        #print('role = %r' % role)
        #print('data = %r' % data)
        #print('type(data) = %r' % type(data))
        if isinstance(data, float):
            var = QVariant(QString.number(data, format='g', precision=6))
        if isinstance(data, bool):
            var = QVariant(data).toString()
        if isinstance(data, int):
            var = QVariant(data).toString()
        #print('var= %r' % var)
        #print('type(var)= %r' % type(var))
        return var

    @report_thread_error
    def index(self, row, col, parent=QModelIndex()):
        """Returns the index of the item in the model specified
        by the given row, column and parent index."""
        if parent.isValid() and parent.column() != 0:
            return QModelIndex()
        parentPref = self.index2Pref(parent)
        childPref  = parentPref.qt_get_child(row)
        if childPref:
            return self.createIndex(row, col, childPref)
        else:
            return QModelIndex()

    @report_thread_error
    def parent(self, index=None):
        """Returns the parent of the model item with the given index.
        If the item has no parent, an invalid QModelIndex is returned."""
        if index is None:  # Overload with QObject.parent()
            return QObject.parent(self)
        if not index.isValid():
            return QModelIndex()
        nodePref = self.index2Pref(index)
        parentPref = nodePref.qt_get_parent()
        if parentPref == self.rootPref:
            return QModelIndex()
        return self.createIndex(parentPref.qt_parents_index_of_me(), 0, parentPref)

    #-----------
    # Overloaded ItemModel Write Functions
    @report_thread_error
    def flags(self, index):
        """Returns the item flags for the given index."""
        if index.column() == 0:
            # The First Column is just a label and unchangable
            return Qt.ItemIsEnabled | Qt.ItemIsSelectable
        if not index.isValid():
            return Qt.ItemFlag(0)
        childPref = self.index2Pref(index)
        if childPref:
            if childPref.qt_is_editable():
                return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
        return Qt.ItemFlag(0)

    @report_thread_error
    def setData(self, index, data, role=Qt.EditRole):
        """Sets the role data for the item at index to value."""
        if role != Qt.EditRole:
            return False
        #print('--- setData() ---')
        #print('role = %r' % role)
        #print('data = %r' % data)
        #print('type(data) = %r' % type(data))
        leafPref = self.index2Pref(index)
        result = leafPref.qt_set_leaf_data(data)
        if result is True:
            self.dataChanged.emit(index, index)
        return result

    @report_thread_error
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            if section == 0:
                return QVariant('Config Key')
            if section == 1:
                return QVariant('Config Value')
        return QVariant()

# ---
# THE PREFERENCE SKELETON
# ---
class Ui_editPrefSkel(object):
    def setupUi(self, editPrefSkel):
        editPrefSkel.setObjectName(_fromUtf8('editPrefSkel'))
        editPrefSkel.resize(668, 530)
        # Add Pane for TreeView
        self.verticalLayout = QtWidgets.QVBoxLayout(editPrefSkel)
        self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))
        # The TreeView for QAbstractItemModel to attach to
        self.prefTreeView = QtWidgets.QTreeView(editPrefSkel)
        self.prefTreeView.setObjectName(_fromUtf8('prefTreeView'))
        self.verticalLayout.addWidget(self.prefTreeView)
        # Add Pane for buttons
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))
        #
        #self.redrawBUT = QtWidgets.QPushButton(editPrefSkel)
        #self.redrawBUT.setObjectName(_fromUtf8('redrawBUT'))
        #self.horizontalLayout.addWidget(self.redrawBUT)
        ##
        #self.unloadFeaturesAndModelsBUT = QtWidgets.QPushButton(editPrefSkel)
        #self.unloadFeaturesAndModelsBUT.setObjectName(_fromUtf8('unloadFeaturesAndModelsBUT'))
        #self.horizontalLayout.addWidget(self.unloadFeaturesAndModelsBUT)
        #
        self.defaultPrefsBUT = QtWidgets.QPushButton(editPrefSkel)
        self.defaultPrefsBUT.setObjectName(_fromUtf8('defaultPrefsBUT'))
        self.horizontalLayout.addWidget(self.defaultPrefsBUT)
        # Buttons are a child of the View
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.retranslateUi(editPrefSkel)
        QtCore.QMetaObject.connectSlotsByName(editPrefSkel)

    def retranslateUi(self, editPrefSkel):
        # UTF-8 Support
        editPrefSkel.setWindowTitle(_translate('editPrefSkel', 'Edit Preferences', None))
        #self.redrawBUT.setText(_translate('editPrefSkel', 'Redraw', None))
        #self.unloadFeaturesAndModelsBUT.setText(_translate('editPrefSkel', 'Unload Features and Models', None))
        self.defaultPrefsBUT.setText(_translate('editPrefSkel', 'Defaults', None))

# ---
# THE PREFERENCE WIDGET
# ---
class EditPrefWidget(QWidget):
    """The Settings Pane; Subclass of Main Windows."""
    def __init__(self, pref_struct):
        super(EditPrefWidget, self).__init__()
        self.ui = Ui_editPrefSkel()
        self.ui.setupUi(self)
        self.pref_model = None
        self.populatePrefTreeSlot(pref_struct)
        #self.ui.redrawBUT.clicked.connect(fac.redraw)
        #self.ui.defaultPrefsBUT.clicked.connect(fac.default_prefs)
        #self.ui.unloadFeaturesAndModelsBUT.clicked.connect(fac.unload_features_and_models)

    @pyqtSlot(Pref, name='populatePrefTreeSlot')
    def populatePrefTreeSlot(self, pref_struct):
        """Populates the Preference Tree Model"""
        #printDBG('Bulding Preference Model of: ' + repr(pref_struct))
        #Creates a QStandardItemModel that you can connect to a QTreeView
        self.pref_model = QPreferenceModel(pref_struct)
        #printDBG('Built: ' + repr(self.pref_model))
        self.ui.prefTreeView.setModel(self.pref_model)
        self.ui.prefTreeView.header().resizeSection(0, 250)

    def refresh_layout(self):
        self.pref_model.layoutAboutToBeChanged.emit()
        self.pref_model.layoutChanged.emit()
'''


text:
package annis.ql.parser;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static annis.test.TestHelper.springFiles;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import annis.test.SpringQueryExamples;
import annis.test.SpringSyntaxTreeExamples;
import annis.test.SyntaxTreeExample;
import annis.exceptions.AnnisException;
import annis.ql.node.Start;

// see http://junit.sourceforge.net/doc/ReleaseNotes4.4.html
// and http://popper.tigris.org/tutorial.html
@RunWith(Theories.class)
public class TestAnnisParserExamples {

	// where to find query and syntax tree examples
	private static final String EXAMPLES = "annis/ql/parser/TestAnnisParser-examples.xml";

	// access to AnnisParser
	static ApplicationContext ctx;

	// simple DddQueryParser instance
	private AnnisParser parser;

	// load Spring application context once
	@BeforeClass
	public static void loadApplicationContext() {
		final String[] ctxFiles =
			springFiles(TestAnnisParserExamples.class, "AnnisParser-context.xml");
		ctx = new ClassPathXmlApplicationContext(ctxFiles);
	}

	// setup a fresh parser
	@Before
	public void setup() {
		parser = (AnnisParser) ctx.getBean("annisParser");
	}

	///// Syntax-Tree tests

	@Theory
	public void testSyntaxTrees(
			@SpringSyntaxTreeExamples(exampleMap = "exampleSyntaxTrees", contextLocation=EXAMPLES)
			SyntaxTreeExample example) {
		Start syntaxTree = parser.parse(example.getQuery());
		assertThat(syntaxTree, is(not(nullValue())));
		String actual = parser.dumpTree(syntaxTree).trim();
                // replace the unix line ending from the SVN with the systems line ending
                // (the dump tree will use the system line ending and the examples were created under linux)
                String provided = example.getSyntaxTree().replaceAll("\n", System.getProperty("line.separator"));
		assertEquals("wrong syntax tree for: " + example.getQuery(),provided.trim(), actual.trim());
	}

	@Theory
	public void testGoodQueries(
			@SpringQueryExamples(exampleList = "good", contextLocation=EXAMPLES)
			String annisQuery) {
		assertThat(parser.parse(annisQuery), is(not(nullValue())));
	}

	@Theory
	public void testBadQueries(
			@SpringQueryExamples(exampleList = "bad", contextLocation=EXAMPLES)
			String annisQuery) {
		try {
			parser.parse(annisQuery);
			fail("bad query passed as good: " + annisQuery);
		} catch (AnnisException e) {
			// ok
		}
	}

}


text:
jQuery(document).ready(function($) {

    var $window = $(window),
        $body = $('body'),
        $navbar = $('#top-navbar'),
        $navbarContent = $('#top-navbar-content'),
        $navbarToggle = $('#top-navbar-toggle'),
        $titleImage = $('#be-title');

    $body.localScroll({
        filter:'.smoothScroll',
        duration: 300,
        hash: true,
        onBefore: function() {
            if ($navbarToggle.is(':visible')) {
                $navbarContent.collapse('hide');
            }
        }
    });

    $navbarContent.on('hide.bs.collapse', function () {
        $navbar.removeClass('expanded');
    });

    $navbarContent.on('show.bs.collapse', function () {
        $navbar.addClass('expanded');
    });

    var imageTop = $titleImage.offset().top;
    var imageCenter = imageTop + ($titleImage.outerHeight() / 2);
    var navbarHeight = $navbar.outerHeight()
    var transparencyOffset = imageCenter - navbarHeight;

    var updateNavbarTransparency = function() {
        if ($window.scrollTop() >= transparencyOffset) {
            $navbar.addClass('opaque');
        } else {
            $navbar.removeClass('opaque');
        }
    };
    updateNavbarTransparency();
    $window.scroll(updateNavbarTransparency);
});