text:
var bindEvents, buttonIsDown, coordsForTouchEvent, position;

coordsForTouchEvent = function(el, e) {
  var p, tx, ty;
  tx = e.changedTouches[0].clientX;
  ty = e.changedTouches[0].clientY;
  p = el.getBoundingClientRect();
  return [tx - p.left, ty - p.top];
};

position = function(el, e) {
  var p;
  p = el.getBoundingClientRect();
  return {
    left: e.clientX - p.left,
    top: e.clientY - p.top
  };
};

buttonIsDown = function(e) {
  if (e.buttons != null) {
    return e.buttons === 1;
  } else {
    return e.which > 0;
  }
};

module.exports = bindEvents = function(lc, canvas, panWithKeyboard) {
  var listener, mouseMoveListener, mouseUpListener, touchEndListener, touchMoveListener, unsubs;
  if (panWithKeyboard == null) {
    panWithKeyboard = false;
  }
  unsubs = [];
  mouseMoveListener = (function(_this) {
    return function(e) {
      var p;
      e.preventDefault();
      p = position(canvas, e);
      return lc.pointerMove(p.left, p.top);
    };
  })(this);
  mouseUpListener = (function(_this) {
    return function(e) {
      var p;
      e.preventDefault();
      canvas.onselectstart = function() {
        return true;
      };
      p = position(canvas, e);
      lc.pointerUp(p.left, p.top);
      document.removeEventListener('mousemove', mouseMoveListener);
      document.removeEventListener('mouseup', mouseUpListener);
      return canvas.addEventListener('mousemove', mouseMoveListener);
    };
  })(this);
  canvas.addEventListener('mousedown', (function(_this) {
    return function(e) {
      var down, p;
      if (e.target.tagName.toLowerCase() !== 'canvas') {
        return;
      }
      down = true;
      e.preventDefault();
      canvas.onselectstart = function() {
        return false;
      };
      p = position(canvas, e);
      lc.pointerDown(p.left, p.top);
      canvas.removeEventListener('mousemove', mouseMoveListener);
      document.addEventListener('mousemove', mouseMoveListener);
      return document.addEventListener('mouseup', mouseUpListener);
    };
  })(this));
  touchMoveListener = function(e) {
    e.preventDefault();
    return lc.pointerMove.apply(lc, coordsForTouchEvent(canvas, e));
  };
  touchEndListener = function(e) {
    e.preventDefault();
    lc.pointerUp.apply(lc, coordsForTouchEvent(canvas, e));
    document.removeEventListener('touchmove', touchMoveListener);
    document.removeEventListener('touchend', touchEndListener);
    return document.removeEventListener('touchcancel', touchEndListener);
  };
  canvas.addEventListener('touchstart', function(e) {
    if (e.target.tagName.toLowerCase() !== 'canvas') {
      return;
    }
    e.preventDefault();
    if (e.touches.length === 1) {
      lc.pointerDown.apply(lc, coordsForTouchEvent(canvas, e));
      document.addEventListener('touchmove', touchMoveListener);
      document.addEventListener('touchend', touchEndListener);
      return document.addEventListener('touchcancel', touchEndListener);
    } else {
      return lc.pointerMove.apply(lc, coordsForTouchEvent(canvas, e));
    }
  });
  if (panWithKeyboard) {
    console.warn("Keyboard panning is deprecated.");
    listener = function(e) {
      switch (e.keyCode) {
        case 37:
          lc.pan(-10, 0);
          break;
        case 38:
          lc.pan(0, -10);
          break;
        case 39:
          lc.pan(10, 0);
          break;
        case 40:
          lc.pan(0, 10);
      }
      return lc.repaintAllLayers();
    };
    document.addEventListener('keydown', listener);
    unsubs.push(function() {
      return document.removeEventListener(listener);
    });
  }
  return function() {
    var f, i, len, results;
    results = [];
    for (i = 0, len = unsubs.length; i < len; i++) {
      f = unsubs[i];
      results.push(f());
    }
    return results;
  };
};


text:
package ol;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;

import ol.event.ClickListener;
import ol.event.DoubleClickListener;
import ol.event.EventListener;
import ol.event.MapMoveListener;
import ol.event.MapZoomListener;
import ol.event.OLHandlerRegistration;
import ol.event.TileLoadEndListener;
import ol.event.TileLoadErrorListener;
import ol.event.TileLoadStartListener;
import ol.events.Event;
import ol.geom.Polygon;
import ol.geom.SimpleGeometryCoordinates;
import ol.gwt.CollectionWrapper;
import ol.layer.Base;
import ol.layer.Layer;
import ol.proj.Projection;
import ol.source.Source;
import ol.source.Tile;
import ol.source.UrlTile;
import ol.source.Xyz;
import ol.source.XyzOptions;
import ol.style.Style;
import ol.tilegrid.TileGrid;
import ol.tilegrid.TileGridOptions;

/**
 * Utility functions.
 *
 * @author sbaumhekel
 */
@ParametersAreNonnullByDefault
public final class OLUtil {

    /**
     * Radius equal to the semi-major axis of the normal ellipsoid (like
     * ol.sphere.NORMAL).
     */
    public static final double EARTH_RADIUS_NORMAL = 6370997;

    /**
     * Radius equal to the semi-major axis of the WGS84 ellipsoid (like
     * ol.sphere.WGS84).
     */
    public static final double EARTH_RADIUS_WGS84 = 6378137;

    // prevent instantiating this class
    @Deprecated
    private OLUtil() {
        throw new AssertionError();
    }

    /**
     * Adds a click listener for the given map.
     *
     * @param map
     *            {@link Map}
     * @param singleClicksOnly
     *            wait fortrue single click with no dragging and no double
     *            click? Note that this event is delayed by 250 ms to ensure
     *            that it is not a double click.
     * @param listener
     *            {@link ClickListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addClickListener(Map map, boolean singleClicksOnly,
            final ClickListener listener) {
        String type;
        if(singleClicksOnly) {
            type = "singleclick";
        } else {
            type = "click";
        }
        return observe(map, type, new EventListener<MapBrowserEvent>() {

            @Override
            public void onEvent(MapBrowserEvent event) {
                listener.onClick(event);
            }
        });
    }

    /**
     * Adds a click listener for the given map.
     *
     * @param map
     *            {@link Map}
     * @param listener
     *            {@link DoubleClickListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addDoubleClickListener(Map map, final DoubleClickListener listener) {
        return observe(map, "dblclick", new EventListener<MapBrowserEvent>() {

            @Override
            public void onEvent(MapBrowserEvent event) {
                listener.onDoubleClick(event);
            }
        });
    }

    /**
     * Adds a map move listener for the given map.
     *
     * @param map
     *            {@link Map}
     * @param listener
     *            {@link MapMoveListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addMapMoveListener(final Map map, final MapMoveListener listener) {
        // listen to "moveend" events of map
        final HandlerRegistration handlerMap = observe(map, "moveend", new EventListener<MapEvent>() {
            @Override
            public void onEvent(MapEvent event) {
                listener.onMapMove(event);
            }
        });
        // fire events while the map is moving
        // try to set up an event handler for the change of the view center
        // as "moveend" will be only fired when the map stops moving
        View view = map.getView();
        if(view != null) {
            final HandlerRegistration handlerView = OLUtil.observe(view, "change:center",
                    new EventListener<ObjectEvent>() {
                        @Override
                        public void onEvent(ObjectEvent event) {
                            // create an artificial move event
                            Event e2 = createLinkedEvent(event, "move", map);
                            MapEvent me = initMapEvent(e2, map);
                            listener.onMapMove(me);
                        }
                    });
            // return a handler registration, which detaches both event
            // handlers
            return new HandlerRegistration() {
                @Override
                public void removeHandler() {
                    handlerMap.removeHandler();
                    handlerView.removeHandler();
                }
            };
        }
        // just return the map handler
        return handlerMap;
    }

    /**
     * Adds a map zoom listener for the given map.
     *
     * @param map
     *            {@link Map}
     * @param listener
     *            {@link MapZoomListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addMapZoomListener(final Map map, final MapZoomListener listener) {
        return observe(map.getView(), "propertychange", new EventListener<ObjectEvent>() {

            @Override
            public void onEvent(ObjectEvent event) {
                if("resolution".equals(event.getKey())) {
                    Event e2 = createLinkedEvent(event, "zoom", map);
                    MapEvent me = initMapEvent(e2, map);
                    listener.onMapZoom(me);
                }
            }
        });
    }

    /**
     * Adds a {@link Style} to the given array of {@link Style}s.
     *
     * @param s
     *            array of {@link Style}s (will be changed)
     * @param s2
     *            {@link Style}
     * @return the changed array
     */
    public static native ol.style.Style[] addStyle(ol.style.Style[] s, ol.style.Style s2) /*-{
		s.push(s2);
		return s;
    }-*/;

    /**
     * Combines two arrays of {@link Style}s.
     *
     * @param s
     *            array of {@link Style}s 1
     * @param s2
     *            array of {@link Style}s 2
     * @return the combined array
     */
    public static native ol.style.Style[] addStyles(ol.style.Style[] s, ol.style.Style[] s2) /*-{
		return s.concat(s2);
    }-*/;

    /**
     * Adds a listener for tile loading errors.
     *
     * @param source
     *            source
     *
     * @param listener
     *            {@link TileLoadErrorListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addTileLoadErrorListener(UrlTile source, final TileLoadErrorListener listener) {
        return observe(source, "tileloaderror", new EventListener<Tile.Event>() {

            @Override
            public void onEvent(Tile.Event event) {
                listener.onTileLoadError(event);
            }
        });
    }

    /**
     * Adds a listener for tile start loading.
     *
     * @param source
     *            source
     *
     * @param listener
     *            {@link TileLoadStartListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addTileLoadStartListener(UrlTile source, final TileLoadStartListener listener) {
        return observe(source, "tileloadstart", new EventListener<Tile.Event>() {

            @Override
            public void onEvent(Tile.Event event) {
                listener.onTileLoadStart(event);
            }
        });
    }

    /**
     * Adds a listener for tile end loading.
     *
     * @param source
     *            source
     *
     * @param listener
     *            {@link TileLoadEndListener}
     * @return {@link HandlerRegistration}
     */
    public static HandlerRegistration addTileLoadEndListener(UrlTile source, final TileLoadEndListener listener) {
        return observe(source, "tileloadend", new EventListener<Tile.Event>() {

            @Override
            public void onEvent(Tile.Event event) {
                listener.onTileLoadEnd(event);
            }
        });
    }

    /**
     * Create an approximation of a circle on the surface of a sphere.
     * @param sphere
     *            The sphere.
     * @param center
     *            Center (`[lon, lat]` in degrees).
     * @param radius
     *            The great-circle distance from the center to the polygon
     *            vertices.
     * @param opt_n
     *            Optional number of vertices for the resulting polygon. Default
     *            is `32`.
     * @return {ol.geom.Polygon} The "circular" polygon.
     */
    public static native Polygon circular(Sphere sphere, ol.Coordinate center, double radius, int opt_n) /*-{
        return $wnd.ol.geom.Polygon.circular(sphere, center, radius, opt_n);
    }-*/;

    /**
     * Combines two {@link Style}s into an array of {@link Style}s.
     *
     * @param s1
     *            {@link Style} 1
     * @param s2
     *            {@link Style} 2
     * @return array of {@link Style}s
     */
    public static native ol.style.Style[] combineStyles(ol.style.Style s1, ol.style.Style s2) /*-{
		return [ s1, s2 ];
    }-*/;

    /**
     * Links to {@link Event}s by delegating the childs methods to the parents
     * methods.
     *
     * @param eParent
     *            parent {@link Event} (is not changed)
     * @param type
     *            type of the event
     * @param currentTarget
     *            current target of the child event
     * @return child {@link Event} (gets its methods linked to the parent event)
     * @param <T>
     *            type of the event
     * @param <U>
     *            type of the target
     */
    public static native <T extends Event, U> T createLinkedEvent(T eParent, String type, U currentTarget) /*-{
		var eChild = {};
		eChild.preventDefault = function() {
			eParent.preventDefault();
			eChild.defaultPrevented = eParent.defaultPrevented;
		};
		eChild.stopPropagation = function() {
			eParent.stopPropagation();
		};
		eChild.currentTarget = currentTarget;
		eChild.defaultPrevented = eParent.defaultPrevented;
		eChild.target = eParent.target;
		eChild.type = type;
		return eChild;
    }-*/;

    /**
     * Creates a sphere with radius equal to the semi-major axis of the WGS84
     * ellipsoid.
     * @return {@link Sphere}
     */
    public static Sphere createSphereWGS84() {
        return OLFactory.createSphere(EARTH_RADIUS_WGS84);
    }

    /**
     * Creates a sphere with radius equal to the semi-major axis of the normal
     * ellipsoid.
     * @return {@link Sphere}
     */
    public static Sphere createSphereNormal() {
        return OLFactory.createSphere(EARTH_RADIUS_NORMAL);
    }

    /**
     * Gets the geometry layout string for the given dimension.
     *
     * @param dim
     *            dimension (i.e. 2 or 3)
     * @return geometry layout string
     */
    public static String getGeometryLayout(int dim) {
        if(dim > 2) {
            return "XYZ";
        }
        return "XY";
    }

    /**
     * Gets the geometry layout string for the given dimension.
     *
     * @param dim
     *            dimension (i.e. 2 or 3)
     * @param measure
     *            include measure 'M' coordinate?
     * @return geometry layout string
     */
    public static String getGeometryLayout(int dim, boolean measure) {
        if(measure) {
            if(dim > 2) {
                return "XYZM";
            }
            return "XYM";
        } else {
            if(dim > 2) {
                return "XYZ";
            }
            return "XY";
        }
    }

    /**
     * Determines the ground resolution (in meters per pixel) at a specified
     * latitude and level of detail.
     *
     * @param latitude
     *            latitude
     * @param zoomLevel
     *            zoomlevel
     * @return ground resolution
     */
    public static double getGroundResolutionInMeters(double latitude, int zoomLevel) {
        return Math.cos(latitude * Math.PI / 180) * 2 * Math.PI * EARTH_RADIUS_WGS84 / getMapSizeInPixels(zoomLevel);
    }

    /**
     * Gets a layer by the given name.
     *
     * @param map
     *            {@link Map}
     * @param name
     *            name of the layer
     * @return {@link Layer} on success, else null
     */
    @Nullable
    public static Base getLayerByName(Map map, String name) {
        CollectionWrapper<Base> layers = new CollectionWrapper<Base>(map.getLayers());
        for(Base l : layers) {
            if(name.equals(getName(l))) {
                return l;
            }
        }
        return null;
    }

    /**
     * Determines the map width and height (in pixels) at a specified level of
     * detail.
     *
     * @param zoomLevel
     *            Level of detail, from 1 (lowest detail) to 23 (highest
     *            detail).
     * @return The map width and height in pixels.
     */
    public static double getMapSizeInPixels(int zoomLevel) {
        return ((double)(1 << zoomLevel)) * 256;
    }

    /**
     * Gets the name of the given {@link Layer}.
     *
     * @param layer
     *            {@link Layer}
     * @return name on success, else null
     */
    @Nullable
    public static String getName(Base layer) {
        return layer.get("name");
    }

    /**
     * Gets a {@link TileGrid} from the given object, if the property is set
     *
     * @param o
     *            {@link ol.source.Source}
     * @return {@link TileGrid} on success, else null
     */
    private static native TileGrid getTileGrid(ol.source.Source o) /*-{
		return o.tileGrid || null;
    }-*/;

    /**
     *
     * @param extent
     * @return width of extent
     */
    public static native double getWidth(Extent extent) /*-{
        return $wnd.ol.extent.getWidth(extent);
    }-*/;

    /**
    *
    * @param extent
    * @return top left coordinate of the extent
    */
   public static native Coordinate getTopLeft(Extent extent) /*-{
       return $wnd.ol.extent.getTopLeft(extent);
   }-*/;

    /**
     * Gets the current zoom level of the given {@link View}.
     *
     * @param v
     *            {@link View}
     * @return Zoom on success, else -1
     */
    private static native int getZoom(View v) /*-{
		return v.getZoom() || -1;
    }-*/;

    /**
     * Gets the current zoomlevel of the given {@link Map}.
     *
     * @param map
     *            {@link Map}
     * @return zoomlevel on success, else -1
     */
    public static int getZoomLevel(Map map) {
        View v = map.getView();
        // try to get zoom
        int z = getZoom(v);
        if(z >= 0) {
            return z;
        }
        // zoom is undefined, so check resolution
        double zoomResolution = v.getResolution();
        // walk layers to find resolution
        CollectionWrapper<Base> layers = new CollectionWrapper<Base>(map.getLayers());
        for(Base l : layers) {
            // get source if layer instance has it
            Source source = l.get("source");
            if(source != null) {
                // try to get a tilegrid from the source
                TileGrid tg = getTileGrid(source);
                if(tg != null) {
                    // check resolutions
                    double[] resolutions = tg.getResolutions();
                    if(resolutions != null) {
                        double dPreviousResolution = 0;
                        for(int i = 0; i < resolutions.length; i++) {
                            // resolutions are sorted in descending order, so
                            // compare with actual one
                            double resolution = resolutions[i];
                            if(resolution <= zoomResolution) {
                                if(i > 1) {
                                    // check to which zoomlevel resolution is
                                    // nearer and prefer the larger number by
                                    // (75%:25%=3)
                                    if((zoomResolution - resolution) / (dPreviousResolution - zoomResolution) < 3) {
                                        return i;
                                    } else {
                                        return i - 1;
                                    }
                                } else {
                                    return 0;
                                }
                            }
                            dPreviousResolution = resolution;
                        }
                    }
                }
            }
        }
        return -1;
    }

    /**
     * Returns the geodesic area in square meters of the given geometry using
     * the haversine formula.
     *
     * @param geom
     *            geometry.
     * @return geodesic area on success, else {@link Double#NaN}
     */
    public static double geodesicArea(Polygon geom) {
        // get coordinates and check that there are at least 2
        Coordinate[][] coordinates = geom.getCoordinates();
        if((coordinates != null) && (coordinates.length > 0)) {
            // get area of outer ring
            double area = geodesicArea(coordinates[0]);
            // walk through inner rings
            for(int i = 1; i < coordinates.length; i++) {
                // if area is valid, subtract it from the outer ring's area
                double holeArea = geodesicArea(coordinates[i]);
                if(!Double.isNaN(holeArea)) {
                    area -= holeArea;
                }
            }
            return area;
        }
        return Double.NaN;
    }

    /**
     * Returns the geodesic area in square meters of the given geometry using
     * the haversine formula.
     *
     * @param coordinates
     *            coordinates.
     * @return geodesic area on success, else {@link Double#NaN}
     */
    private static double geodesicArea(Coordinate[] coordinates) {
        // check that there are at least 2
        if((coordinates != null) && (coordinates.length > 1)) {
            Sphere sphere = createSphereNormal();
            // only return positive area
            return Math.abs(sphere.geodesicArea(coordinates));
        }
        return Double.NaN;
    }

    /**
     * Returns the geodesic length in meters of the given geometry using the
     * haversine formula.
     *
     * @param geom
     *            geometry.
     * @return geodesic length on success, else {@link Double#NaN}
     */
    public static double geodesicLength(SimpleGeometryCoordinates geom) {
        // get coordinates and check that there are at least 2
        Coordinate[] coordinates = geom.getCoordinates();
        if((coordinates != null) && (coordinates.length > 1)) {
            // calculate the distance on every segment of the line and add it up
            Sphere sphere = createSphereNormal();
            double distance = 0;
            for(int i = 0; i <= coordinates.length - 2; i++) {
                Coordinate c1 = coordinates[i];
                Coordinate c2 = coordinates[i + 1];
                distance += sphere.haversineDistance(c1, c2);
            }
            return distance;
        }
        return Double.NaN;
    }

    /**
     * Initializes a {@link MapEvent}, can be used for creating a new
     * {@link MapEvent} as it does not work with ol.js in release mode using the
     * OpenLayers API.
     *
     * @param e
     *            base {@link Event}
     * @param map
     *            {@link Map}
     * @return {@link MapEvent}
     */
    public static native MapEvent initMapEvent(Event e, Map map) /*-{
		e.map = map;
		e.framestate = null;
		return e;
    }-*/;

    /**
     * Limits the zoomlevels of the {@link Xyz} layer source created of the
     * given {@link XyzOptions}.
     *
     * @param options
     *            {@link XyzOptions}
     * @param minZoomLevel
     *            minimum zoomlevel (0-28)
     * @param maxZoomLevel
     *            maximum zoomlevel (0-28)
     */
    public static void limitZoomLevels(XyzOptions options, int minZoomLevel, int maxZoomLevel) {
        TileGridOptions tileGridOptions = OLFactory.<TileGridOptions> createOptions();
        tileGridOptions.setMinZoom(minZoomLevel);
        tileGridOptions.setMaxZoom(maxZoomLevel);
        options.setTileGrid(OLFactory.createTileGridXYZ(tileGridOptions));
    }

    /**
     * Registers the given event listener to listen for the given event type on
     * the given {@link Observable}.
     *
     * @param o
     *            {@link Observable}
     * @param eventType
     *            event type
     * @param listener
     *            listener
     * @return {@link HandlerRegistration}
     */
    public static <E extends Event> HandlerRegistration observe(Observable o, String eventType,
            EventListener<E> listener) {
        EventsKey key = o.on(eventType, listener);
        return new OLHandlerRegistration(o, key);
    }

    /**
     * Registers the given event listener to listen once for the given event
     * type on the given {@link Observable}.
     *
     * @param o
     *            {@link Observable}
     * @param eventType
     *            event type
     * @param listener
     *            listener
     * @return {@link HandlerRegistration}
     */
    public static <E extends Event> HandlerRegistration observeOnce(Observable o, String eventType,
            EventListener<E> listener) {
        EventsKey key = o.once(eventType, listener);
        return new OLHandlerRegistration(o, key);
    }

    /**
     * Sets the container for the given {@link Map} to the given {@link Widget}.
     *
     * @param map
     *            {@link Map}
     * @param target
     *            {@link Widget}
     */
    public static void setMapTarget(Map map, Widget target) {
        map.setTarget(target.getElement());
    }

    /**
     * Sets the name of the given {@link Layer}.
     *
     * @param layer
     *            {@link Layer}
     * @param name
     *            name
     */
    public static void setName(Base layer, String name) {
        layer.set("name", name);
    }

    /**
     * Set the style for the feature. This can be a single style object, an
     * array of styles, or a function that takes a resolution and returns an
     * array of styles. If it is `null` the feature has no style (a `null`
     * style).
     *
     * @param f
     *            {@link ol.Feature}
     * @param style
     *            Style for this feature.
     */
    public static native void setStyle(ol.Feature f, @Nullable ol.style.Style[] style) /*-{
        f.setStyle(style);
    }-*/;

    /**
     * Set the style for features. This can be a single style object, an array
     * of styles, or a function that takes a feature and resolution and returns
     * an array of styles. If it is `undefined` the default style is used. If it
     * is `null` the layer has no style (a `null` style), so only features that
     * have their own styles will be rendered in the layer. See {@link ol.style}
     * for information on the default style.
     *
     * @param l
     *            Layer
     * @param style
     *            Layer style.
     */
    public static native void setStyle(ol.layer.Vector l, @Nullable ol.style.Style[] style) /*-{
        l.setStyle(style);
    }-*/;

    /**
     * Transforms coordinates from source projection to destination projection.
     * This returns new coordinates (and does not modify the original).
     *
     * @param coordinates
     *            coordinates to transform
     * @param source
     *            source projection
     * @param destination
     *            destination projection
     * @return transformed coordinates
     */
    public static Coordinate[] transform(Coordinate[] coordinates, String source, String destination) {

        Coordinate[] transformedCoordinates = new Coordinate[coordinates.length];

        for(int i = 0; i < coordinates.length; i++) {
            transformedCoordinates[i] = Projection.transform(coordinates[i], source, destination);
        }

        return transformedCoordinates;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy
      xmlns="urn:oasis:names:tc:xacml:1.0:policy"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:oasis:names:tc:xacml:1.0:policy
        cs-xacml-schema-policy-01.xsd"
      PolicyId="urn:oasis:names:tc:xacml:1.0:conformance-test:IIB009:policy"
      RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">
    <Description>
        Policy for Conformance Test IIB009.
    </Description>
    <Target>
        <Subjects>
            <AnySubject/>
        </Subjects>
        <Resources>
            <AnyResource/>
        </Resources>
        <Actions>
            <AnyAction/>
        </Actions>
    </Target>
    <Rule
          RuleId="urn:oasis:names:tc:xacml:1.0:conformance-test:IIB009:rule"
          Effect="Permit">
        <Description>
            Julius Hibbert can read or write Bart Simpson's medical record.
        </Description>
        <Target>
            <Subjects>
                <Subject>
                    <SubjectMatch
                          MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                        <AttributeValue
                              DataType="http://www.w3.org/2001/XMLSchema#string">Julius Hibbert</AttributeValue>
                        <SubjectAttributeDesignator
                              AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id"
                              DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    </SubjectMatch>
                </Subject>
            </Subjects>
            <Resources>
                <Resource>
                    <ResourceMatch
                          MatchId="urn:oasis:names:tc:xacml:1.0:function:anyURI-equal">
                        <AttributeValue
                              DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://medico.com/record/patient/BartSimpson</AttributeValue>
                        <ResourceAttributeDesignator
                              AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"
                              DataType="http://www.w3.org/2001/XMLSchema#anyURI"/>
                    </ResourceMatch>
                </Resource>
            </Resources>
            <Actions>
                <Action>
                    <ActionMatch
                          MatchId="urn:oasis:names:tc:xacml:1.0:function:regexp-string-match">
                        <AttributeValue
                              DataType="http://www.w3.org/2001/XMLSchema#string">read|write</AttributeValue>
                        <ActionAttributeDesignator
                              AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
                              DataType="http://www.w3.org/2001/XMLSchema#string"/>
                    </ActionMatch>
                </Action>
            </Actions>
        </Target>
    </Rule>
</Policy>


text:
'use strict';

angular.module('etestApp')
  .controller('VerbalController', function ($scope, User, Auth, UtilityService) {
    var vm = this;
    vm.tests = [
      {
        image: 'assets/images/tcs_logo_stacked.png',
        title: 'TCS Verbal Ability Tests',
        content: 'Take TCS Verbal Ability test',
        link: 'main.tcsverbal'
      },
      {
        image: 'assets/images/ibm_logo.png',
        title: 'IBM Verbal Test',
        content: 'Coming Soon',
        link: 'main.verbal'
      },
      {
        image: 'assets/images/mu-sigma.jpg',
        title: 'Mu Apt',
        content: 'Coming Soon',
        link: 'main.verbal'
      }
    ];

    UtilityService.generateMeta({
      description: verbalKeywords.join(", "),
      title: "etest | TCS Verbal Ability Test Online",
      keywords: verbalKeywords.join(", "),
    });

  });


text:
class HTMLGenerator(object):
    name = 'HTML'
    aliases = ['html']

    def get_description(self):
        return (self.name, self.aliases)


text:
package simpledb;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;

import simpledb.Aggregator.Op;
import simpledb.systemtest.SimpleDbTestBase;
import simpledb.systemtest.SystemTestUtil;

public class TableStatsTest extends SimpleDbTestBase {
	public static final int IO_COST = 71;

	ArrayList<ArrayList<Integer>> tuples;
	HeapFile f;
	String tableName;
	int tableId;

	@Before public void setUp() throws Exception {
		super.setUp();
		this.tuples = new ArrayList<ArrayList<Integer>>();
		this.f = SystemTestUtil.createRandomHeapFile(10, 1020, 32, null, tuples);

		this.tableName = SystemTestUtil.getUUID();
		Database.getCatalog().addTable(f, tableName);
		this.tableId = Database.getCatalog().getTableId(tableName);
	}

	private double[] getRandomTableScanCosts(int[] pageNums, int[] ioCosts) throws IOException, DbException, TransactionAbortedException {
		double[] ret = new double[ioCosts.length];
		for(int i = 0; i < ioCosts.length; ++i) {
			HeapFile hf = SystemTestUtil.createRandomHeapFile(1, 992*pageNums[i], 32, null, tuples);
			Assert.assertEquals(pageNums[i], hf.numPages());
			String tableName = SystemTestUtil.getUUID();
			Database.getCatalog().addTable(hf, tableName);
			int tableId = Database.getCatalog().getTableId(tableName);
			ret[i] = (new TableStats(tableId, ioCosts[i])).estimateScanCost();
		}
		return ret;
	}
	/**
	 * Verify the cost estimates of scanning various numbers of pages from a HeapFile
	 * This test checks that the estimateScanCost is:
	 *   +linear in numPages when IO_COST is constant
	 *   +linear in IO_COST when numPages is constant
	 *   +quadratic when IO_COST and numPages increase linearly.
	 */
	@Test public void estimateScanCostTest() throws IOException, DbException, TransactionAbortedException {
		Object[] ret;
		int[] ioCosts = new int[20];
		int[] pageNums = new int[ioCosts.length];
		// IO_COST constant, numPages change
		for(int i = 0; i < ioCosts.length; ++i) {
			ioCosts[i] = 1;
			pageNums[i] = 3*(i+1);
		}
		double stats[] = getRandomTableScanCosts(pageNums, ioCosts);
		ret = SystemTestUtil.checkConstant(stats);
		Assert.assertEquals(ret[0], Boolean.FALSE);
		ret = SystemTestUtil.checkLinear(stats);
		Assert.assertEquals(ret[0], Boolean.TRUE);
		// numPages constant, IO_COST change
		for(int i = 0; i < ioCosts.length; ++i) {
			ioCosts[i] = 10*(i + 1);
			pageNums[i] = 3;
		}
		stats = getRandomTableScanCosts(pageNums, ioCosts);
		ret = SystemTestUtil.checkConstant(stats);
		Assert.assertEquals(ret[0], Boolean.FALSE);
		ret = SystemTestUtil.checkLinear(stats);
		Assert.assertEquals(ret[0], Boolean.TRUE);
		//numPages & IO_COST increase linearly
		for(int i = 0; i < ioCosts.length; ++i) {
			ioCosts[i] = 3*(i + 1);
			pageNums[i] = (i+1);
		}
		stats = getRandomTableScanCosts(pageNums, ioCosts);
		ret = SystemTestUtil.checkConstant(stats);
		Assert.assertEquals(ret[0], Boolean.FALSE);
		ret = SystemTestUtil.checkLinear(stats);
		Assert.assertEquals(ret[0], Boolean.FALSE);
		ret = SystemTestUtil.checkQuadratic(stats);
		Assert.assertEquals(ret[0], Boolean.TRUE);

	}

	/**
	 * Verify the table-cardinality estimates based on a selectivity estimate
	 */
	@Test public void estimateTableCardinalityTest() {
		TableStats s = new TableStats(this.tableId, IO_COST);

		// Try a random selectivity
		Assert.assertEquals(306, s.estimateTableCardinality(0.3));

		// Make sure we get all rows with 100% selectivity, and none with 0%
		Assert.assertEquals(1020, s.estimateTableCardinality(1.0));
		Assert.assertEquals(0, s.estimateTableCardinality(0.0));
	}

	/**
	 * Verify that selectivity estimates do something reasonable.
	 * Don't bother splitting this into N different functions for
	 * each possible Op because we will probably catch any bugs here in
	 * IntHistogramTest, so we hopefully don't need all the JUnit checkboxes.
	 */
	@Test public void estimateSelectivityTest() {
		final int maxCellVal = 32;	// Tuple values are randomized between 0 and this number

		final Field aboveMax = new IntField(maxCellVal + 10);
		final Field atMax = new IntField(maxCellVal);
		final Field halfMaxMin = new IntField(maxCellVal/2);
		final Field atMin = new IntField(0);
		final Field belowMin = new IntField(-10);

		TableStats s = new TableStats(this.tableId, IO_COST);

		for (int col = 0; col < 10; col++) {
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.EQUALS, aboveMax), 0.001);
			Assert.assertEquals(1.0/32.0, s.estimateSelectivity(col, Predicate.Op.EQUALS, halfMaxMin), 0.015);
			Assert.assertEquals(0, s.estimateSelectivity(col, Predicate.Op.EQUALS, belowMin), 0.001);

			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, aboveMax), 0.001);
			Assert.assertEquals(31.0/32.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, halfMaxMin), 0.015);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, belowMin), 0.015);

			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, aboveMax), 0.001);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, atMax), 0.001);
			Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, halfMaxMin), 0.1);
			Assert.assertEquals(31.0/32.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, atMin), 0.05);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, belowMin), 0.001);

			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, aboveMax), 0.001);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, atMax), 0.015);
			Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, halfMaxMin), 0.1);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, atMin), 0.001);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, belowMin), 0.001);

			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, aboveMax), 0.001);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, atMax), 0.015);
			Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, halfMaxMin), 0.1);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, atMin), 0.015);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, belowMin), 0.001);

			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, aboveMax), 0.001);
			Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, atMax), 0.015);
			Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, halfMaxMin), 0.1);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, atMin), 0.05);
			Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, belowMin), 0.001);
		}
	}
}


text:
title: Tweaking the Linux Console
permalink: /tweak-linux-console/
excerpt: We can tweak a lot of things about the linux console. Here are some ways to do it with setterm and disable the annoying PC Speaker.
date: 2008-04-16 15:04:45 -0600
layout: post
categories: [ Linux System ]
tags: [ console, customize ]
---

One of the main programs used for tweaking the console is setterm. It "writes to standard output a character string that will invoke the specified terminal capabilities. Where possible terminfo database (terminfo is a data base describing terminals, used by screen-oriented programs and libraries such as ncurses) is consulted to find the string to use."

## Disable the Annoying PC Speaker

Add this to `/etc/rc.local`

	/sbin/modprobe -r pcspkr

## Disable Screen Blanking

By default Linux enables screen blanking, like in a desktop environment. You can disable it by running this in the console.

	$ setterm -powersave off -blank 0

Or to permanently disable it, add this to /etc/rc.local

	sh -c 'setterm -blank 0 -powersave off -powerdown 0 `< /dev/console >` /dev/console 2>&1'
	xset s off > /dev/null 2>&1

## Other Useful Options

Resets the terminal to its power on state:

	$ setterm -reset

Alternatively, initialize terminal:

	$ setterm -initialize

Turns the terminal's cursor on or off:

	$ setterm -cursor [on|off]

Turns automatic line-wrapping on or off (virtual consoles only)

	$ setterm -linewrap [on|off]

Sets the foreground text color (virtual consoles only):

	$ setterm -foreground blue

Sets the background text color (virtual consoles only):

	$ setterm -background red

Enables or disables the sending of kernel printk() messages to the console (virtual consoles only). Useful if you get lots message from iptables firewall:

	$ setterm -msg [on|off]

## Sources

Article: [Linux disable screen blanking](http://www.cyberciti.biz/tips/linux-disable-screen-blanking-screen-going-blank.html)


text:
require "spec_helper_lite"

describe Undo do
  let(:object) { double :object, change: true }
  subject { described_class }

  describe "pass through options to serializer" do
    let(:serializer) { double :serializer }

    specify "from #wrap" do
      expect(serializer).to receive(:serialize).with(object, foo: :bar)

      wrapper = subject.wrap object,
        serializer: serializer,
        store_on: [:change],
        foo: :bar

      wrapper.change
    end
  end

  describe "pass through options to storage" do
    let(:storage) { double :storage }

    specify "from #wrap" do
      expect(storage).to receive(:store).with(anything, object, foo: :bar)

      wrapper = subject.wrap object,
        storage: storage,
        store_on: [:change],
        foo: :bar

      wrapper.change
    end
  end

  describe "#wrap" do
    before do
      subject::Wrapper.configure do |config|
        config.store_on = [:change]
      end
    end

    it "is a decorator" do
      object = %w[hello world]

      decorator = subject.wrap object
      expect(object).to receive(:some_method)
      decorator.some_method

      expect(decorator.class).to eq Array
      expect(decorator).to be_a Array
    end

    describe "restores" do
      specify "using provided uuid" do
        uuid = "uniq_identifier"
        model = subject.wrap object, uuid: uuid
        model.change

        expect(subject.restore uuid).to eq object
      end

      specify "using gerenated uuid" do
        uuid = object.object_id
        model = subject.wrap object, uuid_generator: -> object { object.object_id }
        model.change

        expect(model.undo_uuid).to eq uuid
        expect(subject.restore uuid).to eq object
      end
    end
  end
end


text:
package fr.xebia.librestry;

import junit.framework.Assert;

import org.junit.Test;

import fr.xebia.librestry.domain.Book;

public class SuccessTest {

	@Test
	public void test_success1() {
		Book book = new Book();
		book.setAuthor("author");
		book.setTitle("title");

		Assert.assertEquals("author", book.getAuthor());
		Assert.assertEquals("title", book.getTitle());
	}

	@Test
	public void test_success2() {

	}

	@Test
	public void test_success3() {

	}
}


text:
using System;
using System.Diagnostics;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
using SonarLint.VisualStudio.Integration.Resources;

namespace SonarLint.VisualStudio.Integration
{
    internal class BuildPropertyTestProjectIndicator : ITestProjectIndicator
    {
        private readonly IProjectSystemHelper projectSystem;
        private readonly IProjectPropertyManager propertyManager;

        public BuildPropertyTestProjectIndicator(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            projectSystem = serviceProvider.GetService<IProjectSystemHelper>();
            projectSystem.AssertLocalServiceIsNotNull();

            propertyManager = serviceProvider.GetMefService<IProjectPropertyManager>();
            Debug.Assert(propertyManager != null, $"Failed to get {nameof(IProjectPropertyManager)}");
        }

        public bool? IsTestProject(Project project)
        {
            VerifyThatProjectHasBuildProperties(project);

            var sonarTest = propertyManager.GetBooleanProperty(project, Constants.SonarQubeTestProjectBuildPropertyKey);

            return sonarTest;
        }

        private void VerifyThatProjectHasBuildProperties(Project project)
        {
            var hierarchy = projectSystem.GetIVsHierarchy(project);

            if (!(hierarchy is IVsBuildPropertyStorage))
            {
                throw new ArgumentException(Strings.ProjectFilterDteProjectFailedToGetIVs, nameof(project));
            }
        }
    }
}


text:
package com.amazonaws.services.athena.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The metadata and rows that comprise a query result set. The metadata describes the column structure and data types.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResultSet implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The rows in the table.
     *

     */
    private java.util.List<Row> rows;
    /**
     *

     * The metadata that describes the column structure and data types of a table of query results.
     *

     */
    private ResultSetMetadata resultSetMetadata;

    /**
     *

     * The rows in the table.
     *

     *
     * @return The rows in the table.
     */

    public java.util.List<Row> getRows() {
        return rows;
    }

    /**
     *

     * The rows in the table.
     *

     *
     * @param rows
     *        The rows in the table.
     */

    public void setRows(java.util.Collection<Row> rows) {
        if (rows == null) {
            this.rows = null;
            return;
        }

        this.rows = new java.util.ArrayList<Row>(rows);
    }

    /**
     *

     * The rows in the table.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setRows(java.util.Collection)} or {@link #withRows(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param rows
     *        The rows in the table.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultSet withRows(Row... rows) {
        if (this.rows == null) {
            setRows(new java.util.ArrayList<Row>(rows.length));
        }
        for (Row ele : rows) {
            this.rows.add(ele);
        }
        return this;
    }

    /**
     *

     * The rows in the table.
     *

     *
     * @param rows
     *        The rows in the table.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultSet withRows(java.util.Collection<Row> rows) {
        setRows(rows);
        return this;
    }

    /**
     *

     * The metadata that describes the column structure and data types of a table of query results.
     *

     *
     * @param resultSetMetadata
     *        The metadata that describes the column structure and data types of a table of query results.
     */

    public void setResultSetMetadata(ResultSetMetadata resultSetMetadata) {
        this.resultSetMetadata = resultSetMetadata;
    }

    /**
     *

     * The metadata that describes the column structure and data types of a table of query results.
     *

     *
     * @return The metadata that describes the column structure and data types of a table of query results.
     */

    public ResultSetMetadata getResultSetMetadata() {
        return this.resultSetMetadata;
    }

    /**
     *

     * The metadata that describes the column structure and data types of a table of query results.
     *

     *
     * @param resultSetMetadata
     *        The metadata that describes the column structure and data types of a table of query results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultSet withResultSetMetadata(ResultSetMetadata resultSetMetadata) {
        setResultSetMetadata(resultSetMetadata);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getRows() != null)
            sb.append("Rows: ").append(getRows()).append(",");
        if (getResultSetMetadata() != null)
            sb.append("ResultSetMetadata: ").append(getResultSetMetadata());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ResultSet == false)
            return false;
        ResultSet other = (ResultSet) obj;
        if (other.getRows() == null ^ this.getRows() == null)
            return false;
        if (other.getRows() != null && other.getRows().equals(this.getRows()) == false)
            return false;
        if (other.getResultSetMetadata() == null ^ this.getResultSetMetadata() == null)
            return false;
        if (other.getResultSetMetadata() != null && other.getResultSetMetadata().equals(this.getResultSetMetadata()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getRows() == null) ? 0 : getRows().hashCode());
        hashCode = prime * hashCode + ((getResultSetMetadata() == null) ? 0 : getResultSetMetadata().hashCode());
        return hashCode;
    }

    @Override
    public ResultSet clone() {
        try {
            return (ResultSet) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.athena.model.transform.ResultSetMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package OpenXPKI::Server::Workflow::Activity::Tools::RenderSubject;

use strict;

use OpenXPKI::Debug;
use OpenXPKI::Exception;
use OpenXPKI::Serialization::Simple;
use OpenXPKI::Server::Context qw( CTX );
use English;
use Template;
use Data::Dumper;

use base qw( OpenXPKI::Server::Workflow::Activity );

sub execute {
    my $self     = shift;
    my $workflow = shift;

    ##! 8: 'Start'

    my $context = $workflow->context();
    my $config = CTX('config');

    my $tt = new Template();
    my $ser = new OpenXPKI::Serialization::Simple;
    my $result;

    # Get the profile name and style
    my $profile = $self->param('cert_profile');
    $profile = $context->param('cert_profile') unless($profile);

    my $style = $self->param('cert_subject_style');
    $style = $context->param('cert_subject_style') unless($style);

    if (!$profile  || !$style) {
        OpenXPKI::Exception->throw(
            message => 'I18N_OPENXPKI_SERVER_WORKFLOW_ACTIVITY_TOOLS_RENDER_SUBJECT_NO_PROFILE',
            params  => {
                PROFILE => $profile,
                STYLE   => $style,
            }
        );
    }

    if (!$context->param('cert_subject_parts')) {
        OpenXPKI::Exception->throw(
            message => 'I18N_OPENXPKI_SERVER_WORKFLOW_ACTIVITY_TOOLS_RENDER_SUBJECT_NO_SUBJECT_VARS_IN_CONTEXT',
        );
    }
    # Render the DN - get the input data from the context
    my $subject_vars = $ser->deserialize(  $context->param('cert_subject_parts') );

    ##! 16: 'Deserialized cert_subject_parts ' . Dumper $subject_vars

    # TODO - this does not work! Will fail with non-scalar items and
    # crashes the search_cert method used in csr workflow!
    map {
        $subject_vars->{$_} =~ s{,}{\\,}xmsg if ($subject_vars->{$_} && !ref $subject_vars->{$_});
    } keys %{$subject_vars};

    ##! 16: 'Cleaned subject_vars' . Dumper $subject_vars
    CTX('log')->application()->trace("Subject render input vars " . Dumper $subject_vars);

    my $cert_subject = CTX('api2')->render_subject_from_template(
        profile => $profile,
        style   => $style,
        vars    => $subject_vars
    );

    if (!$cert_subject) {
        OpenXPKI::Exception->throw(
            message => 'I18N_OPENXPKI_SERVER_WORKFLOW_ACTIVITY_TOOLS_RENDER_SUBJECT_DN_RESULT_EMPTY',
            params  => {
                PROFILE => $profile,
                STYLE   => $style,
            }
        );
    }

    CTX('log')->application()->info("Rendering subject: $cert_subject");

    my $cert_san_parts  = $context->param('cert_san_parts');
    my $extra_san = {};
    if ($cert_san_parts) {
        $extra_san = $ser->deserialize( $cert_san_parts );
    }

    ##! 32: 'extra san' . Dumper $extra_san

    my $san_list;
    # Try to render using the template mode, will return undef if there is no
    # rendering rule

    $san_list = CTX('api2')->render_san_from_template(
        profile => $profile,
        style   => $style,
        vars    => $subject_vars,
        additional => $extra_san || {},
    );

    ##! 64: "Entries in san_list \n" .  Dumper $san_list;

    # store in context
    $context->param('cert_subject' => $cert_subject);

    # Current serialize creates an "UNDEF" string which fails an easy "is empty" test
    if ($san_list) {
        $context->param('cert_subject_alt_name' => $ser->serialize( $san_list ));
    } else {
        $context->param('cert_subject_alt_name' => '');
    }

    # If the SAN come from the internal rendering we need to set the source
    # parameter for as this is required by persist_csr

    my $source_ref;
    if ($context->param('sources')) {
        $source_ref = $ser->deserialize($context->param('sources'));
    } else {
        $source_ref =  {};
    }

    if (!$source_ref->{cert_subject_alt_name_parts} && !$source_ref->{cert_subject_alt_name}) {
        $source_ref->{cert_subject_alt_name} = 'PROFILE';
    }
    $context->param('sources' => $ser->serialize( $source_ref ));

    return 1;

}

1;
__END__

=head1 Name

OpenXPKI::Server::Workflow::Activity::Tools::RenderSubject;

=head1 Description

Take the input parameters provided by the ui and render the subject and
subject alternative according to the profiles template definition.
The SAN part is made up from two seperate sources:

=head2 templated SAN entries

Define template fields in the ui.subject section of you profile and use them in the
rendering information in subject.san the same way you do for the subject.

Example:

  ui:
    subject:
    - hostname
    - hostname2
    - port

  subject:
    dn: CN=[% hostname %][% IF port AND port != 443 %]:[% port %][% END %],DC=Test Deployment,DC=OpenXPKI,DC=org
    san:
      dns:
      - "[% hostname %]"
      - "[% FOREACH entry = hostname2 %][% entry %]|[% END %]"

This will end up with a certificate which has the hostname as CN and
additionally copied to the SAN. A second hostname is also put into the SAN
section, empty or duplicate values are purged, in case that hostname2
is an array (multi input field), you need to use a foreach loop and end
each entry with the pipe symbol |. Hint: The foreach loop automagically
degrades if the given value is a scalar or even undef, so use foreach
whenever a list is possible.

Templated entries are displayed to the user during request but can not be
removed by the user.

=head2 free SAN entries

To enable free SAN entries add a section ui.san next to you ui.subject. The
form fields MUST have a key that fits any of the allowed SAN items (e.g DNS,
IP, OID) and the value must be given in the approriate format for this item.
The users input is mapped without further templating to the san section of the
certificate (duplicate items and and leading/trailing whitespace are removed).

Note: If you upload a PKCS10 request having SANs, those ones that match the
available type are prefilled. Items that do not match a defined type are
discarded.

Example:

   # In the style definition
   ui:
     san:
        - san_dns
        - san_ip

   # In the template section
   template:
     san_dns:
       id: dns
       label: I18N_OPENXPKI_SAN_DNS
       description: I18N_OPENXPKI_SAN_DNS_DESCRIPTION
       type: freetext
       width: 40
       min: 0
       max: 20

    san_ip:
       id: ip
       label: I18N_OPENXPKI_SAN_IP
       description: I18N_OPENXPKI_SAN_IP_DESCRIPTION
       type: freetext
       width: 15
       min: 0
       max: 20

The above code will present the user up to 20 fields each to enter IPs or DNS
names. Each entry will show up "as is" as a single san entry.

=head1 Configuration

=head2 Activity Parameters

=over

=item cert_profile

Determines the used profile, has priority over context key.

=item cert_subject_style

Determines the used profile substyle, has priority over context key.

=back

=head2 context values

=over

=item cert_subject_parts

The main subject parameters, used for rendering the subject dn and in template
mode for the san. The "cert_subject_" prefix is removed from the keys name.

=item cert_profile (deprecated, use activity parameter)

Determines the used profile, activity parameter has priority!

=item cert_subject_style (deprecated, use activity parameter)

Determines the used profile substyle, activity parameter has priority!

=item cert_subject

Holds the result for the subject.

=item cert_subject_alt_name

Holds the result for the san section.

=back


text:
/**
 * Define a namespace
 * Don't define the same namespace in other script files. See for example mutiInstances.js
 *
 * you may also want to create a package.
 * jsx3.lang.Package.definePackage("sfn.dialogs", function(dialogs) { Your functions } )
 * @see jsx3.lang.Package
 */
if (window["sfn"] == null)
window.sfn  = new Object();

/**
 * Returns the application server object which by default is the application
 * namespace as specified in Project->Deployment Options.
 *
 * @returns {jsx3.app.Server} the application server object.
 */
  sfn.getServer = function() {
    // should be the same as namespace in Project -> Deployment Options
    return sampledialogs32;
  }

/**
 * Clear work area
 *
 * @param workArea {jsx3.app.Model} – the JSX object to be cleared.
 */
sfn.clearWorkArea = function(workArea) {
       workArea.removeChildren();
}

/**
* Launches a none existing gui as a child of the target.
* brings an existing gui forward instead of launching it again
*
* @param target {jsx3.app.Model} – JSX Object.
* @guiFile {String} the serialization file to deserialize. Base diectory is 'components/'
* @bClear {boolean} if true clear the work area before load();
*
* @see jsx3.app.Model.load()
*/
sfn.launchComponent= function(target,guiFile,bClear){
    var componentName = guiFile.doReplace('.xml','')
    if(bClear){
       sfn.clearWorkArea(target);
    }
   var objDialog = target.getChild(componentName);
   if (!objDialog){
    objDialog =  target.load("components/"+guiFile);
    objDialog.setName(componentName);
   }
   else{
    objDialog.focus();
   }

return objDialog;
}

/**
  * Launches a simple dialog as a child of server body block if one dosen't exists.
  * Brings an existing dialog forward instead of launching it again
  */
sfn.launchSimple = function() {
   var objDialog = sfn.getServer().getBodyBlock().getChild('dlgSimpleDialog');
   if (!objDialog){
     objDialog = sfn.getServer().getBodyBlock().load("components/simpleDialog.xml");
        }
   else{
    objDialog.focus();
   }
}

/**
 * Show salert bound to dialog box.
 */
sfn.showDialogAlert = function() {
  sfn.getServer().getJSXByName("dlgParentDialog").alert("Dialog Alert","
This is an alert bound to this dialog.

Note that while the application is still active, the dialog is disabled.
");
}

/**
 * Shows confirm alert.
 */
sfn.showConfirmAlert = function() {
  sfn.getServer().confirm("Confirm Alert","
This is a confirm alert.
");
}

/**
 * Shows prompt alert.
 */
sfn.showPromptAlert = function() {
  sfn.getServer().prompt("Prompt Alert","
This is a prompt alert.
", sfn.showJSAlert);
}

/**
 * Displays alert and closes dialog box that called the function.
 *
 * @param objDialog {jsx3.gui.Dialog} dialog box to close.
 * @param textToDisplay {String} string to be displayed in alert.
 */
sfn.showJSAlert = function(objDialog, textToDisplay) {
  alert(textToDisplay);
  objDialog.doClose();
}

/**
 * Shows alert bound to application's server instance.
 */
sfn.showServerAlert = function() {
  sfn.getServer().alert("My Alert","
This is an alert bound to this application's server instance.

Note that the user cannot interact with the application until the alert is dismissed.
");
}

/**
 * Formats error.
 */
sfn.formatErr = function(err){
   alert("Error:  "+err);
}


text:
package test.org.apache.skywalking.apm.testcase.toolkit.controller;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import org.apache.skywalking.apm.toolkit.model.User;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.CallableWrapper;
import org.apache.skywalking.apm.toolkit.trace.RunnableWrapper;
import org.apache.skywalking.apm.toolkit.trace.SupplierWrapper;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Component;

@Component
public class TestService {

    private static final ExecutorService SERVICE = Executors.newSingleThreadExecutor(r -> {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        return thread;
    });

    @Trace
    public void testTag() {
        ActiveSpan.tag("key", "value");
    }

    @Trace
    @Tag(key = "p1", value = "arg[0]")
    @Tag(key = "p2", value = "arg[1]")
    public void testTagAnnotation(String param1, String param2) {
        // whatever
    }

    @Trace
    public void testError() {
        ActiveSpan.error();
    }

    @Trace
    public void testErrorMsg() {
        ActiveSpan.error("TestErrorMsg");
    }

    @Trace
    public void testErrorThrowable() {
        ActiveSpan.error(new RuntimeException("Test-Exception"));
    }

    @Trace
    public void testDebug() {
        ActiveSpan.debug("TestDebugMsg");
    }

    @Trace
    @Tag(key = "username", value = "returnedObj.username")
    public User testTagAnnotationReturnInfo(final String username, final Integer age) {
        return new User(username, age);
    }

    @Trace
    @Tag(key = "testTag", value = "arg[0]")
    public void testInfo(final String testInfoParam) {
        ActiveSpan.info("TestInfoMsg");
    }

    public void asyncRunnable(Runnable runnable) {
        SERVICE.submit(RunnableWrapper.of(runnable));
    }

    public void asyncCallable(Callable<Boolean> callable) {
        SERVICE.submit(CallableWrapper.of(callable));
    }

    public void asyncSupplier(Supplier<Boolean> supplier) {
        CompletableFuture.supplyAsync(SupplierWrapper.of(supplier));
    }

    @Trace
    public void testSetOperationName(String operationName) {
        ActiveSpan.setOperationName(operationName);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <changeSet id="1" author="yohahn">
        <createTable tableName="book">
            <column name="id" type="bigint" autoIncrement="true">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="title" type="varchar(255)">
                <constraints nullable="false"/>
            </column>
        </createTable>
    </changeSet>
</databaseChangeLog>


text:
import React from "react";
import PropTypes from "prop-types";

const types = ["line", "circle"] as const;
export type Type = typeof types[number];
export const PType = PropTypes.oneOf([...types]);

const sizes = ["normal", "small"] as const;
export type Size = typeof sizes[number];
export const PSize = PropTypes.oneOf([...sizes]);

const statuses = ["normal", "active", "success", "exception"] as const;
export type Status = typeof statuses[number];
export const PStatus = PropTypes.oneOf([...statuses]);

type Text = React.ReactNode;
export const PText = PropTypes.node;

export type WrapStyle = {
  width?: string;
  height?: string;
};
export type TextWrapStyle = {
  width?: string;
  fontSize?: string;
};

export interface ProgressProps {
  max?: number;
  value?: number;
  type?: Type;
  size?: Size;
  status?: Status;
  width?: number;
  strokeWidth?: number;
  strokeColor?: string;
  showInfo?: boolean;
  infoWidth?: number;
  customInfo?: Text;
}

export interface LineBarProps {
  strokeWidth?: number;
  max?: number;
  value?: number;
  size?: Size;
  strokeColor?: string;
}

export interface CircleBarProps {
  max?: number;
  value?: number;
  size?: Size;
  width?: number;
  strokeWidth?: number;
  strokeColor?: string;
}

export interface TextContentProps {
  max?: number;
  value?: number;
  type?: Type;
  size?: Size;
  status?: Status;
  customInfo?: Text;
}

export const DOUBLE: number = 2;
export const PERCENTAGE_VALUE: number = 100;
// eslint-disable-next-line
export const CIRCLE_PROGRESS_RATIO_OF_FONT_SIZE_AND_WIDTH: number = 1 / 6;
export const VIEWBOX_SIZE: number = 100;
export const SVG_BASE_RADIUS: number = VIEWBOX_SIZE / DOUBLE;
export const CIRCLE_NORMAL_DEFAULT_WIDTH: number = 120;
export const CIRCLE_SMALL_DEFAULT_WIDTH: number = 84;
export const CIRCLE_NORMAL_DEFAULT_STROKE_WIDTH: number = 6;
export const CIRCLE_SMALL_DEFAULT_STROKE_WIDTH: number = 4;
export const LINE_NORMAL_DEFAULT_STROKE_WIDTH: number = 8;
export const LINE_SMALL_DEFAULT_STROKE_WIDTH: number = 6;
export const LINE_DEFAULT_WIDTH: number = 0;
export const CIRCLE_NORMAL_ICON_STROKE_WIDTH: number = 3;
export const CIRCLE_SMALL_ICON_STROKE_WIDTH: number = 2;
export const LINE_ICON_STROKE_WIDTH: number = 1;

export const MAX_DEFAULT: number = 100;
export const VALUE_DEFAULT: number = 0;
export const TYPE_DEFAULT: Type = "line";
export const SIZE_DEFAULT: Size = "normal";
export const STATUS_DEFAULT: Status = "normal";
export const SHOW_INFO_DEFAULT: boolean = true;


text:
import { AbstractControl, ValidatorFn } from '@angular/forms';
import { LOCALE_I18N } from '../../i18n/i18n.service';

import { ReverseFormatDate } from '../../core/helper/reverseformatdate';
import { TlLeftPadPipe } from '../../internals/pipes/leftpad.pipe';

let dateExpressFormat;

export function DateValidator( formatDate, isoDate ): ValidatorFn {
  dateExpressFormat = formatDate;
  return ( c: AbstractControl ) => {

    if (!c.value) {
      return null;
    }

    if ( !stringUnmasked( c ) && c.touched ) {
      return { date: LOCALE_I18N.Validators.invalidDatePattern + ' [ ' + dateExpressFormat.toUpperCase() + ' ]' };
    }

    if ( (stringUnmasked( c ).length) !== dateExpressFormat.length && !isoDate ) {
      return { date: LOCALE_I18N.Validators.invalidDatePattern + ' [ ' + dateExpressFormat.toUpperCase() + ' ]' };
    }

    const formattedDate = ReverseFormatDate(stringUnmasked(c), dateExpressFormat);
    const date = new Date( formattedDate['year'] + '-' + formattedDate['month'] + '-' + formattedDate['day'] );

    if ( date.toDateString() === 'Invalid Date' ) {
      return { date: LOCALE_I18N.Validators.invalidDatePattern +  ' [ ' + dateExpressFormat.toUpperCase() + ' ]' };
    }

    return null;
  };
}

function stringUnmasked( c ) {
  return String( c.value ).replace( /(\|-|_|\(|\)|:|\+)/gi, '' );
}


text:
"""
Python class to map data types from XSD schema as accurately as possible.

We need to define custom data types because built-in Python types sometimes don't match definitions for XSD.

For example xsd.Date might contain a timezone reference but that is not allowed for datetime.date.
"""

from datetime import date

class XSDDate:
    """
    Represents the value of a xsd.date.

    Please note that dates in an XML schema can have time zone information attached (unlike Python's datetime.date).
    Also the schema spec supports "negative" dates (B.C.) and dates with years > 10000.

    Currently this class only supports dates representable by Python's datetime.date (with an optional time zone
    attached) but you should not assume that this will be true forever (see LIMITATIONS.md for further information).
    """

    def __init__(self, year, month, day, tzinfo=None):
        self.year = year
        self.month = month
        self.day = day
        self.tzinfo = tzinfo
        # simplistic validation that the provided date is actually valid
        self.as_datetime_date()

    @classmethod
    def from_datetime_date(cls, dt_date):
        return XSDDate(dt_date.year, dt_date.month, dt_date.day, tzinfo=None)

    def strftime(self, format_):
        """
        Usual strftime as implemented on datetime.date (thus without time zone support).

        Currently does not support time zones it should be used with care and probably treated as INTERNAL API.
        """
        return self.as_datetime_date().strftime(format_)

    def as_datetime_date(self):
        """
        Return a datetime.date instance which represents the same date as this instance.

        (Silently ignores the time zone information if present).
        Raises a ValueError if the date is not representable by datetime.date.
        """
        return date(self.year, self.month, self.day)

    def __eq__(self, other):
        return all(
            hasattr(other, key) and getattr(self, key) == getattr(other, key)
            for key in ('year', 'month', 'day', 'tzinfo')
        )

    def __repr__(self):
        return f'XSDDate({self.year!r}, {self.month!r}, {self.day!r}, tzinfo={self.tzinfo!r})'


text:
    <button href="#" data-dismiss="modal" class="close">×</button>

Вспомнить пароль

Новый пароль отправлен на ваш e-mail!

      <form class="remember-form form form-horizontal">

          E-mail

            <input type="text" value="[%= email %]" placeholder="E-mail" class="remember-email input-text"/>

        <button type="submit" class="btn btn-primary btn-block">Отправить</button>
      </form>


text:
package products;

/**
 * Class that represents a product without any price history
 *
 * @author Rui Grand�o  - ei11010@fe.up.pt
 * @author Andr� Silva - ei12133@fe.up.pt
 *
 */
public class Product {
    public static String[] PRODUCT_NAMES = { "MONITOR", "KEYBOARD", "MOUSE", "MOUSEPAD", "SMARTPHONE", "LAPTOP", "HEADSET", "CHAIR", "MICROPHONE", "DESKTOP"};
    ////////////////////
    // Private Fields //
    ////////////////////
    private Integer ID;
    private String name;
    private String desc;
    private String currentBidder;

    private double startingPrice;
    private double currentPrice;

    //////////////////
    // Constructors //
    //////////////////
    public Product (Integer ID, String name, double startingPrice){
        this.ID = ID;
        this.name = name;
        this.startingPrice = startingPrice;
        this.currentPrice = startingPrice;
        this.currentBidder = "";
    }

    public Product (Integer ID, String name, double startingPrice, String desc){
        this(ID, name, startingPrice);
        this.desc = desc;
    }

    public Product (Integer ID, String name){
        this(ID, name, 0.0);
        this.currentPrice = 0;
        this.desc = "Wishlist Product";
    }

    /////////////////////////
    // Getters and Setters //
    /////////////////////////
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getDesc() { return desc; }
    public void setDesc(String desc) { this.desc = desc; }

    public double getStartingPrice() { return startingPrice; }
    public void setStartingPrice(double startingPrice) { this.startingPrice = startingPrice; }

    public double getCurrentPrice() { return currentPrice; }
    public void setCurrentPrice(double currentPrice) { this.currentPrice = currentPrice; }

    public Integer getID() { return ID; }

    public String getCurrentBidder() { return currentBidder; }
    public void setCurrentBidder(String currentBidder) { this.currentBidder = currentBidder; }
}


text:
/* aes_keyschedule.h */
/*
 This file is part of the AVR-Crypto-Lib.
 Copyright (C) 2006-2015 Daniel Otte (bg@nerilex.org)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * \file     aes_keyschedule.h
 * \email    bg@nerilex.org
 * \author   Daniel Otte
 * \date     2008-12-30
 * \license  GPLv3 or later
 * \ingroup  AES
 */

#ifndef AES_KEYSCHEDULE_H_
#define AES_KEYSCHEDULE_H_

#include "aes_types.h"
/**
 * \brief initialize the keyschedule
 *
 * This function computes the keyschedule from a given key with a given length
 * and stores it in the context variable
 * \param key       pointer to the key material
 * \param keysize_b length of the key in bits (valid are 128, 192 and 256)
 * \param ctx       pointer to the context where the keyschedule should be stored
 */
void aes_init(const void *key, uint16_t keysize_b, aes_genctx_t *ctx);

/**
 * \brief initialize the keyschedule for 128 bit key
 *
 * This function computes the keyschedule from a given 128 bit key
 * and stores it in the context variable
 * \param key       pointer to the key material
 * \param ctx       pointer to the context where the keyschedule should be stored
 */
void aes128_init(const void *key, aes128_ctx_t *ctx);

/**
 * \brief initialize the keyschedule for 192 bit key
 *
 * This function computes the keyschedule from a given 192 bit key
 * and stores it in the context variable
 * \param key       pointer to the key material
 * \param ctx       pointer to the context where the keyschedule should be stored
 */
void aes192_init(const void *key, aes192_ctx_t *ctx);

/**
 * \brief initialize the keyschedule for 256 bit key
 *
 * This function computes the keyschedule from a given 256 bit key
 * and stores it in the context variable
 * \param key       pointer to the key material
 * \param ctx       pointer to the context where the keyschedule should be stored
 */
void aes256_init(const void *key, aes256_ctx_t *ctx);

#endif /* AES_KEYSCHEDULE_H_ */


text:
// This package is generated by client-gen with the default arguments.

// Package fake has the automatically generated clients.
package fake


text:
/*
 */

'use strict';

var util = require('util');

/**
 * @class
 * Initializes a new instance of the UsageListResult class.
 * @constructor
 * The List Usages operation response.
 *
 */
function UsageListResult() {
}

util.inherits(UsageListResult, Array);

/**
 * Defines the metadata of UsageListResult
 *
 * @returns {object} metadata of UsageListResult
 *
 */
UsageListResult.prototype.mapper = function () {
  return {
    required: false,
    serializedName: 'UsageListResult',
    type: {
      name: 'Composite',
      className: 'UsageListResult',
      modelProperties: {
        value: {
          required: false,
          serializedName: '',
          type: {
            name: 'Sequence',
            element: {
                required: false,
                serializedName: 'UsageElementType',
                type: {
                  name: 'Composite',
                  className: 'Usage'
                }
            }
          }
        }
      }
    }
  };
};

module.exports = UsageListResult;


text:
package org.apache.karaf.tooling.commands;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Command;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.xbean.finder.ClassFinder;

/**
 * Generates help documentation for Karaf commands
 */
@Mojo(name = "commands-generate-help", defaultPhase = LifecyclePhase.GENERATE_RESOURCES,
        requiresDependencyResolution = ResolutionScope.RUNTIME, inheritByDefault = false, threadSafe = true)
public class GenerateHelpMojo extends AbstractMojo {

    /**
     * The output folder
     */
    @Parameter(defaultValue = "${project.build.directory}/docbkx/sources")
    protected File targetFolder;

    /**
     * The output format
     */
    @Parameter(defaultValue = "docbx")
    protected String format;

    /**
     * The classloader to use for loading the commands.
     * Can be "project" or "plugin"
     */
    @Parameter(defaultValue = "project")
    protected String classLoader;

    /**
     * Includes the --help command output in the generated documentation
     */
    @Parameter(defaultValue = "true")
    protected boolean includeHelpOption;

    /**
     * The maven project.
     */
    @Parameter(defaultValue = "${project}")
    protected MavenProject project;

    private static final String FORMAT_CONF = "conf";
    private static final String FORMAT_DOCBX = "docbx";
    private static final String FORMAT_ASCIIDOC = "asciidoc";

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            if (!FORMAT_DOCBX.equals(format) && !FORMAT_CONF.equals(format) && !FORMAT_ASCIIDOC.equals(format)) {
                throw new MojoFailureException("Unsupported format: " + format + ". Supported formats are: asciidoc, docbx, or conf.");
            }
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }

            ClassFinder finder = createFinder(classLoader);
            List<Class<?>> classes = finder.findAnnotatedClasses(Command.class);
            if (classes.isEmpty()) {
                throw new MojoFailureException("No command found");
            }

            CommandHelpPrinter helpPrinter = null;
            if (FORMAT_ASCIIDOC.equals(format)) {
                helpPrinter = new AsciiDoctorCommandHelpPrinter();
            }
            if (FORMAT_CONF.equals(format)) {
                helpPrinter = new UserConfCommandHelpPrinter();
            }
            if (FORMAT_DOCBX.equals(format)) {
                helpPrinter = new DocBookCommandHelpPrinter();
            }

            Map<String, Set<String>> commands = new TreeMap<>();

            String commandSuffix = null;
            if (FORMAT_ASCIIDOC.equals(format)) {
                commandSuffix = "adoc";
            }
            if (FORMAT_CONF.equals(format)) {
                commandSuffix = "conf";
            }
            if (FORMAT_DOCBX.equals(format)) {
                commandSuffix = "xml";
            }
            for (Class<?> clazz : classes) {
                try {
                    Action action = (Action) clazz.newInstance();
                    Command cmd = clazz.getAnnotation(Command.class);

                    // skip the *-help command
                    if (cmd.scope().equals("*")) continue;

                    File output = new File(targetFolder, cmd.scope() + "-" + cmd.name() + "." + commandSuffix);
                    FileOutputStream outStream = new FileOutputStream(output);
                    PrintStream out = new PrintStream(outStream);
                    helpPrinter.printHelp(action, out, includeHelpOption);
                    out.close();
                    outStream.close();

                    commands.computeIfAbsent(cmd.scope(), k -> new TreeSet<>()).add(cmd.name());
                    getLog().info("Found command: " + cmd.scope() + ":" + cmd.name());
                } catch (Exception e) {
                    getLog().warn("Unable to write help for " + clazz.getName(), e);
                }
            }

            String overViewSuffix = null;
            if (FORMAT_ASCIIDOC.equals(format)) {
                overViewSuffix = "adoc";
            }
            if (FORMAT_CONF.equals(format)) {
                overViewSuffix = "conf";
            }
            if (FORMAT_DOCBX.equals(format)) {
                overViewSuffix = "xml";
            }
            PrintStream writer = new PrintStream(new FileOutputStream(new File(targetFolder, "commands." + overViewSuffix)));
            helpPrinter.printOverview(commands, writer);
            writer.close();
        } catch (Exception e) {
            throw new MojoExecutionException("Error building commands help", e);
        }
    }

    private ClassFinder createFinder(String classloaderType) throws
            Exception {
        ClassFinder finder;
        if ("project".equals(classloaderType)) {
            List<URL> urls = new ArrayList<>();
            for (Object object : project.getCompileClasspathElements()) {
                String path = (String) object;
                urls.add(new File(path).toURI().toURL());
            }
            ClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
            finder = new ClassFinder(loader, urls);
        } else if ("plugin".equals(classLoader)) {
            finder = new ClassFinder(getClass().getClassLoader());
        } else {
            throw new MojoFailureException("classLoader attribute must be 'project' or 'plugin'");
        }
        return finder;
    }

}


text:
require 'jruby_cxf'
Dir.glob(File.dirname(File.absolute_path(__FILE__)) + '/examples/*', &method(:require))

describe CXF::WebServiceServlet do

  context WebServiceWithExposedMethodsHavingResponseWrapperNameSet do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithExposedMethodsHavingResponseWrapperNameSet.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with response wrapper elements named according to given response wrapper names" do
      wsdl['definitions']['types']['schema']['complexType'][1]['name'].should eq 'GiveAgeResponseWrapper'
      wsdl['definitions']['types']['schema']['complexType'][3]['name'].should eq 'SayHelloResponseWrapper'
    end

  end

  context WebServiceWithExposedMethodsHavingOutParameterNameSet do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithExposedMethodsHavingOutParameterNameSet.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with return value elements named according to given out parameter names" do
      wsdl['definitions']['types']['schema']['complexType'][1]['sequence']['element']['name'].should eq 'OutGiveAge'
      wsdl['definitions']['types']['schema']['complexType'][3]['sequence']['element']['name'].should eq 'OutSayHello'
    end

  end

  context WebServiceWithExposedMethodsHavingLabels do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithExposedMethodsHavingLabels.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL that has its operations name according to labels given" do
      wsdl['definitions']['binding']['operation'][0]['name'].should eq 'GiveAge'
      wsdl['definitions']['binding']['operation'][1]['name'].should eq 'SayHello'
    end

  end

  context WebServiceWithExposedMethods do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithExposedMethods.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with declared methods exposed" do
      wsdl['definitions']['types']['schema']['complexType'][0]['sequence']['element']['type'].should eq 'xsd:int'
      wsdl['definitions']['types']['schema']['complexType'][1]['sequence']['element']['type'].should eq 'xsd:int'
      wsdl['definitions']['types']['schema']['complexType'][2]['sequence']['element']['type'].should eq 'xsd:string'
      wsdl['definitions']['types']['schema']['complexType'][3]['sequence']['element']['type'].should eq 'xsd:string'
      wsdl['definitions']['binding']['operation'][0]['name'].should eq 'give_age'
      wsdl['definitions']['binding']['operation'][1]['name'].should eq 'say_hello'
    end
  end

  context WebServiceWithExposedMethods do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithExposedMethods.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with declared methods exposed" do
      wsdl['definitions']['types']['schema']['complexType'][0]['sequence']['element']['type'].should eq 'xsd:int'
      wsdl['definitions']['types']['schema']['complexType'][1]['sequence']['element']['type'].should eq 'xsd:int'
      wsdl['definitions']['types']['schema']['complexType'][2]['sequence']['element']['type'].should eq 'xsd:string'
      wsdl['definitions']['types']['schema']['complexType'][3]['sequence']['element']['type'].should eq 'xsd:string'
      wsdl['definitions']['binding']['operation'][0]['name'].should eq 'give_age'
      wsdl['definitions']['binding']['operation'][1]['name'].should eq 'say_hello'
    end
  end

   context WebServiceWithRequiredProperty do
      subject(:wsdl) { @web_service.wsdl }

      before(:all) do
        @web_service = WebServiceWithRequiredProperty.new
        @web_service.publish
      end

      after(:all) do
        @web_service.teardown
      end

      it "gives a WSDL with non-required members having minOccurs set to 0" do
        wsdl['definitions']['types']['schema'][0]['complexType']['sequence']['element'][2]['minOccurs'].should eq '0'
      end

      it "gives a WSDL with required members having no minOccurs" do
        wsdl['definitions']['types']['schema'][0]['complexType']['sequence']['element'][0]['minOccurs'].should eq nil
        wsdl['definitions']['types']['schema'][0]['complexType']['sequence']['element'][1]['minOccurs'].should eq nil
      end
    end

  context WebServiceWithServiceNameSet do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithServiceNameSet.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with the configured service name" do
      wsdl['definitions']['service']['name'].should eq 'FooService'
    end
  end

  context WebServiceWithEndpointNameSet do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithEndpointNameSet.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with the port name matching the configured endpoint name" do
      wsdl['definitions']['service']['port']['name'].should eq 'FooPort'
    end
  end

  context WebServiceWithServiceNamespaceSet do
    subject(:wsdl) { @web_service.wsdl }

    before(:all) do
      @web_service = WebServiceWithServiceNamespaceSet.new
      @web_service.publish
    end

    after(:all) do
      @web_service.teardown
    end

    it "gives a WSDL with the service target namespace matching the configured service namespace" do
      wsdl['definitions']['targetNamespace'].should eq 'http://jruby-cxf.org'
    end
  end

end


text:
import { Enumerable } from "../enumerable_";
import { keySelector, Operator } from "../common/types";
import { wrapInIterable, wrapInThunk, wrapInThunkIfOnlyFirstArgumentIsIterable } from "../common/wrap";

function _union<T>(source: Iterable<T>, source2: Iterable<T>, keySelector?: keySelector<T, any>) {
    return wrapInIterable(function* () {
        if (typeof keySelector === "undefined") {
            keySelector = item => item;
        }
        var set = new Set<any>();
        var key;
        for (var item of source) {
            key = keySelector(item);
            if (!set.has(key)) {
                set.add(key);
                yield item;
            }
        }
        for (var item of source2) {
            key = keySelector(item);
            if (!set.has(key)) {
                set.add(key);
                yield item;
            }
        }
    });
}

export function union<T>(source: Iterable<T>, source2: Iterable<T>, keySelector?: keySelector<T, any>): Iterable<T>;
export function union<T>(source2: Iterable<T>, keySelector?: keySelector<T, any>): Operator<T, T>;
export function union() {
    return wrapInThunkIfOnlyFirstArgumentIsIterable(arguments, _union);
}

declare module '../enumerable_' {
    interface Enumerable<T> {
        union(source2: Iterable<T>, keySelector?: keySelector<T, any>): Enumerable<T>;
    }
}
Enumerable.prototype.union = function <T>(this: Enumerable<T>, source2: Iterable<T>, keySelector?: keySelector<T, any>): Enumerable<T> {
    return new Enumerable<T>(_union<T>(this, source2, keySelector));
};


text:
.hamburger-inner, .hamburger-inner::before, .hamburger-inner::after {
  background-color: white; }

.hamburger-li li {
  background-color: #c62828; }
.hamburger-li li:hover {
  background-color: #b71c1c; }


text:
package com.outbrain.aletheia.tutorial;

import com.outbrain.aletheia.datum.DatumKeySelector;
import com.outbrain.aletheia.datum.DatumType;

import org.joda.time.DateTime;
import org.joda.time.Instant;

@DatumType(datumTypeId = "my_datum_id", timestampExtractor = MyDatum.TimeSelector.class)
public class MyDatum {

  public static class TimeSelector implements DatumType.TimestampSelector<MyDatum> {
    @Override
    public DateTime extractDatumDateTime(final MyDatum domainObject) {
      return domainObject.getTimestamp().toDateTime();
    }
  }

  public static class MyKeySelector implements DatumKeySelector<MyDatum> {
    @Override
    public String getDatumKey(MyDatum domainObject) {
      return domainObject.getInfo();
    }
  }

  private Instant timestamp;
  private String info;

  MyDatum() {
  }

  public MyDatum(final Instant timestamp, final String info) {
    this.timestamp = timestamp;
    this.info = info;
  }

  public Instant getTimestamp() {
    return timestamp;
  }

  public String getInfo() {
    return info;
  }

  @Override
  public String toString() {
    return "MyDatum{" +
        "timestamp=" + timestamp +
        ", info='" + info + '\'' +
        '}';
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="format-detection" content="telephone=no" />
  <title>Control Gimnasio - Bienvenido</title>

                                    The introduction of your message preview goes here. Try to make it short.

Control Gimnasio

30 DÍAS GRATIS

                      Entrar

30 días gratis

Ahora puedes usar Control Gimnasio durante 30 días de prueba gratis. Cuando acabe tu período de prueba podrás seguir usando Control Gimnasio llamando al +505 7669 8050 o escribiendo a info@dak42.com

Escritorio y teléfonos inteligentes

Desde su computadora, tablet o teléfono podrá ver estadísticas de visita, conozca los días y horas más concurridos.

MODERNO

Una aplicación moderna con la que puede administrar su gimnasio desde cualquier navegador, inviertiendo poco tiempo.

FÁCIL DE USAR

Nos enfocamos en la facilidad de uso, de esa forma puede invertir el tiempo dónde más importa, atendiendo a sus clientes y su gimnasio.

INTELIGENTE

Genere información útil, tiempos de más uso de sus instalaciones, clientes más frecuentes, historial de pagos y mucho más.

ACTUALIZACIONES

Nuestra aplicación está en constante avance, frecuentemente agregamos nuevas características las cuáles le costarán $0.

Copyright © 2015 Control Gimnasio. Todos los derechos reservados.


text:
"""
Test wiping of a bundle that does not have an embedded script (on API)
"""

import os
import sys
import repyhelper
repyhelper.translate_and_import('bundle.repy')

# We make a local copy of the test bundle so that we
# don't affect the execution of other tests
ORIGINAL_BUNDLE_FN = 'test_readonly.bundle.repy'
TEST_BUNDLE_FN = 'test.bundle.repy'

# This must be done in binary mode.  Otherwise, differences of filesize due to
# \r\n and \n on different OSes will cause the bundler to look for data at the
# wrong places.
_bundle_copy_file(ORIGINAL_BUNDLE_FN, TEST_BUNDLE_FN)

# Perform action
bundle_clear_bundle_from_file(TEST_BUNDLE_FN)

# Make sure the output is empty
# If something is printed, then UTF will flag it as an error
sys.stdout.write(open(TEST_BUNDLE_FN, 'rb').read())


text:
from django.core.urlresolvers import reverse
from django.test import TestCase

class ModelAdminTests(TestCase):
    def test_change_book(self):
        # adrian can change his book as its author
        self.assertTrue(self.client.login(username='adrian', password='secr3t'))
        response = self.client.get(reverse('admin:testapp_book_change', args=(1,)))
        self.assertEqual(response.status_code, 200)

        # martin can change adrian's book as an editor
        self.assertTrue(self.client.login(username='martin', password='secr3t'))
        response = self.client.get(reverse('admin:testapp_book_change', args=(1,)))
        self.assertEqual(response.status_code, 200)

    def test_delete_book(self):
        # martin can *not* delete adrian's book
        self.assertTrue(self.client.login(username='martin', password='secr3t'))
        response = self.client.get(reverse('admin:testapp_book_delete', args=(1,)))
        self.assertEqual(response.status_code, 403)

        # adrian can delete his book as its author
        self.assertTrue(self.client.login(username='adrian', password='secr3t'))
        response = self.client.get(reverse('admin:testapp_book_delete', args=(1,)))
        self.assertEqual(response.status_code, 200)


text:
namespace _04.Sort_Students
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class SortStudents
    {
        public static void Main()
        {
            string input = Console.ReadLine();
            List<List<string>> allStudents = new List<List<string>>();

            while (input != "END")
            {
                allStudents.Add(input.Split(' ').ToList());

                input = Console.ReadLine();
            }

            allStudents
                .OrderBy(n => n[1])
                .ThenByDescending(n => n[0])
                .ToList()
                .ForEach(s => Console.WriteLine($"{s[0]} {s[1]}"));
        }
    }
}


text:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^sample_index', views.sample_index, name='sample_index'),
    url(r'^login', views.user_login, name='login'),
    url(r'^logout', views.user_logout, name='logout'),
]


text:
angular.module("sim/ui/ActionBar.js", []).
    controller("ActionBar", ActionBar);

angular.module("sim/Simulation.js").
    directive("actionbar", function () {
      return {
        restrict: "E",
        scope: {
          actions: "=",
          player: "="
        },
        templateUrl: "ui/ActionBar.html"
      }
    });

function ActionBar($scope) {
  $scope.classes = function (action) {
    return {
      active: action.active(),
      disabled: !action.enabled()
    }
  };
}