text:
require 'spec_helper'
require 'tiny_server'

describe Chef::Knife::Ssh do

  before(:all) do
    @original_config = Chef::Config.hash_dup
    Chef::Knife::Ssh.load_deps
    Thin::Logging.silent = true
    @server = TinyServer::Manager.new
    @server.start
  end

  after(:all) do
    Chef::Config.configuration = @original_config
    @server.stop
  end

  describe "identity file" do
    context "when knife[:ssh_identity_file] is set" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/aws.rsa"
      end

      it "uses the ssh_identity_file" do
        @knife.run
        @knife.config[:identity_file].should == "~/.ssh/aws.rsa"
      end
    end

    context "when knife[:ssh_identity_file] is set and frozen" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/aws.rsa".freeze
      end

      it "uses the ssh_identity_file" do
        @knife.run
        @knife.config[:identity_file].should == "~/.ssh/aws.rsa"
      end
    end

    context "when -i is provided" do
      before do
        setup_knife(['-i ~/.ssh/aws.rsa', '*:*', 'uptime'])
        Chef::Config[:knife][:ssh_identity_file] = nil
      end

      it "should use the value on the command line" do
        @knife.run
        @knife.config[:identity_file].should == "~/.ssh/aws.rsa"
      end

      it "should override what is set in knife.rb" do
        Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/other.rsa"
        @knife.run
        @knife.config[:identity_file].should == "~/.ssh/aws.rsa"
      end
    end

    context "when knife[:ssh_identity_file] is not provided]" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_identity_file] = nil
      end

      it "uses the default" do
        @knife.run
        @knife.config[:identity_file].should == nil
      end
    end
  end

  describe "user" do
    context "when knife[:ssh_user] is set" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_user] = "ubuntu"
      end

      it "uses the ssh_user" do
        @knife.run
        @knife.config[:ssh_user].should == "ubuntu"
      end
    end

    context "when knife[:ssh_user] is set and frozen" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_user] = "ubuntu".freeze
      end

      it "uses the ssh_user" do
        @knife.run
        @knife.config[:ssh_user].should == "ubuntu"
      end
    end

    context "when -x is provided" do
      before do
        setup_knife(['-x ubuntu', '*:*', 'uptime'])
        Chef::Config[:knife][:ssh_user] = nil
      end

      it "should use the value on the command line" do
        @knife.run
        @knife.config[:ssh_user].should == "ubuntu"
      end

      it "should override what is set in knife.rb" do
        Chef::Config[:knife][:ssh_user] = "root"
        @knife.run
        @knife.config[:ssh_user].should == "ubuntu"
      end
    end

    context "when knife[:ssh_user] is not provided]" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_user] = nil
      end

      it "uses the default" do
        @knife.run
        @knife.config[:ssh_user].should == nil
      end
    end
  end

  describe "attribute" do
    context "when knife[:ssh_attribute] is set" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_attribute] = "ec2.public_hostname"
      end

      it "uses the ssh_attribute" do
        @knife.run
        @knife.config[:attribute].should == "ec2.public_hostname"
      end
    end

    context "when knife[:ssh_attribute] is not provided]" do
      before do
        setup_knife(['*:*', 'uptime'])
        Chef::Config[:knife][:ssh_attribute] = nil
      end

      it "uses the default" do
        @knife.run
        @knife.config[:attribute].should == "fqdn"
      end
    end

    context "when -a ec2.public_ipv4 is provided" do
      before do
        setup_knife(['-a ec2.public_hostname', '*:*', 'uptime'])
        Chef::Config[:knife][:ssh_attribute] = nil
      end

      it "should use the value on the command line" do
        @knife.run
        @knife.config[:attribute].should == "ec2.public_hostname"
      end

      it "should override what is set in knife.rb" do
        # This is the setting imported from knife.rb
        Chef::Config[:knife][:ssh_attribute] = "fqdn"
        # Then we run knife with the -a flag, which sets the above variable
        setup_knife(['-a ec2.public_hostname', '*:*', 'uptime'])
        @knife.run
        @knife.config[:attribute].should == "ec2.public_hostname"
      end
    end
  end

  def setup_knife(params=[])
    @knife = Chef::Knife::Ssh.new(params)
    @knife.stub!(:ssh_command).and_return { [] }
    @api = TinyServer::API.instance
    @api.clear

    Chef::Config[:node_name] = nil
    Chef::Config[:client_key] = nil
    Chef::Config[:chef_server_url] = 'http://localhost:9000'

    @api.get("/search/node?q=*:*&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=1000", 200) {
      %({"total":1, "start":0, "rows":[{"name":"i-xxxxxxxx", "json_class":"Chef::Node", "automatic":{"fqdn":"the.fqdn", "ec2":{"public_hostname":"the_public_hostname"}},"recipes":[]}]})
    }
  end

end


text:
package io.github.jsbd.common.serialization.bytebean;

/**
 * 标识接口
 */
public interface ByteBean {

}

redpajama_set_name: RedPajamaGithub


text:
package me.reminisce

import me.reminisce.analysis.DataTypes.{ItemType, ReactionType}
import me.reminisce.analysis.model.{ItemSummary, UserSummary}
import me.reminisce.database.MongoDBEntities.{AbstractReaction, FBFrom, FBPage, FBPageLike, FBPost, filterReaction}
import me.reminisce.fetching.config.GraphResponses.Friend

import scala.annotation.tailrec

package object analysis {

  case class AnalysisData(analysedPosts: List[FBPost], allPosts: List[FBPost], userLikedPages: List[FBPage],
                          allPages: List[FBPage], pageLikes: List[FBPageLike], friends: Set[Friend], notLikedPagesCount: Int,
                          userSummary: UserSummary, itemSummaries: List[ItemSummary])

  case class AnalysisResults(userSummary: UserSummary, itemsSummaries: List[ItemSummary])

  /**
    * Merge two Maps and sum the values of the shared keys
    *
    * @param m1 First Map
    * @param m2 Second Map
    * @return the merged Maps
    */
  def mapWithValuesSummed[K](m1: Map[K, Int], m2: Map[K, Int]): Map[K, Int] = {
    m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
  }

  /**
    * Add a new count to a map of items => count
    *
    * @param typeAndCount new count
    * @param oldMap       current counts
    * @tparam T the type of item being counted
    * @return the new map
    */
  def addTypeToMap[T](typeAndCount: (T, Int), oldMap: Map[T, Int]): Map[T, Int] = typeAndCount match {
    case (tpe, count) =>
      if (oldMap.contains(tpe)) {
        oldMap.updated(tpe, oldMap(tpe) + count)
      } else {
        oldMap.updated(tpe, count)
      }
  }

  /**
    * Adds new counts to a map of item => count
    *
    * @param typesAndCounts new counts
    * @param oldMap         current counts
    * @tparam T type of item counted
    * @return the new map
    */
  @tailrec
  def addTypesToMap[T](typesAndCounts: Iterable[(T, Int)], oldMap: Map[T, Int]): Map[T, Int] = {
    if (typesAndCounts.isEmpty) {
      oldMap
    } else {
      addTypesToMap(typesAndCounts.tail, addTypeToMap(typesAndCounts.head, oldMap))
    }
  }

  /**
    * Get item summary for user id and item id in a list of item summaries. Returns a default value if nothing is found
    *
    * @param userId         user to look for
    * @param itemId         item to look for
    * @param itemType       type of the item
    * @param itemsSummaries list of items summaries
    * @return found item summary
    */
  def getItemSummary(userId: String, itemId: String, itemType: ItemType, itemsSummaries: List[ItemSummary]): ItemSummary = {
    itemsSummaries.filter(is => is.userId == userId && is.itemId == itemId) match {
      case Nil =>
        ItemSummary(None, userId, itemId, itemType, Set(), 0)
      case head :: _ =>
        //Normally only one match is possible
        head
    }
  }

  /**
    * Returns the reaction type only if there are more than 3 of any other types of reaction
    * @param reactions all the reactions to consider
    * @param totalReactions the total number of reactions
    * @param reactionType the type of reaction
    * @tparam React any type that inherits from AbstractReaction
    * @return maybe the reaction type
    */
  def maybeReactionType[React <: AbstractReaction](reactions: Set[React], totalReactions: Int)
                                                  (reactionType: ReactionType): Option[ReactionType] = {
    val reactionCount = noDuplicatePerson(filterReaction(reactions, reactionType)).size
    if (totalReactions - reactionCount >= 3 && reactionCount > 0) {
      Some(reactionType)
    } else {
      None
    }
  }

  /**
    * Filters out the elements that are in the black list
    * @param reactions the considered reactions
    * @param blacklist the black list
    * @tparam React reaction type
    * @return new set of reactions
    */
  def applyBlacklist[React <: AbstractReaction](reactions: Set[React], blacklist: Set[FBFrom]): Set[React] = {
    reactions.filterNot(react => blacklist.contains(react.from))
  }

  /**
    * Keeps only one reaction per person. Warning: no guarantee which reaction it will be
    * @param reactions reactions to handle
    * @tparam React type of reaction
    * @return new list of reactions
    */
  def noDuplicatePerson[React <: AbstractReaction](reactions: Iterable[React]): Iterable[React] = {
    reactions.groupBy(_.from).flatMap { case (_, reacts) => reacts.headOption }
  }

}


text:
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup() {
    ofSetLogLevel(OF_LOG_SILENT);
    ofSetVerticalSync(true);
    ofSetFrameRate(30);
	//ofEnableSmoothing();
    ofBackground(255, 255, 255);

    //kinect
	kinect.init();
    // enable depth->video image calibration
    //    bool infraRed = true;
    //    bool colourVideo = false;
    //    bool texture = true;
    //	kinect.init(infraRed, colourVideo, texture);
    kinect.setRegistration(true);
	kinect.enableDepthNearValueWhite(true);
	kinect.open();

    // depth image stuff
    depthPreCrop.allocate(kinect.width, kinect.height);
    maskImage.allocate(kinect.width, kinect.height);

    //from memo
    depthOrig.allocate(kinect.width, kinect.height);
    depthProcessed.allocate(kinect.width, kinect.height);

    // RGB image stuff
    colorImageRGB.allocate(kinect.width, kinect.height);
    //greyIRSingleChannel.allocate(kinect.width, kinect.height);

    ofSetVerticalSync(true);
	ofSetFrameRate(30);

    ofSetVerticalSync(true);

	nonTimelineGUI.setup();
    //crop
    nonTimelineGUI.add(leftCrop.setup("Crop Left", 0.f, 0.f, 1.f));
    nonTimelineGUI.add(rightCrop.setup("Crop Right", 1.f, 0.f, 1.f));
    nonTimelineGUI.add(topCrop.setup("Crop Top", 0.f, 0.f, 1.f));
    nonTimelineGUI.add(bottomCrop.setup("Crop Bottom", 1.f, 0.f, 1.f));
    // depth
    nonTimelineGUI.add(invert.setup("Depth invert", false));
    nonTimelineGUI.add(mirror.setup("Depth mirror", true));
    nonTimelineGUI.add(preBlur.setup("Depth Pre blur", 1,0,20));
    nonTimelineGUI.add(bottomThreshold.setup("Depth Bottom threshold", 0,0,1));
    nonTimelineGUI.add(topThreshold.setup("Depth Top threshold", 1,0,1));
	nonTimelineGUI.add(erodeAmount.setup("Depth Erode amout",1,0,10));
	nonTimelineGUI.add(dilateAmount.setup("Depth Dilate amount", 1,0,10));
    nonTimelineGUI.add(dilateBeforeErode.setup("Depth Dilate before erode", false));
    // contours
    nonTimelineGUI.add(maxNumBlobs.setup("Contours max number of blobs", 1,1,11));
    nonTimelineGUI.add(findHoles.setup("Contours find holes", false));
    nonTimelineGUI.add(useApproximation.setup("Contours use approximation", true));
    nonTimelineGUI.add(minBlobSize.setup("Contours min blob size", 0,0,1));
    nonTimelineGUI.add(maxBlobSize.setup("Contours max blob size", 1,0,1));
    // flow
    nonTimelineGUI.add(pyramidScale.setup("Pyramid scale", 0.5f, 0.f, 0.75f));
    nonTimelineGUI.add(pyramidLevels.setup("Pyramid levels", 3, 1, 100));
    nonTimelineGUI.add(windowSize.setup("Window size", 10, 1, 100));
    nonTimelineGUI.add(expansionAreaDoubleMe.setup("Half expansion area", 3,1,10));
    nonTimelineGUI.add(expansionSigma.setup("Expansion Sigma", 1.5f, 0.f, 10.f));
    nonTimelineGUI.add(flowFeedback.setup("Flow feedback", false));
    nonTimelineGUI.add(gaussianFiltering.setup("Gaussian filtering", false));

    nonTimelineGUI.loadFromFile("settings.xml");

    //showing
    bShowNonTimelineGUI = true;
    showMouse = true; //show the mouse by default
    showTimeline = true; //and timeline

    //scan for slitscans, so can populate gui correctly...
    //now scan the slit scan directory for all the files you can
	slitScanDirectory.listDir("bigMaps/");
	slitScanDirectory.sort(); // in linux the file system doesn't return file lists ordered in alphabetical order

	//allocate the vector to have as many ofImages as files
	if( slitScanDirectory.size() ){
		slitScans.assign(slitScanDirectory.size(), ofImage());
	}

    //ofxTimeLine
    ofxTimeline::removeCocoaMenusFromGlut("HAndLGreenpeace");
	timeline.setup();

    timeline.addVideoTrack("video", "movies/Greenpeace_Final.mov");
    timeline.addAudioTrack("audio", "audio/Greenpeace_Final.aiff");
    timeline.setDurationInSeconds(timeline.getAudioTrack("audio")->getDuration());
    timeline.addBangs("bangs");
	timeline.addFlags("scene");
    timeline.addCurves("slitscan", ofRange(0, slitScanDirectory.size()-1));
    timeline.addCurves("star", ofRange(2, 12));
    timeline.addCurves("offset", ofRange(0.f, 1.f));

	timeline.setPageName("Page 1");
	timeline.setCurrentPage(0);

	timeline.enableSnapToOtherKeyframes(true);
	timeline.setLoopType(OF_LOOP_NORMAL);

	ofAddListener(timeline.events().bangFired, this, &ofApp::bangFired);

    //slitscan

    ofImage distortionMap;
    distortionMap.loadImage("distortionBig.png");
    distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());

    //set up a slit scan with a maximum capacity of frames
    // in the distortion buffer
    slitScan.setup(timeline.getVideoPlayer("video")->getWidth(),timeline.getVideoPlayer("video")->getHeight(), 30);

    slitScan.setDelayMap(distortionMap);
    //blending means the edges between the scans are feathered
    slitScan.setBlending(true);
    //time delay is the deepest in history the delay can go
    //and width is the number of frames the distortion will encompass
    //note that the delay cannot be more than the total capacity
    slitScan.setTimeDelayAndWidth(30, 30);

	// you can now iterate through the files and load them into the ofImage vector
	for(int i = 0; i < (int)slitScanDirectory.size(); i++){
		slitScans[i].loadImage(slitScanDirectory.getPath(i));
	}

    //gui bits...
    slitScanSliderSlid(); // call it once to initialise
    prevSlitScan = 0;

    //sparkles
    someSparkles.setup(timeline.getVideoPlayer("video")->getWidth(),timeline.getVideoPlayer("video")->getHeight());

    //paint
    paintCanvas.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
    paintCanvasAsOfImage.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight(), OF_IMAGE_COLOR);

    paintCanvas.set(0); //black! so much black...

    //opptimising mirrors
    verticalMirrorImage.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
    horizontalMirrorImage.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
    kaleidoscopeMirrorImage.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());

    ofBackground(ofColor::black);

    //fur

    int iterationsPerLevel = 1;

    flowSolver.setup(kinect.getWidth()/2.f, kinect.getHeight()/2.f,
                     pyramidScale,
                     pyramidLevels,
                     windowSize,
                     iterationsPerLevel,
                     expansionAreaDoubleMe*2,
                     expansionSigma,
                     flowFeedback,
                     gaussianFiltering);

    //shatter
    theShatter.setup(timeline.getVideoPlayer("video")->getWidth(),timeline.getVideoPlayer("video")->getHeight());

    //spikey!
    theSpikey.setup(timeline.getVideoPlayer("video")->getWidth(),timeline.getVideoPlayer("video")->getHeight());

    //flocking!
    theParticles.setup(timeline.getVideoPlayer("video")->getWidth(),timeline.getVideoPlayer("video")->getHeight());
}

//--------------------------------------------------------------
void ofApp::exit(){
	kinect.close();
}

//--------------------------------------------------------------
void ofApp::slitScanSliderSlid(){
    ofImage distortionMap;
    int theCurrentSlitScan = timeline.getValue("slitscan");
    distortionMap.setFromPixels(slitScans[theCurrentSlitScan]);
    distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
    slitScan.setDelayMap(distortionMap);
}

//--------------------------------------------------------------
void ofApp::update() {
    //kinect
    kinect.update();

    // there is a new frame and we are connected
    if(kinect.isFrameNew()) {

        // load grayscale depth image from the kinect source
        depthPreCrop.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height);

        if(mirror){
            depthPreCrop.mirror(false, true);
        }

        maskGrayImage();

        depthPreCrop.flagImageChanged();

        // save original depth, and do some preprocessing

        depthOrig = depthPreCrop; //coopy cropped image into orig
        depthProcessed = depthOrig; //copy orig into processd
        colorImageRGB = kinect.getPixels(); //getting colour pixels
        //greyIRSingleChannel = kinect.getPixels(); //getting IR single channel pixels

        if(invert) depthProcessed.invert();
        if(mirror) {
            colorImageRGB.mirror(false, true);
            //greyIRSingleChannel.mirror(false, true);
        }

        depthOrig.flagImageChanged();
        depthProcessed.flagImageChanged();
        colorImageRGB.flagImageChanged();
        //greyIRSingleChannel.flagImageChanged();

        if(preBlur) cvSmooth(depthProcessed.getCvImage(), depthProcessed.getCvImage(), CV_BLUR , preBlur*2+1);
        if(topThreshold) cvThreshold(depthProcessed.getCvImage(), depthProcessed.getCvImage(), topThreshold * 255, 255, CV_THRESH_TRUNC);
        if(bottomThreshold) cvThreshold(depthProcessed.getCvImage(), depthProcessed.getCvImage(), bottomThreshold * 255, 255, CV_THRESH_TOZERO);
        if(dilateBeforeErode) {
            if(dilateAmount) cvDilate(depthProcessed.getCvImage(), depthProcessed.getCvImage(), 0, dilateAmount);
            if(erodeAmount) cvErode(depthProcessed.getCvImage(), depthProcessed.getCvImage(), 0, erodeAmount);
        } else {
            if(erodeAmount) cvErode(depthProcessed.getCvImage(), depthProcessed.getCvImage(), 0, erodeAmount);
            if(dilateAmount) cvDilate(depthProcessed.getCvImage(), depthProcessed.getCvImage(), 0, dilateAmount);
        }
        depthProcessed.flagImageChanged();

        // do adaptive threshold
        //	if(adaptiveThreshold) {
        //		cvAdaptiveThreshold(depthProcessed.getCvImage(), depthAdaptive.getCvImage(), 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 2*adaptiveBlockSize+1, adaptiveThreshold);
        //		depthAdaptive.invert();
        //		depthAdaptive.flagImageChanged();
        //	}

        // accumulate older depths to smooth out
        //	if(accumOldWeight) {
        //		cvAddWeighted(depthAccum.getCvImage(), accumOldWeight, depthProcessed.getCvImage(), accumNewWeight, 0, depthAccum.getCvImage());
        //		if(accumBlur) cvSmooth(depthAccum.getCvImage(), depthAccum.getCvImage(), CV_BLUR , accumBlur * 2 + 1);
        //		if(accumThreshold) cvThreshold(depthAccum.getCvImage(), depthAccum.getCvImage(), accumThreshold * 255, 255, CV_THRESH_TOZERO);
        //
        //		depthAccum.flagImageChanged();
        //
        //	} else {
        //		depthAccum = depthProcessed;
        //	}
        //

        // find contours
        depthContours.findContours(depthProcessed,
                                   minBlobSize * minBlobSize * depthProcessed.getWidth() * depthProcessed.getHeight(),
                                   maxBlobSize * maxBlobSize * depthProcessed.getWidth() * depthProcessed.getHeight(),
                                   maxNumBlobs, findHoles, useApproximation);

        //blobTracker.update(grayImage, -1, minArea, maxArea, nConsidered, 20, findHoles, true);

        //now do the diff bits for the PAINT mode
        ofxCvGrayscaleImage thresholdedDepthImageForPaint;
        thresholdedDepthImageForPaint.setFromPixels(depthProcessed.getPixelsRef());

        thresholdedDepthImageForPaint.resize(paintCanvas.getWidth(), paintCanvas.getHeight());
        thresholdedDepthImageForPaint.flagImageChanged();

        // loop through pixels
        //  - add new colour pixels into canvas
        unsigned char *canvasPixels = paintCanvas.getPixels();
        unsigned char *diffPixels = thresholdedDepthImageForPaint.getPixels();
        //        int r = colours[colourIndex].r;
        //        int g = colours[colourIndex].g;
        //        int b = colours[colourIndex].b;

        //int r = (int)((0.5f + ofNoise(ofGetElapsedTimef())*0.5f)*255.f);
        int r = 255;
        //int matchCount = 0;
        for(int i = 0; i < paintCanvas.width*paintCanvas.height; i++) {
            if(diffPixels[i]) {
                //paint in the new colour if
                canvasPixels[i*3] = r;
                canvasPixels[i*3+1] = r;
                canvasPixels[i*3+2] = r;
            }else{
                int greyScale = (int)(canvasPixels[i*3]*0.9f);

                canvasPixels[i*3] = greyScale;
                canvasPixels[i*3+1] = greyScale;
                canvasPixels[i*3+2] = greyScale;
            }
            //            if(canvasPixels[i*3]==r && canvasPixels[i*3+1]==g && canvasPixels[i*3+2]==b) {
            //                matchCount++;
            //            }
        }

        //        float totalCount = paintCanvas.width*paintCanvas.height;
        //        float proportionOfMatchedPixels = (float)matchCount/totalCount;

        paintCanvas.blur();
        paintCanvas.flagImageChanged();

        paintCanvasAsOfImage.setFromPixels(paintCanvas.getPixelsRef());
        paintCanvasAsOfImage.update();

        flowSolver.setPyramidScale(pyramidScale);
        flowSolver.setPyramidLevels(pyramidLevels);
        flowSolver.setWindowSize(windowSize);
        flowSolver.setExpansionArea(expansionAreaDoubleMe*2);
        flowSolver.setExpansionSigma(expansionSigma);
        flowSolver.setFlowFeedback(flowFeedback);
        flowSolver.setGaussianFiltering(gaussianFiltering);

        flowSolver.update(depthProcessed);
    }

    //Dirty filthy hack
    if(currentMode != SLITSCANBASIC){
        prevSlitScan = -1;
    }

    switch(currentMode){
        case BLANK: //image drawing mode
            break;
        case GUI: //GUI MODE
            break;
        case VIDEO:
            break;
        case VIDEOCIRCLES: //the film as circles
            break;
        case KINECTPOINTCLOUD: //draw the kinect camera depth cloud
            break;
        case SLITSCANBASIC: //slit scan the movie on the grey from the kinect depth grey
        {
            //check slit scan...
            int theCurrentSlitScan = timeline.getValue("slitscan");
            if(prevSlitScan != theCurrentSlitScan){
                slitScanSliderSlid(); //only update when you have to...
                prevSlitScan = theCurrentSlitScan;
            }

            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case SLITSCANKINECTDEPTHGREY: //slit scan the movie on the grey from the kinect depth grey
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                //kinect slitscan
                //depthPixels.setFromPixels(kinect.getDepthPixelsRef());
                depthPixels.setFromPixels(depthProcessed.getPixelsRef());
                depthPixels.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
                //            slitScanDepthGrey.setDelayMap(depthPixels);
                //            slitScanDepthGrey.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
                slitScan.setDelayMap(depthPixels);
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case SPARKLE: //sparkles on the slitscan
        {
            //update the sparkles come what may...
            someSparkles.update(&depthContours);
            someSparkles.draw(ofColor::white);
            //someSparkles.draw(timeline.getColor("colour"));

            ofImage distortionMap;
            distortionMap.allocate(someSparkles.theFBO.getWidth(), someSparkles.theFBO.getHeight(), OF_IMAGE_COLOR);

            someSparkles.theFBO.readToPixels(distortionMap.getPixelsRef());

            distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
            slitScan.setDelayMap(distortionMap);

            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case VERTICALMIRROR: //vertical mirror
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                verticalMirrorImage.setFromPixels(timeline.getVideoPlayer("video")->getPixels(), verticalMirrorImage.getWidth(), verticalMirrorImage.getHeight());

                verticalMirrorImage.updateTexture();
            }
        }
            break;
        case PAINT: //body painting diff
        {
            slitScan.setDelayMap(paintCanvasAsOfImage);
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case HORIZONTALMIRROR: //HORIZONTALMIRROR mirror
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                horizontalMirrorImage.setFromPixels(timeline.getVideoPlayer("video")->getPixels(), horizontalMirrorImage.getWidth(), horizontalMirrorImage.getHeight());

                horizontalMirrorImage.updateTexture();
            }
        }
            break;
        case KALEIDOSCOPE: //kaleidsocope
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                kaleidoscopeMirrorImage.setFromPixels(timeline.getVideoPlayer("video")->getPixels(), kaleidoscopeMirrorImage.getWidth(), kaleidoscopeMirrorImage.getHeight());

                kaleidoscopeMirrorImage.updateTexture();
            }
        }
            break;
        case COLOURFUR: //COLOURFUR
        {
        }
            break;
        case DEPTH: //DEPTH
        {
        }
            break;
        case SHATTER:
        {
            //update the shatter
            theShatter.update(&depthContours);
            theShatter.draw(ofColor::white);

            ofImage distortionMap;
            distortionMap.allocate(theShatter.theFBO.getWidth(), theShatter.theFBO.getHeight(), OF_IMAGE_COLOR);

            theShatter.theFBO.readToPixels(distortionMap.getPixelsRef());

            distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
            slitScan.setDelayMap(distortionMap);

            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case SELFSLITSCAN:
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                //self slitscan
                //                ofImage selfSlitScanDelayMap;
                //                selfSlitScanDelayMap.allocate(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight(), OF_IMAGE_COLOR);
                //                selfSlitScanDelayMap.setFromPixels(timeline.getVideoPlayer("video")->getPixelsRef());

                slitScan.setDelayMap(timeline.getVideoPlayer("video")->getPixelsRef());
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case SPIKYBLOBSLITSCAN:
        {
            //SPIKYBLOBSLITSCAN
            //update the spikes come what may...
            theSpikey.update(&depthContours);
            theSpikey.draw(ofColor::white);

            ofImage distortionMap;
            distortionMap.allocate(theSpikey.theFBO.getWidth(), theSpikey.theFBO.getHeight(), OF_IMAGE_COLOR);

            theSpikey.theFBO.readToPixels(distortionMap.getPixelsRef());

            distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
            slitScan.setDelayMap(distortionMap);

            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case MIRRORKALEIDOSCOPE: //MIRRORKALEIDOSCOPE mirror
        {
            if(timeline.getVideoPlayer("video")->isFrameNew()){
                verticalMirrorImage.setFromPixels(timeline.getVideoPlayer("video")->getPixels(), verticalMirrorImage.getWidth(), verticalMirrorImage.getHeight());

                verticalMirrorImage.updateTexture();

                kaleidoscopeMirrorImage.setFromPixels(timeline.getVideoPlayer("video")->getPixels(), kaleidoscopeMirrorImage.getWidth(), kaleidoscopeMirrorImage.getHeight());

                kaleidoscopeMirrorImage.updateTexture();
            }
        }
            break;
        case PARTICLES:
        {
            //PARTICLES
            theParticles.update(&depthContours);
            theParticles.draw(ofColor::white);

            ofImage distortionMap;
            distortionMap.allocate(theParticles.theFBO.getWidth(), theParticles.theFBO.getHeight(), OF_IMAGE_COLOR);

            theParticles.theFBO.readToPixels(distortionMap.getPixelsRef());

            distortionMap.resize(timeline.getVideoPlayer("video")->getWidth(), timeline.getVideoPlayer("video")->getHeight());
            slitScan.setDelayMap(distortionMap);

            if(timeline.getVideoPlayer("video")->isFrameNew()){
                slitScan.addImage(timeline.getVideoPlayer("video")->getPixelsRef());
            }
        }
            break;
        case WHITEFUR: //WHITEFUR, nowt
        {
        }
            break;
        default:
            break;
    }
}

void ofApp::maskGrayImage(){
    //make sure its black
    cvSet(maskImage.getCvImage(), cvScalar(0));

    float leftCropInPixels = leftCrop * kinect.getWidth();
    float rightCropInPixels = rightCrop * kinect.getWidth();
    float topCropInPixels = topCrop * kinect.getHeight();
    float bottomCropInPixels = bottomCrop * kinect.getHeight();

    CvPoint topLeft = cvPoint(leftCropInPixels, topCropInPixels);
    CvPoint bottomRight = cvPoint(rightCropInPixels,bottomCropInPixels);

    cvRectangle(maskImage.getCvImage(), topLeft, bottomRight, cvScalar(255), CV_FILLED);
    maskImage.flagImageChanged();
    //and it with the grayImage from the kinect, to only get the pixels that you want to look at, and then do blobs on those
    cvAnd(maskImage.getCvImage(), depthPreCrop.getCvImage(), depthPreCrop.getCvImage()); //can this be done "in place"?
    depthPreCrop.flagImageChanged();
}

//--------------------------------------------------------------
void ofApp::draw() {
	ofBackground(0, 0, 0);
	ofSetColor(255, 255, 255);

    switch (currentMode) {
        case BLANK: //nothing
            ofFill();
            ofSetColor(0);
            ofRect(0,0,ofGetWidth(),ofGetHeight()); //draw a black rectangle
            break;
        case GUI: //image drawing mode
        {
            ofFill();
            ofSetColor(0);
            ofRect(0,0,ofGetWidth(),ofGetHeight()); //draw a black rectangle

            int imageOffSet = 10;
            int imageWidth = 320;
            int imageHeight = 240;
            int imageX = imageOffSet;

            // draw everything
            ofSetColor(ofColor::white);
            ofEnableAlphaBlending();
            flowSolver.drawColored(imageWidth, imageHeight, 10, 3);
            ofDisableAlphaBlending();
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Flow", imageX, imageOffSet);
            ofSetColor(ofColor::white);
            colorImageRGB.draw(imageX, imageHeight+imageOffSet, imageWidth, imageHeight);
            //greyIRSingleChannel.draw(imageX, imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Kinect Video", imageX, imageHeight+imageOffSet);
            imageX += imageOffSet+imageWidth;
            ofSetColor(ofColor::white);
            kinect.drawDepth(imageX, imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Kinect", imageX, imageHeight+imageOffSet);
            imageX += imageOffSet+imageWidth;
            ofSetColor(ofColor::white);
            maskImage.draw(imageX,imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Mask", imageX, imageHeight+imageOffSet);
            imageX = imageOffSet;
            ofSetColor(ofColor::white);
            depthOrig.draw(imageX,imageHeight+imageOffSet+imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Original Depth", imageX, imageHeight+imageOffSet+imageHeight+imageOffSet);
            imageX += imageOffSet+imageWidth;
            ofSetColor(ofColor::white);
            depthProcessed.draw(imageX,imageHeight+imageOffSet+imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Depth Processed", imageX, imageHeight+imageOffSet+imageHeight+imageOffSet);
            imageX += imageOffSet+imageWidth;
            ofSetColor(ofColor::white);
            depthContours.draw(imageX, imageHeight+imageOffSet+imageHeight+imageOffSet, imageWidth, imageHeight);
            ofSetColor(ofColor::royalBlue);
            ofDrawBitmapString("Depth Contours", imageX, imageHeight+imageOffSet+imageHeight+imageOffSet);
            ofSetColor(ofColor::skyBlue);
            // draw instructions
            stringstream reportStream;
            reportStream
            << "f to fullscreen, g to show/hide timeline, m to show/hide mouse" << endl
            << "a/s to cycle through scenes" << endl
            << "Function	                                      Shortcut" << endl
            << "Cut Selection	                                  command+x" << endl
            << "Copy Selection	                                  command+c" << endl
            << "Paste Selection	                                  command+v" << endl
            << "Undo	                                          command+z" << endl
            << "Redo	                                          shift+command+z" << endl
            << "Select all keyframes in Focused track	          command+a" << endl
            << "Add all keyframes in Focused track to selection   command+shift+a" << endl
            << "Delete all selected keyframes	                  delete or backspace" << endl
            << "Nudge keyframes a little	                      arrow keys" << endl
            << "Nudge keyframes a little more	                  shift+arrow keys" << endl
            << "Expand Focused track	                          alt+e" << endl
            << "Collapse all tracks	                              alt+c" << endl
            << "Evenly distribute track sizes	                  alt+shift+c" << endl
            //                << "accel is: " << ofToString(kinect.getMksAccel().x, 2) << " / "
            //                << ofToString(kinect.getMksAccel().y, 2) << " / "
            //                << ofToString(kinect.getMksAccel().z, 2) << endl
            << ", fps: " << ofGetFrameRate() << endl
            << "press shift squerty 1-5 & 0 to change the led mode" << endl;
            ofDrawBitmapString(reportStream.str(),20,ofGetHeight()/2.f);

            stringstream m;
            m << "fps " << ofGetFrameRate() << endl
            << "pyramid scale: " << flowSolver.getPyramidScale() << " p/P" << endl
            << "pyramid levels: " << flowSolver.getPyramidLevels() << " l/L" << endl
            << "averaging window size: " << flowSolver.getWindowSize() << " w/W" << endl
            << "iterations per level: " << flowSolver.getIterationsPerLevel() << " i/I" << endl
            << "expansion area: " << flowSolver.getExpansionArea() << " a/A" << endl
            << "expansion sigma: " << flowSolver.getExpansionSigma() << " s/S" << endl
            << "flow feedback: " << flowSolver.getFlowFeedback() << " f/F" << endl
            << "gaussian filtering: " << flowSolver.getGaussianFiltering() << " g/G";

            ofDrawBitmapString(m.str(), 20+320, 20);

        }
            break;
        case VIDEO: //the film
            ofFill();
            ofSetColor(255);
            timeline.getVideoPlayer("video")->draw(0, 0, ofGetWidth(),ofGetHeight());
            break;
        case VIDEOCIRCLES: //the film as circles
        {
            ofFill();
            ofSetColor(0);
            ofRect(0,0,ofGetWidth(),ofGetHeight()); //draw a black rectangle
            if (timeline.getVideoPlayer("video")->isLoaded()) {
                unsigned char * pixels = timeline.getVideoPlayer("video")->getPixels();
                ofPixelsRef pixelsRef = timeline.getVideoPlayer("video")->getPixelsRef();

                // let's move through the "RGB(A)" char array
                // using the red pixel to control the size of a circle.
                //ofSetColor(timeline.getColor("colour"));
                ofSetColor(ofColor::lightBlue);

                float circleSpacing = 10.f;

                float widthRatio = ofGetWidth()/timeline.getVideoPlayer("video")->getWidth();
                float heightRatio = ofGetHeight()/timeline.getVideoPlayer("video")->getHeight();

                for(int i = 0; i < timeline.getVideoPlayer("video")->getWidth(); i+= 8){
                    for(int j = 0; j < timeline.getVideoPlayer("video")->getHeight(); j+= 8){
                        ofColor pixelColor = timeline.getVideoPlayer("video")->getPixelsRef().getColor(i, j);
                        int b = pixelColor.b;
                        float val = 1 - ((float)b / 255.0f); //more blue in the arctic!
                        ofCircle(i*widthRatio, j*heightRatio, circleSpacing * val);
                    }
                }
            }
        }
            break;
        case KINECTPOINTCLOUD: //draw the kinect camera depth cloud
            easyCam.begin();
            drawPointCloud();
            easyCam.end();
            break;
        case SLITSCANBASIC: //slit scan the movie on depth png
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());

            //white fur
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();

            break;
        case SLITSCANKINECTDEPTHGREY: //slit scan the movie on the grey from the kinect depth grey
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            //slitScanDepthGrey.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            break;
        case SPARKLE:
            //do some sparkles - used the slit scan to hold it....
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            //ofSetColor(255,255,255);
            //someSparkles.theFBO.draw(0, 0, ofGetWidth(), ofGetHeight());
            break;
        case VERTICALMIRROR:
        {
            bool usingNormTexCoords = ofGetUsingNormalizedTexCoords();

            if(!usingNormTexCoords) {
                ofEnableNormalizedTexCoords();
            }

            verticalMirrorImage.getTextureReference().bind();

            ofMesh mesh;
            mesh.clear();
            mesh.addVertex(ofVec3f(0, 0));
            mesh.addVertex(ofVec3f(0, ofGetHeight()));
            mesh.addVertex(ofVec3f(ofGetWidth()/2, 0));
            mesh.addVertex(ofVec3f(ofGetWidth()/2, ofGetHeight()));
            mesh.addVertex(ofVec3f(ofGetWidth(), 0));
            mesh.addVertex(ofVec3f(ofGetWidth(), ofGetHeight()));

            mesh.addTexCoord(ofVec2f(0.25, 0.0));
            mesh.addTexCoord(ofVec2f(0.25, 1.0));
            mesh.addTexCoord(ofVec2f(0.75, 0.0));
            mesh.addTexCoord(ofVec2f(0.75, 1.0));
            mesh.addTexCoord(ofVec2f(0.25, 0.0));
            mesh.addTexCoord(ofVec2f(0.25, 1.0));

            mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
            ofSetColor(ofColor::white);
            mesh.draw();

            verticalMirrorImage.getTextureReference().unbind();

            // pop normalized tex coords
            if(!usingNormTexCoords) {
                ofDisableNormalizedTexCoords();
            }

            //white fur
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
        case HORIZONTALMIRROR:
        {
            bool usingNormTexCoords = ofGetUsingNormalizedTexCoords();

            if(!usingNormTexCoords) {
                ofEnableNormalizedTexCoords();
            }

            horizontalMirrorImage.getTextureReference().bind();

            ofMesh mesh;
            mesh.clear();
            mesh.addVertex(ofVec3f(ofGetWidth(), 0));
            mesh.addVertex(ofVec3f(0, 0));
            mesh.addVertex(ofVec3f(ofGetWidth(), ofGetHeight()/2));
            mesh.addVertex(ofVec3f(0, ofGetHeight()/2));
            mesh.addVertex(ofVec3f(ofGetWidth(), ofGetHeight()));
            mesh.addVertex(ofVec3f(0,ofGetHeight()));

            mesh.addTexCoord(ofVec2f(1.0, 0.25));
            mesh.addTexCoord(ofVec2f(0.0, 0.25));
            mesh.addTexCoord(ofVec2f(1.0, 0.75));
            mesh.addTexCoord(ofVec2f(0.0, 0.75));
            mesh.addTexCoord(ofVec2f(1.0, 0.25));
            mesh.addTexCoord(ofVec2f(0.0, 0.25));

            mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
            ofSetColor(ofColor::white);
            mesh.draw();

            horizontalMirrorImage.getTextureReference().unbind();

            // pop normalized tex coords
            if(!usingNormTexCoords) {
                ofDisableNormalizedTexCoords();
            }

            //white fur
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
        case KALEIDOSCOPE:
        {
            bool usingNormTexCoords = ofGetUsingNormalizedTexCoords();

            if(!usingNormTexCoords) {
                ofEnableNormalizedTexCoords();
            }

            kaleidoscopeMirrorImage.getTextureReference().bind();

            int star = ((int)timeline.getValue("star")*2);//8; //get star from the timeline gui, but multiply by 2 to get to always even
            float offset = timeline.getValue("offset");//0.5f; // get offset from the timeline gui
            float angle = 360.f/star; //8 sides to start

			ofMesh mesh;

			ofVec3f vec(0,0,0);
			mesh.addVertex(vec);
			vec.x += ofGetHeight()/2;

			for(int i = 0; i < star; i++) {
				mesh.addVertex(vec);
				vec.rotate(angle, ofVec3f(0,0,1));
			}

			// close the loop
			mesh.addVertex(vec);

			// now work out the texcoords
			/*
			 __________________
			 |   \        /   |
			 |    \      /    |
			 |     \    /     |
			 |      \  /      |
			 |       \/       |
			 +----------------+

			 A v shape out of the centre of the camera texture
			 */

			float realOffset = 0.5;
			// normalized distance from the centre (half the width of the above 'V')
			float dist = ABS((float)kaleidoscopeMirrorImage.getHeight()*tan(ofDegToRad(angle)*0.5))/(float)kaleidoscopeMirrorImage.getHeight();

			// the realOffset is where the (normalized) middle of the 'V' is on the x-axis
			realOffset = ofMap(offset, 0, 1, dist, 1-dist);

			// this is the point at the bottom of the triangle - our centre for the triangle fan
			mesh.addTexCoord(ofVec2f(realOffset, 1));

			ofVec2f ta(realOffset-dist, 0);
			ofVec2f tb(realOffset+dist, 0);
			for(int i = 0; i <= star; i++) {
				if(i%2==0) {
					mesh.addTexCoord(ta);
				} else {
					mesh.addTexCoord(tb);
				}
			}

			glPushMatrix();
			glTranslatef(ofGetWidth()/2, ofGetHeight()/2, 0);
			mesh.setMode(OF_PRIMITIVE_TRIANGLE_FAN);
			mesh.draw();
			glPopMatrix();

            kaleidoscopeMirrorImage.getTextureReference().unbind();

            // pop normalized tex coords
            if(!usingNormTexCoords) {
                ofDisableNormalizedTexCoords();
            }

            //white fur
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
        case PAINT:
        {
            //do some paint - used the slit scan to hold it....
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());

            //paintCanvasAsOfImage.draw(0, 0, ofGetWidth(), ofGetHeight());
        }
            break;
        case COLOURFUR:
        {
            ofSetColor(ofColor::white);
            timeline.getVideoPlayer("video")->draw(0, 0, ofGetWidth(),ofGetHeight());
            ofEnableAlphaBlending();
            flowSolver.drawColored(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
        case DEPTH:
        {
            depthProcessed.draw(0,0,ofGetWidth(), ofGetHeight());
        }
            break;
        case SHATTER:
        {
            //do some shattering - used the slit scan to hold it....
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            //ofSetColor(255,255,255);
            //theShatter.theFBO.draw(0, 0, ofGetWidth(), ofGetHeight());
        }
            break;
        case SELFSLITSCAN:
        {
            //do some SELFSLITSCAN - used the slit scan to hold it....
            ofSetColor(255,255,255);
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
        }
            break;
        case SPIKYBLOBSLITSCAN:
        {
            //do some SPIKYBLOBSLITSCAN - used the slit scan to hold it....
            ofSetColor(255,255,255);
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            //theSpikey.theFBO.draw(0,0,ofGetWidth(), ofGetHeight());
        }
            break;
        case MIRRORKALEIDOSCOPE:
        {
            bool usingNormTexCoords = ofGetUsingNormalizedTexCoords();

            if(!usingNormTexCoords) {
                ofEnableNormalizedTexCoords();
            }

            verticalMirrorImage.getTextureReference().bind();

            ofMesh mirrorMesh;
            mirrorMesh.clear();
            mirrorMesh.addVertex(ofVec3f(0, 0));
            mirrorMesh.addVertex(ofVec3f(0, ofGetHeight()));
            mirrorMesh.addVertex(ofVec3f(ofGetWidth()/2, 0));
            mirrorMesh.addVertex(ofVec3f(ofGetWidth()/2, ofGetHeight()));
            mirrorMesh.addVertex(ofVec3f(ofGetWidth(), 0));
            mirrorMesh.addVertex(ofVec3f(ofGetWidth(), ofGetHeight()));

            mirrorMesh.addTexCoord(ofVec2f(0.25, 0.0));
            mirrorMesh.addTexCoord(ofVec2f(0.25, 1.0));
            mirrorMesh.addTexCoord(ofVec2f(0.75, 0.0));
            mirrorMesh.addTexCoord(ofVec2f(0.75, 1.0));
            mirrorMesh.addTexCoord(ofVec2f(0.25, 0.0));
            mirrorMesh.addTexCoord(ofVec2f(0.25, 1.0));

            mirrorMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
            ofSetColor(ofColor::white);
            mirrorMesh.draw();

            verticalMirrorImage.getTextureReference().unbind();

            kaleidoscopeMirrorImage.getTextureReference().bind();

            int star = ((int)timeline.getValue("star")*2);//8; //get star from the timeline gui, but multiply by 2 to get to always even
            float offset = timeline.getValue("offset");//0.5f; // get offset from the timeline gui
            float angle = 360.f/star; //8 sides to start

			ofMesh mesh;

			ofVec3f vec(0,0,0);
			mesh.addVertex(vec);
			vec.x += ofGetHeight()/2;

			for(int i = 0; i < star; i++) {
				mesh.addVertex(vec);
				vec.rotate(angle, ofVec3f(0,0,1));
			}

			// close the loop
			mesh.addVertex(vec);

			// now work out the texcoords
			/*
			 __________________
			 |   \        /   |
			 |    \      /    |
			 |     \    /     |
			 |      \  /      |
			 |       \/       |
			 +----------------+

			 A v shape out of the centre of the camera texture
			 */

			float realOffset = 0.5;
			// normalized distance from the centre (half the width of the above 'V')
			float dist = ABS((float)kaleidoscopeMirrorImage.getHeight()*tan(ofDegToRad(angle)*0.5))/(float)kaleidoscopeMirrorImage.getHeight();

			// the realOffset is where the (normalized) middle of the 'V' is on the x-axis
			realOffset = ofMap(offset, 0, 1, dist, 1-dist);

			// this is the point at the bottom of the triangle - our centre for the triangle fan
			mesh.addTexCoord(ofVec2f(realOffset, 1));

			ofVec2f ta(realOffset-dist, 0);
			ofVec2f tb(realOffset+dist, 0);
			for(int i = 0; i <= star; i++) {
				if(i%2==0) {
					mesh.addTexCoord(ta);
				} else {
					mesh.addTexCoord(tb);
				}
			}

			glPushMatrix();
			glTranslatef(ofGetWidth()/2, ofGetHeight()/2, 0);
			mesh.setMode(OF_PRIMITIVE_TRIANGLE_FAN);
			mesh.draw();
			glPopMatrix();

            kaleidoscopeMirrorImage.getTextureReference().unbind();

            // pop normalized tex coords
            if(!usingNormTexCoords) {
                ofDisableNormalizedTexCoords();
            }

            //white fur
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
        case PARTICLES:
        {
            //do some PARTICLES - used the slit scan to hold it....
            ofSetColor(255,255,255);
            slitScan.getOutputImage().draw(0, 0, ofGetWidth(), ofGetHeight());
            //theParticles.theFBO.draw(0,0,ofGetWidth(), ofGetHeight());
        }
            break;
        case WHITEFUR:
        {
            ofSetColor(ofColor::white);
            timeline.getVideoPlayer("video")->draw(0, 0, ofGetWidth(),ofGetHeight());
            ofEnableAlphaBlending();
            flowSolver.drawGrey(ofGetWidth(),ofGetHeight(), 10, 3);
            ofDisableAlphaBlending();
        }
            break;
    }

    if( bShowNonTimelineGUI ){
        nonTimelineGUI.draw();
    }

	if( timeline.getIsShowing() ){
        ofSetColor(255, 255, 255);

        //timeline
        timeline.draw();

        string modeString;
        modeString = "Mode is ";

        switch (currentMode) {
            case BLANK: //blank mode
                modeString += "BLANK";
                break;
            case GUI: //GUI drawing mode
                modeString += "GUI";
                break;
            case VIDEO: //the film
                modeString += "VIDEO";
                break;
            case VIDEOCIRCLES: //the film as circles
                modeString += "VIDEOCIRCLES";
                break;
            case KINECTPOINTCLOUD: //draw the kinect camera depth cloud
                modeString += "POINTCLOUD";
                break;
            case SLITSCANBASIC: //slit scan the movie on the grey from the kinect depth grey
                modeString += "SLITSCAN BASIC";
                break;
            case SLITSCANKINECTDEPTHGREY: //slit scan the movie on the grey from the kinect depth grey
                modeString += "SLITSCAN KINECT DEPTH GREY";
                break;
            case SPARKLE: //sparkles on the slitscan
                modeString += "SLITSCAN SPARKLES";
                break;
            case VERTICALMIRROR: //vertical mirror
                modeString += "VERTICAL MIRROR";
                break;
            case PAINT: //body painting diff
                modeString += "PAINT";
                break;
            case HORIZONTALMIRROR: //HORIZONTALMIRROR mirror
                modeString += "HORIZONTALMIRROR";
                break;
            case KALEIDOSCOPE: //KALEIDOSCOPE mirror
                modeString += "KALEIDOSCOPE";
                break;
            case COLOURFUR: //fur!
                modeString +="COLOURFUR";
                break;
            case DEPTH: // depth image
                modeString +="DEPTH";
                break;
            case SHATTER: //shattering blobs
                modeString +="SHATTER";
                break;
            case SELFSLITSCAN: //feeding video frame back into itself as the slitscan
                modeString += "SELFSLITSCAN";
                break;
            case SPIKYBLOBSLITSCAN: //making spikey blobs and putting them in the slitscan
                modeString += "SPIKYBLOBSLITSCAN";
                break;
            case MIRRORKALEIDOSCOPE: //making a kaleidescope with a mirrored background
                modeString += "MIRRORKALEIDOSCOPE";
                break;
            case PARTICLES: //making a partickles that seeks to centroids of the blobs
                modeString += "PARTICLES";
                break;
            case WHITEFUR: //making a white fur coat for people..
                modeString += "WHITEFUR";
                break;
        }

        ofSetColor(ofColor::red);
        ofDrawBitmapString(modeString,20,100);
	}
}

void ofApp::drawPointCloud(){
	int w = 640;
	int h = 480;
	ofMesh mesh;
	mesh.setMode(OF_PRIMITIVE_POINTS);
	int step = 2;
	for(int y = 0; y < h; y += step) {
		for(int x = 0; x < w; x += step) {
			if(kinect.getDistanceAt(x, y) > 0) {
				mesh.addColor(kinect.getColorAt(x,y));
				mesh.addVertex(kinect.getWorldCoordinateAt(x, y));
			}
		}
	}
	glPointSize(3);
	ofPushMatrix();
	// the projected points are 'upside down' and 'backwards'
	ofScale(1, -1, -1);
	ofTranslate(0, 0, -1000); // center the points a bit
	glEnable(GL_DEPTH_TEST);
	mesh.drawVertices();
	glDisable(GL_DEPTH_TEST);
	ofPopMatrix();
}

//--------------------------------------------------------------
void ofApp::keyPressed (int key) {

    switch (key) {
        case 'b':
            break;
        case '0':
            currentMode = BLANK;
            break;
        case '1':
            currentMode = GUI;
            break;
        case '2':
            currentMode = VIDEO;
            break;
        case '3':
            currentMode = VIDEOCIRCLES;
            break;
        case '4':
            currentMode = KINECTPOINTCLOUD;
            break;
        case '5':
            currentMode = VERTICALMIRROR;
            break;
        case '6':
            currentMode = HORIZONTALMIRROR;
            break;
        case '7':
            currentMode = SPARKLE;
            break;
        case '8':
            currentMode = SLITSCANBASIC;
            break;
        case '9':
            currentMode = SLITSCANKINECTDEPTHGREY;
            break;
        case '-':
            currentMode = KALEIDOSCOPE;
            break;
        case '=':
            currentMode = PAINT;
            break;
        case 'q':
            currentMode = COLOURFUR;
            break;
        case 'w':
            currentMode = DEPTH;
            break;
        case 'e':
            currentMode = SHATTER;
            break;
        case 'r':
            currentMode = SELFSLITSCAN;
            break;
        case 'y':
            currentMode = SPIKYBLOBSLITSCAN;
            break;
        case 'u':
            currentMode = MIRRORKALEIDOSCOPE;
            break;
        case 'i':
            currentMode = PARTICLES;
            break;
        case 'o':
            currentMode = WHITEFUR;
            break;
        case 'p':
            bShowNonTimelineGUI = !bShowNonTimelineGUI;
            break;
        case 'f':
            ofToggleFullscreen();
            break;
        case 'a': //used to be key left, but it interferes with ofxtimeline
        {
            currentMode = (GreenpeaceModes)((int)currentMode - 1);
            if(currentMode < 0){
                currentMode = GreenpeaceModes_MAX;//see .h file for stackoverflow justification
            }
            break;
        }
        case 's': //used to be key right, but it interferes with ofxtimeline
        {
            currentMode = (GreenpeaceModes)((int)currentMode + 1);
            if(currentMode > GreenpeaceModes_MAX){
                currentMode = (GreenpeaceModes)0;//see .h file for stackoverflow justification
            }
        }
            break;
            //		case OF_KEY_UP:
            //			angle++;
            //			if(angle>30) angle=30;
            //			kinect.setCameraTiltAngle(angle);
            //			break;
            //		case OF_KEY_DOWN:
            //			angle--;
            //			if(angle<-30) angle=-30;
            //			kinect.setCameraTiltAngle(angle);
            //			break;
            //		case 'p':
            //			bThreshWithOpenCV = !bThreshWithOpenCV;
            //			break;
            //		case'p':
            //			bDrawPointCloud = !bDrawPointCloud;
            //			break;
		case '!':
			kinect.setLed(ofxKinect::LED_GREEN);
			break;
		case '@':
			kinect.setLed(ofxKinect::LED_YELLOW);
			break;
		case '$':
			kinect.setLed(ofxKinect::LED_RED);
			break;
		case '%':
			kinect.setLed(ofxKinect::LED_BLINK_GREEN);
			break;
		case '^':
			kinect.setLed(ofxKinect::LED_BLINK_YELLOW_RED);
			break;
		case '&':
			kinect.setLed(ofxKinect::LED_OFF);
			break;
        case 't': //t for timeline
            if(showTimeline){
                showTimeline = false;
                timeline.hide();
            }else{
                showTimeline = true;
                timeline.show();
            }
            break;
        case 'm': //m for mouse
            if(showMouse){
                showMouse = false;
                ofHideCursor();
            }else{
                showMouse = true;
                ofShowCursor();
            }
            break;
        default:
            //nothing to see here, move along
            break;
    }
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}

//--------------------------------------------------------------
void ofApp::bangFired(ofxTLBangEventArgs& args){
	//cout << "bang fired!" << args.flag << endl;

    if(args.flag == "VIDEO"){
        currentMode = VIDEO;
    }

    if(args.flag == "SLITSCANBASIC"){
        currentMode = SLITSCANBASIC;
    }

    if (args.flag == "SPARKLE") {
        currentMode = SPARKLE;
    }

    if (args.flag == "VERTICALMIRROR"){
        currentMode = VERTICALMIRROR;
    }

    if (args.flag == "HORIZONTALMIRROR"){
        currentMode = HORIZONTALMIRROR;
    }

    if (args.flag == "PAINT"){
        currentMode = PAINT;
    }

    if (args.flag == "KALEIDOSCOPE"){
        currentMode = KALEIDOSCOPE;
    }

    if (args.flag == "COLOURFUR"){
        currentMode = COLOURFUR;
    }

    if(args.flag == "DEPTH"){
        currentMode = DEPTH;
    }

    if(args.flag == "SHATTER"){
        currentMode = SHATTER;
    }

    if(args.flag == "SELFSLITSCAN"){
        currentMode = SELFSLITSCAN;
    }

    if(args.flag == "SPIKYBLOBSLITSCAN"){
        currentMode = SPIKYBLOBSLITSCAN;
    }

    if(args.flag == "MIRRORKALEIDOSCOPE"){
        currentMode = MIRRORKALEIDOSCOPE;
    }

    if(args.flag == "PARTICLES"){
        currentMode = PARTICLES;
    }

    if(args.flag == "WHITEFUR"){
        currentMode = WHITEFUR;
    }
}


text:
define(['../internals/baseUniq', '../functions/createCallback'], function(baseUniq, createCallback) {

  /**
   * Creates a duplicate-value-free version of an array using strict equality
   * for comparisons, i.e. `===`. If the array is sorted, providing `true` for
   * `isSorted` will use a faster algorithm. If a callback is provided it will
   * be executed for each value in the array to generate the criterion by which
   * uniqueness is computed. The callback is bound to `thisArg` and invoked with
   * three arguments; (value, index, array).
   *
   * If a property name is provided for `callback` the created "_.pluck" style
   * callback will return the property value of the given element.
   *
   * If an object is provided for `callback` the created "_.where" style callback
   * will return `true` for elements that have the properties of the given object,
   * else `false`.
   *
   * @static
   * @memberOf _
   * @alias unique
   * @category Arrays
   * @param {Array} array The array to process.
   * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
   * @param {Function|Object|string} [callback] The function called per iteration.
   *  If a property name or object is provided it will be used to create a "_.pluck"
   *  or "_.where" style callback respectively.
   * @param {*} [thisArg] The `this` binding of `callback`.
   * @returns {Array} Returns the new duplicate-value-free array.
   * @example
   *
   * _.uniq([1, 2, 1, 3, 1]);
   * // => [1, 2, 3]
   *
   * // using `isSorted`
   * _.uniq([1, 1, 2, 2, 3], true);
   * // => [1, 2, 3]
   *
   * // using `callback`
   * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
   * // => ['A', 'b', 'C']
   *
   * // using `callback` with `thisArg`
   * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
   * // => [1, 2.5, 3]
   *
   * // using "_.pluck" callback shorthand
   * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
   * // => [{ 'x': 1 }, { 'x': 2 }]
   */
  function uniq(array, isSorted, callback, thisArg) {
    var length = array ? array.length : 0;
    if (!length) {
      return [];
    }
    // juggle arguments
    var type = typeof isSorted;
    if (type != 'boolean' && isSorted != null) {
      thisArg = callback;
      callback = isSorted;
      isSorted = false;

      // enables use as a callback for functions like `_.map`
      if ((type == 'number' || type == 'string') && thisArg && thisArg[callback] === array) {
        callback = null;
      }
    }
    if (callback != null) {
      callback = createCallback(callback, thisArg, 3);
    }
    return baseUniq(array, isSorted, callback);
  }

  return uniq;
});


text:
author: dinolupo
comments: true
date: 2006-09-23 14:35:45+00:00
layout: post
slug: replaceregexp-use-ant-to-modify-properties-in-configuration-files-xml-properties-etc-part-1-xml-tag-matching
title: 'Replaceregexp: use ANT to modify properties in configuration files (XML, properties,
  etc.) - Part 1 - XML tag matching'
wordpress_id: 22
categories:
- ANT
---

Enterprise web applications have multiple configuration files both XML and properties types. When you deploy your application you may need to change values like URL, IP, login, password, etc. in all of those files. My solution was to build a tool with ANT using "replaceregexp". But let's go with an example.
<!--more-->
We have a JBoss data source definition file into the deploy directory, this example has two db connections:

 {% highlight xml linenos %}
<datasources>

  <local-tx-datasource>
    <jndi-name>FirsConnectionDS</jndi-name>
    <connection-url>jdbc:mysql://192.168.1.2:3306/database1</connection-url>
    <driver-class>org.gjt.mm.mysql.Driver</driver-class>
    <user-name>root</user-name>
    <password>SamplePass123</password>
    <!-- all other properties are optional -->
    <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
    <!--pooling parameters-->
    <min-pool-size>5</min-pool-size>
    <max-pool-size>100</max-pool-size>
    <blocking-timeout-millis>5000</blocking-timeout-millis>
    <idle-timeout-minutes>15</idle-timeout-minutes>
  </local-tx-datasource>

  <local-tx-datasource>
    <jndi-name>SecondConnectionDS</jndi-name>
    <connection-url>jdbc:mysql://dbserver_name:3306/database2</connection-url>
    <driver-class>org.gjt.mm.mysql.Driver</driver-class>
    <user-name>root</user-name>
    <password>SamplePass123</password>
    <!-- all other properties are optional -->
    <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
    <!--pooling parameters-->
    <min-pool-size>5</min-pool-size>
    <max-pool-size>100</max-pool-size>
    <blocking-timeout-millis>5000</blocking-timeout-millis>
    <idle-timeout-minutes>15</idle-timeout-minutes>
  </local-tx-datasource>

<datasources>
{% endhighlight %}

The ant build.xml that permits to modify the connection-url, user-name and passwords is this:
(to explain the the regular expression which I used, note that I match the entire XML tag and it's content, and with the use of parenthesis I remember what to mantain and what to discard/substitute).

{% highlight xml linenos %}
<?xml version="1.0"?>
<project name="datasources_configuration" default="init" basedir=".">

    <!-- ************************************************************ -->
    <!--             Configuration properties                         -->
    <!-- ************************************************************ -->

    <property name="jboss" value="c:/jboss-3.2.6"/>
    <property name="srv" value="all"/>

    <property name="mysql_db_ip" value="192.168.1.10"/>
    <property name="mysql_db_port" value="3306"/>
    <property name="mysql_db_user" value="root_new"/>
    <property name="mysql_db_password" value="Password_new"/>

    <target name="init">
        <echo message="-------------------------------------------------------------------------" />
        <echo message="JBoss directory:             ${jboss}" />
        <echo message="JBoss configuration:         ${srv}" />
        <echo message="MySql server/port:           ${mysql_db_ip}/${mysql_db_port}" />
        <echo message="MySql user/password:         ${mysql_db_user}/${mysql_db_password}" />
        <echo message="-------------------------------------------------------------------------" />
    </target>

    <target name="all_services_db" depends="init">
        <description> All services Data Source configuration task </description>
        <replaceregexp byline="true">
            <regexp pattern="(Wconnection-urlWs*jdbc:mysql://)(.+)/((w+)WWconnection-urlW)"/>
            <substitution expression="1${mysql_db_ip}:${mysql_db_port}/3"/>
            <fileset dir="${jboss}/server/${srv}/deploy" casesensitive="no">
                <include name="standard-mysql-ds.xml"/>
            </fileset>
        </replaceregexp>

        <replaceregexp byline="true">
            <regexp pattern="(Wuser-nameWs*)(.+)(WWuser-nameW)"/>
          <substitution expression="1${mysql_db_user}3"/>
            <fileset dir="${jboss}/server/${srv}/deploy" casesensitive="no">
                <include name="standard-mysql-ds.xml"/>
            </fileset>
        </replaceregexp>
        <replaceregexp byline="true">
            <regexp pattern="(WpasswordWs*)(.*)(WWpasswordW)"/>
          <substitution expression="1${mysql_db_password}3"/>
            <fileset dir="${jboss}/server/${srv}/deploy" casesensitive="no">
                <include name="standard-mysql-ds.xml"/>
            </fileset>
        </replaceregexp>

    </target>

</project>
{% endhighlight %}

Only thing you have to do is to set your property at the top of the build.xml file and then run it with ANT.

See ya!


text:
package org.springframework.boot.actuate.autoconfigure.metrics.export.datadog;

import io.micrometer.core.instrument.Clock;
import io.micrometer.core.ipc.http.HttpUrlConnectionSender;
import io.micrometer.datadog.DatadogConfig;
import io.micrometer.datadog.DatadogMeterRegistry;

import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.ConditionalOnEnabledMetricsExport;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for exporting metrics to Datadog.
 *
 * @author Jon Schneider
 * @author Artsiom Yudovin
 * @since 2.0.0
 */
@AutoConfiguration(
		before = { CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class },
		after = MetricsAutoConfiguration.class)
@ConditionalOnBean(Clock.class)
@ConditionalOnClass(DatadogMeterRegistry.class)
@ConditionalOnEnabledMetricsExport("datadog")
@EnableConfigurationProperties(DatadogProperties.class)
public class DatadogMetricsExportAutoConfiguration {

	private final DatadogProperties properties;

	public DatadogMetricsExportAutoConfiguration(DatadogProperties properties) {
		this.properties = properties;
	}

	@Bean
	@ConditionalOnMissingBean
	public DatadogConfig datadogConfig() {
		return new DatadogPropertiesConfigAdapter(this.properties);
	}

	@Bean
	@ConditionalOnMissingBean
	public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig, Clock clock) {
		return DatadogMeterRegistry.builder(datadogConfig).clock(clock).httpClient(
				new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout()))
				.build();
	}

}


text:
(function(win, doc, el) {
	var vendors = ['ms', 'moz', 'webkit', 'o'];

	if(typeof(el.prototype.requestPointerLock) == "undefined") {
		for(var i = 0 ; i < vendors.length ; i++) {
			if(el.prototype[vendors[i] + "RequestPointerLock"]) {
				el.prototype.requestPointerLock = el.prototype[vendors[i] + "RequestPointerLock"];
				break;
			}
		}
	}

	if(typeof(doc.exitPointerLock) == "undefined") {
		for(var i = 0 ; i < vendors.length ; i++) {
			if(doc[vendors[i] + "ExitPointerLock"]) {
				doc.exitPointerLock = doc[vendors[i] + "ExitPointerLock"];
				break;
			}
		}
	}

	win.setPointerLockChangeEvent = function(element, callBack) {
		for(var i = 0 ; i < vendors.length ; i++) {
			element.addEventListener(vendors[i] + "pointerlockchange", function(event) {
				callBack(event);
			});
		}
	}

	win.readPointerLockMovement = function(event) {
		if(event.movementX) return [event.movementX, event.movementY];

		for(var i = 0 ; i < vendors.length ; i++) {
			var v = vendors[i];
			if(event[v + "MovementX"]) {
				return [event[v + "MovementX"], event[v + "MovementY"]];
			}
		}

		return [0, 0];
	}
})(window, document, Element);


text:
// Include gulp
var gulp = require('gulp'),

// Include plugins
    sass = require('gulp-sass'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    gulpif = require('gulp-if'),
    useref = require('gulp-useref'),
    cleanCss = require('gulp-clean-css'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create(),
    spa = require('browser-sync-spa'),
    connect = require('gulp-connect'),
    imagemin = require('gulp-imagemin'),
    ngAnnotate = require('gulp-ng-annotate');

var sassOptions = {
    errLogToConsole: true,
    outputStyle: 'expanded',
    noCache: true
};

//convert scss to css
gulp.task('styles', function () {
    gulp
        .src('./src/styles/**/*.sass')
        .pipe(sourcemaps.init())
        .pipe(sass(sassOptions).on('error', sass.logError))
        .pipe(autoprefixer())
        .pipe(sourcemaps.write('./maps/'))
        .pipe(gulp.dest('./src/assets/css/'))
        .pipe(browserSync.stream());
});

// Images
gulp.task('images', function () {
    return gulp.src('./src/assets/imgs/**/*')
        .pipe(imagemin())
        .pipe(gulp.dest('_dist/imgs/'));
});

// Fonts
gulp.task('fonts', function () {
    return gulp.src('./src/assets/fonts/*')
        .pipe(gulp.dest('_dist/fonts/'));
});

//modal
gulp.task('modal', function () {
    return gulp.src('./src/interno/*')
        .pipe(gulpif('*.js', uglify()))
        .pipe(gulp.dest('_dist/interno/'));
});

//build
gulp.task('build', ['fonts', 'styles', 'images', 'modal'], function () {
    return gulp.src([
        './src/**/*.html',
        '!./src/tests/**',
        '!./src/interno/',
        '!./node_modules/**',
        '!./bower_components/**',
        '!./_dist/**',
        './src/Web.config'
    ])
        .pipe(useref())
        // .pipe(gulpif('*.js', uglify()))
        .pipe(gulpif('*.css', cleanCss()))
        .pipe(gulp.dest('_dist'));
});

//serve build dir
gulp.task('serve-build', function () {
    connect.server({
        name: 'Serve Build Dir',
        root: '_dist',
        port: 8000,
        livereload: true
    });
});

// Static Server + watching sass/html files
gulp.task('serve', ['styles'], function () {
    browserSync.use(
        spa({
            selector: '[application]',
            history: {
                index: '/index.html'
            }
        })
    );

    browserSync.init({
        server: {
            baseDir: './src',
            routes: {
                '/bower_components': 'bower_components',
                '/node_modules': 'node_modules'
            }
        }
    });

    // gulp.watch('./src/**/*.sass', ['styles']);
    // gulp.watch('./src/**/*.html').on('change', browserSync.reload);
});

gulp.task('default', ['serve']);


text:
- [all_search](all_search.html)

More to come?...


text:
package org.apache.spark.sql.execution

import scala.collection.JavaConverters._

import org.apache.spark.internal.config.ConfigEntry
import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedAlias, UnresolvedAttribute, UnresolvedRelation, UnresolvedStar}
import org.apache.spark.sql.catalyst.catalog.{BucketSpec, CatalogStorageFormat, CatalogTable, CatalogTableType}
import org.apache.spark.sql.catalyst.expressions.{Ascending, AttributeReference, Concat, SortOrder}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.execution.command._
import org.apache.spark.sql.execution.datasources.{CreateTable, RefreshResource}
import org.apache.spark.sql.internal.{HiveSerDe, SQLConf, StaticSQLConf}
import org.apache.spark.sql.types.{IntegerType, LongType, StringType, StructType}

/**
 * Parser test cases for rules defined in [[SparkSqlParser]].
 *
 * See [[org.apache.spark.sql.catalyst.parser.PlanParserSuite]] for rules
 * defined in the Catalyst module.
 */
class SparkSqlParserSuite extends AnalysisTest {
  import org.apache.spark.sql.catalyst.dsl.expressions._

  val newConf = new SQLConf
  private lazy val parser = new SparkSqlParser(newConf)

  /**
   * Normalizes plans:
   * - CreateTable the createTime in tableDesc will replaced by -1L.
   */
  override def normalizePlan(plan: LogicalPlan): LogicalPlan = {
    plan match {
      case CreateTable(tableDesc, mode, query) =>
        val newTableDesc = tableDesc.copy(createTime = -1L)
        CreateTable(newTableDesc, mode, query)
      case _ => plan // Don't transform
    }
  }

  private def assertEqual(sqlCommand: String, plan: LogicalPlan): Unit = {
    val normalized1 = normalizePlan(parser.parsePlan(sqlCommand))
    val normalized2 = normalizePlan(plan)
    comparePlans(normalized1, normalized2)
  }

  private def intercept(sqlCommand: String, messages: String*): Unit =
    interceptParseException(parser.parsePlan)(sqlCommand, messages: _*)

  test("Checks if SET/RESET can parse all the configurations") {
    // Force to build static SQL configurations
    StaticSQLConf
    ConfigEntry.knownConfigs.values.asScala.foreach { config =>
      assertEqual(s"SET ${config.key}", SetCommand(Some(config.key -> None)))
      if (config.defaultValue.isDefined && config.defaultValueString != null) {
        assertEqual(s"SET ${config.key}=${config.defaultValueString}",
          SetCommand(Some(config.key -> Some(config.defaultValueString))))
      }
      assertEqual(s"RESET ${config.key}", ResetCommand(Some(config.key)))
    }
  }

  test("Report Error for invalid usage of SET command") {
    assertEqual("SET", SetCommand(None))
    assertEqual("SET -v", SetCommand(Some("-v", None)))
    assertEqual("SET spark.sql.key", SetCommand(Some("spark.sql.key" -> None)))
    assertEqual("SET  spark.sql.key   ", SetCommand(Some("spark.sql.key" -> None)))
    assertEqual("SET spark:sql:key=false", SetCommand(Some("spark:sql:key" -> Some("false"))))
    assertEqual("SET spark:sql:key=", SetCommand(Some("spark:sql:key" -> Some(""))))
    assertEqual("SET spark:sql:key=  ", SetCommand(Some("spark:sql:key" -> Some(""))))
    assertEqual("SET spark:sql:key=-1 ", SetCommand(Some("spark:sql:key" -> Some("-1"))))
    assertEqual("SET spark:sql:key = -1", SetCommand(Some("spark:sql:key" -> Some("-1"))))
    assertEqual("SET 1.2.key=value", SetCommand(Some("1.2.key" -> Some("value"))))
    assertEqual("SET spark.sql.3=4", SetCommand(Some("spark.sql.3" -> Some("4"))))
    assertEqual("SET 1:2:key=value", SetCommand(Some("1:2:key" -> Some("value"))))
    assertEqual("SET spark:sql:3=4", SetCommand(Some("spark:sql:3" -> Some("4"))))
    assertEqual("SET 5=6", SetCommand(Some("5" -> Some("6"))))
    assertEqual("SET spark:sql:key = va l u  e ",
      SetCommand(Some("spark:sql:key" -> Some("va l u  e"))))
    assertEqual("SET `spark.sql.    key`=value",
      SetCommand(Some("spark.sql.    key" -> Some("value"))))
    assertEqual("SET `spark.sql.    key`= v  a lu e ",
      SetCommand(Some("spark.sql.    key" -> Some("v  a lu e"))))
    assertEqual("SET `spark.sql.    key`=  -1",
      SetCommand(Some("spark.sql.    key" -> Some("-1"))))

    val expectedErrMsg = "Expected format is 'SET', 'SET key', or " +
      "'SET key=value'. If you want to include special characters in key, " +
      "please use quotes, e.g., SET `ke y`=value."
    intercept("SET spark.sql.key value", expectedErrMsg)
    intercept("SET spark.sql.key   'value'", expectedErrMsg)
    intercept("SET    spark.sql.key \"value\" ", expectedErrMsg)
    intercept("SET spark.sql.key value1 value2", expectedErrMsg)
    intercept("SET spark.   sql.key=value", expectedErrMsg)
    intercept("SET spark   :sql:key=value", expectedErrMsg)
    intercept("SET spark .  sql.key=value", expectedErrMsg)
    intercept("SET spark.sql.   key=value", expectedErrMsg)
    intercept("SET spark.sql   :key=value", expectedErrMsg)
    intercept("SET spark.sql .  key=value", expectedErrMsg)
  }

  test("Report Error for invalid usage of RESET command") {
    assertEqual("RESET", ResetCommand(None))
    assertEqual("RESET spark.sql.key", ResetCommand(Some("spark.sql.key")))
    assertEqual("RESET  spark.sql.key  ", ResetCommand(Some("spark.sql.key")))
    assertEqual("RESET 1.2.key ", ResetCommand(Some("1.2.key")))
    assertEqual("RESET spark.sql.3", ResetCommand(Some("spark.sql.3")))
    assertEqual("RESET 1:2:key ", ResetCommand(Some("1:2:key")))
    assertEqual("RESET spark:sql:3", ResetCommand(Some("spark:sql:3")))
    assertEqual("RESET `spark.sql.    key`", ResetCommand(Some("spark.sql.    key")))

    val expectedErrMsg = "Expected format is 'RESET' or 'RESET key'. " +
      "If you want to include special characters in key, " +
      "please use quotes, e.g., RESET `ke y`."
    intercept("RESET spark.sql.key1 key2", expectedErrMsg)
    intercept("RESET spark.  sql.key1 key2", expectedErrMsg)
    intercept("RESET spark.sql.key1 key2 key3", expectedErrMsg)
    intercept("RESET spark:   sql:key", expectedErrMsg)
    intercept("RESET spark   .sql.key", expectedErrMsg)
    intercept("RESET spark :  sql:key", expectedErrMsg)
    intercept("RESET spark.sql:   key", expectedErrMsg)
    intercept("RESET spark.sql   .key", expectedErrMsg)
    intercept("RESET spark.sql :  key", expectedErrMsg)
  }

  test("refresh resource") {
    assertEqual("REFRESH prefix_path", RefreshResource("prefix_path"))
    assertEqual("REFRESH /", RefreshResource("/"))
    assertEqual("REFRESH /path///a", RefreshResource("/path///a"))
    assertEqual("REFRESH pat1h/112/_1a", RefreshResource("pat1h/112/_1a"))
    assertEqual("REFRESH pat1h/112/_1a/a-1", RefreshResource("pat1h/112/_1a/a-1"))
    assertEqual("REFRESH path-with-dash", RefreshResource("path-with-dash"))
    assertEqual("REFRESH \'path with space\'", RefreshResource("path with space"))
    assertEqual("REFRESH \"path with space 2\"", RefreshResource("path with space 2"))
    intercept("REFRESH a b", "REFRESH statements cannot contain")
    intercept("REFRESH a\tb", "REFRESH statements cannot contain")
    intercept("REFRESH a\nb", "REFRESH statements cannot contain")
    intercept("REFRESH a\rb", "REFRESH statements cannot contain")
    intercept("REFRESH a\r\nb", "REFRESH statements cannot contain")
    intercept("REFRESH @ $a$", "REFRESH statements cannot contain")
    intercept("REFRESH  ", "Resource paths cannot be empty in REFRESH statements")
    intercept("REFRESH", "Resource paths cannot be empty in REFRESH statements")
  }

  private def createTableUsing(
      table: String,
      database: Option[String] = None,
      tableType: CatalogTableType = CatalogTableType.MANAGED,
      storage: CatalogStorageFormat = CatalogStorageFormat.empty,
      schema: StructType = new StructType,
      provider: Option[String] = Some("parquet"),
      partitionColumnNames: Seq[String] = Seq.empty,
      bucketSpec: Option[BucketSpec] = None,
      mode: SaveMode = SaveMode.ErrorIfExists,
      query: Option[LogicalPlan] = None): CreateTable = {
    CreateTable(
      CatalogTable(
        identifier = TableIdentifier(table, database),
        tableType = tableType,
        storage = storage,
        schema = schema,
        provider = provider,
        partitionColumnNames = partitionColumnNames,
        bucketSpec = bucketSpec
      ), mode, query
    )
  }

  private def createTable(
      table: String,
      database: Option[String] = None,
      tableType: CatalogTableType = CatalogTableType.MANAGED,
      storage: CatalogStorageFormat = CatalogStorageFormat.empty.copy(
        inputFormat = HiveSerDe.sourceToSerDe("textfile").get.inputFormat,
        outputFormat = HiveSerDe.sourceToSerDe("textfile").get.outputFormat,
        serde = Some("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe")),
      schema: StructType = new StructType,
      provider: Option[String] = Some("hive"),
      partitionColumnNames: Seq[String] = Seq.empty,
      comment: Option[String] = None,
      mode: SaveMode = SaveMode.ErrorIfExists,
      query: Option[LogicalPlan] = None): CreateTable = {
    CreateTable(
      CatalogTable(
        identifier = TableIdentifier(table, database),
        tableType = tableType,
        storage = storage,
        schema = schema,
        provider = provider,
        partitionColumnNames = partitionColumnNames,
        comment = comment
      ), mode, query
    )
  }

  test("create table - schema") {
    assertEqual("CREATE TABLE my_tab(a INT COMMENT 'test', b STRING) STORED AS textfile",
      createTable(
        table = "my_tab",
        schema = (new StructType)
          .add("a", IntegerType, nullable = true, "test")
          .add("b", StringType)
      )
    )
    assertEqual("CREATE TABLE my_tab(a INT COMMENT 'test', b STRING) " +
      "PARTITIONED BY (c INT, d STRING COMMENT 'test2')",
      createTable(
        table = "my_tab",
        schema = (new StructType)
          .add("a", IntegerType, nullable = true, "test")
          .add("b", StringType)
          .add("c", IntegerType)
          .add("d", StringType, nullable = true, "test2"),
        partitionColumnNames = Seq("c", "d")
      )
    )
    assertEqual("CREATE TABLE my_tab(id BIGINT, nested STRUCT<col1: STRING,col2: INT>) " +
      "STORED AS textfile",
      createTable(
        table = "my_tab",
        schema = (new StructType)
          .add("id", LongType)
          .add("nested", (new StructType)
            .add("col1", StringType)
            .add("col2", IntegerType)
          )
      )
    )
    // Partitioned by a StructType should be accepted by `SparkSqlParser` but will fail an analyze
    // rule in `AnalyzeCreateTable`.
    assertEqual("CREATE TABLE my_tab(a INT COMMENT 'test', b STRING) " +
      "PARTITIONED BY (nested STRUCT<col1: STRING,col2: INT>)",
      createTable(
        table = "my_tab",
        schema = (new StructType)
          .add("a", IntegerType, nullable = true, "test")
          .add("b", StringType)
          .add("nested", (new StructType)
            .add("col1", StringType)
            .add("col2", IntegerType)
          ),
        partitionColumnNames = Seq("nested")
      )
    )
    intercept("CREATE TABLE my_tab(a: INT COMMENT 'test', b: STRING)",
      "no viable alternative at input")
  }

  test("describe query") {
    val query = "SELECT * FROM t"
    assertEqual("DESCRIBE QUERY " + query, DescribeQueryCommand(query, parser.parsePlan(query)))
    assertEqual("DESCRIBE " + query, DescribeQueryCommand(query, parser.parsePlan(query)))
  }

  test("query organization") {
    // Test all valid combinations of order by/sort by/distribute by/cluster by/limit/windows
    val baseSql = "select * from t"
    val basePlan =
      Project(Seq(UnresolvedStar(None)), UnresolvedRelation(TableIdentifier("t")))

    assertEqual(s"$baseSql distribute by a, b",
      RepartitionByExpression(UnresolvedAttribute("a") :: UnresolvedAttribute("b") :: Nil,
        basePlan,
        None))
    assertEqual(s"$baseSql distribute by a sort by b",
      Sort(SortOrder(UnresolvedAttribute("b"), Ascending) :: Nil,
        global = false,
        RepartitionByExpression(UnresolvedAttribute("a") :: Nil,
          basePlan,
          None)))
    assertEqual(s"$baseSql cluster by a, b",
      Sort(SortOrder(UnresolvedAttribute("a"), Ascending) ::
          SortOrder(UnresolvedAttribute("b"), Ascending) :: Nil,
        global = false,
        RepartitionByExpression(UnresolvedAttribute("a") :: UnresolvedAttribute("b") :: Nil,
          basePlan,
          None)))
  }

  test("pipeline concatenation") {
    val concat = Concat(
      Concat(UnresolvedAttribute("a") :: UnresolvedAttribute("b") :: Nil) ::
      UnresolvedAttribute("c") ::
      Nil
    )
    assertEqual(
      "SELECT a || b || c FROM t",
      Project(UnresolvedAlias(concat) :: Nil, UnresolvedRelation(TableIdentifier("t"))))
  }

  test("database and schema tokens are interchangeable") {
    assertEqual("CREATE DATABASE foo", parser.parsePlan("CREATE SCHEMA foo"))
    assertEqual("DROP DATABASE foo", parser.parsePlan("DROP SCHEMA foo"))
    assertEqual("ALTER DATABASE foo SET DBPROPERTIES ('x' = 'y')",
      parser.parsePlan("ALTER SCHEMA foo SET DBPROPERTIES ('x' = 'y')"))
    assertEqual("DESC DATABASE foo", parser.parsePlan("DESC SCHEMA foo"))
  }

  test("manage resources") {
    assertEqual("ADD FILE abc.txt", AddFileCommand("abc.txt"))
    assertEqual("ADD FILE 'abc.txt'", AddFileCommand("abc.txt"))
    assertEqual("ADD FILE \"/path/to/abc.txt\"", AddFileCommand("/path/to/abc.txt"))
    assertEqual("LIST FILE abc.txt", ListFilesCommand(Array("abc.txt")))
    assertEqual("LIST FILE '/path//abc.txt'", ListFilesCommand(Array("/path//abc.txt")))
    assertEqual("LIST FILE \"/path2/abc.txt\"", ListFilesCommand(Array("/path2/abc.txt")))
    assertEqual("ADD JAR /path2/_2/abc.jar", AddJarCommand("/path2/_2/abc.jar"))
    assertEqual("ADD JAR '/test/path_2/jar/abc.jar'", AddJarCommand("/test/path_2/jar/abc.jar"))
    assertEqual("ADD JAR \"abc.jar\"", AddJarCommand("abc.jar"))
    assertEqual("LIST JAR /path-with-dash/abc.jar",
      ListJarsCommand(Array("/path-with-dash/abc.jar")))
    assertEqual("LIST JAR 'abc.jar'", ListJarsCommand(Array("abc.jar")))
    assertEqual("LIST JAR \"abc.jar\"", ListJarsCommand(Array("abc.jar")))
    assertEqual("ADD FILE /path with space/abc.txt", AddFileCommand("/path with space/abc.txt"))
    assertEqual("ADD JAR /path with space/abc.jar", AddJarCommand("/path with space/abc.jar"))
  }

  test("SPARK-32608: script transform with row format delimit") {
    assertEqual(
      """
        |SELECT TRANSFORM(a, b, c)
        |  ROW FORMAT DELIMITED
        |  FIELDS TERMINATED BY ','
        |  COLLECTION ITEMS TERMINATED BY '#'
        |  MAP KEYS TERMINATED BY '@'
        |  LINES TERMINATED BY '\n'
        |  NULL DEFINED AS 'null'
        |  USING 'cat' AS (a, b, c)
        |  ROW FORMAT DELIMITED
        |  FIELDS TERMINATED BY ','
        |  COLLECTION ITEMS TERMINATED BY '#'
        |  MAP KEYS TERMINATED BY '@'
        |  LINES TERMINATED BY '\n'
        |  NULL DEFINED AS 'NULL'
        |FROM testData
      """.stripMargin,
    ScriptTransformation(
      Seq('a, 'b, 'c),
      "cat",
      Seq(AttributeReference("a", StringType)(),
        AttributeReference("b", StringType)(),
        AttributeReference("c", StringType)()),
      UnresolvedRelation(TableIdentifier("testData")),
      ScriptInputOutputSchema(
        Seq(("TOK_TABLEROWFORMATFIELD", ","),
          ("TOK_TABLEROWFORMATCOLLITEMS", "#"),
          ("TOK_TABLEROWFORMATMAPKEYS", "@"),
          ("TOK_TABLEROWFORMATNULL", "null"),
          ("TOK_TABLEROWFORMATLINES", "\n")),
        Seq(("TOK_TABLEROWFORMATFIELD", ","),
          ("TOK_TABLEROWFORMATCOLLITEMS", "#"),
          ("TOK_TABLEROWFORMATMAPKEYS", "@"),
          ("TOK_TABLEROWFORMATNULL", "NULL"),
          ("TOK_TABLEROWFORMATLINES", "\n")), None, None,
        List.empty, List.empty, None, None, false)))
  }

  test("SPARK-32607: Script Transformation ROW FORMAT DELIMITED" +
    " `TOK_TABLEROWFORMATLINES` only support '\\n'") {

      // test input format TOK_TABLEROWFORMATLINES
      intercept(
          s"""
             |SELECT TRANSFORM(a, b, c, d, e)
             |  ROW FORMAT DELIMITED
             |  FIELDS TERMINATED BY ','
             |  LINES TERMINATED BY '@'
             |  NULL DEFINED AS 'null'
             |  USING 'cat' AS (value)
             |  ROW FORMAT DELIMITED
             |  FIELDS TERMINATED BY '&'
             |  LINES TERMINATED BY '\n'
             |  NULL DEFINED AS 'NULL'
             |FROM v
        """.stripMargin,
      "LINES TERMINATED BY only supports newline '\\n' right now")

    // test output format TOK_TABLEROWFORMATLINES
    intercept(
      s"""
         |SELECT TRANSFORM(a, b, c, d, e)
         |  ROW FORMAT DELIMITED
         |  FIELDS TERMINATED BY ','
         |  LINES TERMINATED BY '\n'
         |  NULL DEFINED AS 'null'
         |  USING 'cat' AS (value)
         |  ROW FORMAT DELIMITED
         |  FIELDS TERMINATED BY '&'
         |  LINES TERMINATED BY '@'
         |  NULL DEFINED AS 'NULL'
         |FROM v
        """.stripMargin,
      "LINES TERMINATED BY only supports newline '\\n' right now")
    }
}


text:
namespace Light.Serialization.Json.BuilderHelpers
{
    /// <summary>
    ///     Represents the abstraction used to enable or disable object reference preservation.
    /// </summary>
    public interface ISetObjectReferencePreservationStatus
    {
        /// <summary>
        ///     Sets the value indicating whether object ids and references to objects are serialized in the metadata section.
        /// </summary>
        bool IsSerializingObjectIds { set; }
    }
}


text:
Material Horizontal Floating Action Button

        menu

insert_chart

format_quote

publish

attach_file

      <form>

              <input id="title" type="text" placeholder='Card Title' ng-init="data.title='Test'" ng-model='data.title'></input>Card Title

                <input id="width" type="number" min="300" max="1200" step="10" ng-model='data.width' ng-init='data.width=500'></input>Width (px, min: 300)

                <input id="titleColor" type="color" placeholder='Title Color' ng-init="data.titleColor='#FFFFFF'" ng-model='data.titleColor'></input>Title Color

              <input id="contentBg" type="color" ng-init="data.contentBg='#2196F3'" ng-model='data.contentBg'></input>Content Background Color

            <input id="textcolor" type="color" ng-init="data.textcolor='#000000'" ng-model='data.textcolor'></input>Text Color

              <input id="footerBg" type="color" ng-init="data.footerBg='#FFFFFF'" ng-model='data.footerBg'></input>Footer Background Color

        <button ng-click='simpleCardIpsum()' class="waves-effect waves-light btn">addAdd more ipsum</button>
        <button type='submit' ng-click='simpleCardSubmit(data.title, data.width, data.titleColor, data.contentBg, data.textcolor, data.footerBg)' class="waves-effect waves-light btn">cloudSave to account</button>

      </form>

          <textarea rows="10" cols="20" class="text-area">

    {{title}}

I am a very simple card. I am good at containing small bits of information.
    I am convenient because I require little markup to use effectively.

    This is a link
    This is a link

          </textarea>


text:
namespace urde {

amuse::AudioGroupData CAudioGroupSet::LoadData() {
  athena::io::MemoryReader r(m_buffer.get(), INT32_MAX);
  x10_baseName = r.readString();
  x20_name = r.readString();

  u8* buf = m_buffer.get() + r.position();
  uint32_t poolLen = hecl::SBig(*reinterpret_cast<uint32_t*>(buf));
  unsigned char* pool = buf + 4;
  buf += poolLen + 4;
  uint32_t projLen = hecl::SBig(*reinterpret_cast<uint32_t*>(buf));
  unsigned char* proj = buf + 4;
  buf += projLen + 4;
  uint32_t sampLen = hecl::SBig(*reinterpret_cast<uint32_t*>(buf));
  unsigned char* samp = buf + 4;
  buf += sampLen + 4;
  uint32_t sdirLen = hecl::SBig(*reinterpret_cast<uint32_t*>(buf));
  unsigned char* sdir = buf + 4;

  return {proj, projLen, pool, poolLen, sdir, sdirLen, samp, sampLen, amuse::GCNDataTag{}};
}

CAudioGroupSet::CAudioGroupSet(std::unique_ptr<u8[]>&& in) : m_buffer(std::move(in)), m_data(LoadData()) {}

CFactoryFnReturn FAudioGroupSetDataFactory(const urde::SObjectTag& tag, std::unique_ptr<u8[]>&& in, u32 len,
                                           const urde::CVParamTransfer& vparms, CObjectReference* selfRef) {
  return TToken<CAudioGroupSet>::GetIObjObjectFor(std::make_unique<CAudioGroupSet>(std::move(in)));
}

} // namespace urde


text:
using System;
using System.Diagnostics;
using Microsoft.SPOT.Hardware;

namespace uScoober
{
    [DebuggerStepThrough]
    public class Stopwatch
    {
        private long _lastSplit;
        private long _started;

        public double CumulativeSplit() {
            if (_started == 0) {
                throw new Exception("Stopwatch is not running.");
            }
            return ComputeElapsed();
        }

        public double Split() {
            if (_started == 0) {
                throw new Exception("Stopwatch is not running.");
            }
            long temp = GetMachineTicks();
            double result = (temp - _lastSplit) / (1.0 * TimeSpan.TicksPerSecond);
            _lastSplit = temp;
            return result;
        }

        public void Start() {
            if (_started != 0) {
                throw new Exception("Stopwatch already running.");
            }
            _started = GetMachineTicks();
            _lastSplit = _started;
        }

        public double Stop() {
            if (_started == 0) {
                return 0;
            }
            double result = ComputeElapsed();
            _started = 0;
            return result;
        }

        private double ComputeElapsed() {
            return (GetMachineTicks() - _started) / (1.0 * TimeSpan.TicksPerSecond);
        }

        public static Stopwatch StartNew() {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            return stopwatch;
        }

        public static double TimeExecution(int iterations, Action action) {
            if (action == null) {
                throw new ArgumentNullException("action");
            }
            long start = GetMachineTicks();
            for (int i = 0; i < iterations; i++) {
                action();
            }
            long end = GetMachineTicks();
            return (end - start) / (iterations * 1.0 * TimeSpan.TicksPerSecond);
        }

        private static long GetMachineTicks() {
            return Utility.GetMachineTime()
                          .Ticks;
        }
    }
}