text:
module SugarfreeConfig
  #
  # Exception raised by the module on unexpected behaviors
  #
  class ConfigException < Exception
  end

  #
  # Exception raised by the Config Iterator when a key is not found
  #
  class ConfigKeyException < ConfigException

    #
    # Config key path (as a key collection) that failed
    #
    attr_accessor :key_path_elements

    #
    # Create a new exception with the not found key paths (+key_path_elements+
    # Array)
    #
    def initialize(key_path_elements)
      self.key_path_elements = [*key_path_elements].map(&:to_s)
      super("Cannot find key #{self.key_path_elements.join('.')}")
    end
  end
end


text:
require 'test_helper'

class DeployOptionsHelperTest < ActionView::TestCase
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <title>Chris Gomes' DBC Blog Phase 0 Week 6</title>
  <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
  <link rel="stylesheet" type="text/css" href="../stylesheets/blog.css">
  <meta charset="UTF-8">

DBC Blog

Phase 0

Week 6 11/06/2015

        In the sixth week of Dev Bootcamp, we looked a bit more in depth into classes and nested data-structures. For this entry, I want to discuss classes and give an illustrative example.

 The idea of a class

        Classes are what we use to model real world objects. Think of how you might describe an object. You would use adjectives (nouns) to specify particular qualities of the objects - e.g. ocean water is cool, blue, and salty. However, you can also describe an object by verbs - by what it does or has done to it. Water allows energy to be transmitted in the form of waves. Water freezes. Water causes Sharknados. A class is an abstraction of an object specified by its instance variables (i.e. nouns) and class methods (i.e. verbs). We construct a class (called  Splat) as follows:

          Class Splat {

          def initialize(var1, var2, ...)
            @var1 = var1
            @var2 = var2
              .
              .
              .
          end

          # The rest of your method defintions go here
        }

        Let us note a few things: First, class names are captalized; next, classes have an initialize method. This is the method you use to
        create new new objects of type  Splat. To create a new  Splat-object (called
        shirleys_splat for example), you would declare

          shirleys_splat = Splat.new(var1, var2, ...)

        Please note that the variables  var1, var2, ...  are optional. The variables denoted  @var1, @var2, ...  are called instance variables. Instance variables are 'visible' only inside of the class itself. You cannot alter instance variables from outside of a class (unless you define a class method that allows you to so). Instance variables differ from local variables in that local variables are only visible inside the method they appear in. Instance variables visible in all methods defined iin the class. On other words, once you have declared an instance variable in a class method, you are free to define other class methods that also use that instance variable. For example, suppose that  Splat  has the following methods

          def method1
            @var1 = 0
            @var2 = 'Gravy!'
            var3 = 22.5

            # Put code here to make method1 do something
          end

          def method2
            @var1 = 0
            var4 = "Bug spray"

            # Put code here to make method2 do something
          end

        In the above methods  @var1  is an instance variable and so can appear in methods.
        On the other hand,  var4  is local and can only be used in method2
        and not in method1. There are other concepts related to classes (such as class variables),
        that I won't go into. This is only intended to be a first exposure to these ideas.

 An example of a class

        Let's consider a super villain. At the very least, a super villain can be specified by a name (e.g. The Harmulator), type (e.g. mad scientist, superpowered psychopath), special power (e.g. heat vision, super garlic breath) and by costume color. Some actions related to super villains include:

taking hostages

belittling minions

blowing things up

making demands

       With this in mind, let's construct our basic super villain class.

        class SuperVillain

          def initialize(name, type, super_power, costume_color)
            @name = name
            @type = type
            @super_power = super_power
            @costume_color = costume_color
            @hostages = []
            @to_be_demolished = []
            @proclamations = ["I hearby ban Nutella!", "Bring me ... One Million Kumquats!"]
          end

          def take_hostage(hostage)
            puts "#{hostage}! You have been taken hostage"
            return @hostages + hostage.to_a   # This allows both individual hostages and groups of hostages to be taken
          end

          def belittle_minion()
            print "Your mother wears necropants and your father invented crab shampoo!"
          end

          def demolish(monument)
            puts "Murdiddily-urder #{monument}"
            @to_be_demolished + monument.to_a
          end

          def make_proclamation()
            print @proclamations.shuffle[0]
          end

        end

      Let's construct a new super villain:

       puts harm = SuperVillain.new("The Harmulator", "mad scientist", "super halitosis", "Blood Red")
       puts harm.take_hostage(["Willow","Wesley",["J.Crew Models"]])
       puts harm.belittle_minion()
       puts harm.demolish(["Star Bucks", "Trump Tower"])
       puts harm.make_proclamation()

       # with resulting output
       => nil
       ["Willow", "Wesley", ["J.Crew Models"]]! You have been taken hostage
       Willow
       Wesley
       J.Crew Models
       Murdiddily-urder ["Star Bucks", "Trump Tower"]
       Star Bucks
       Trump Tower
       Bring me ... One Million Kumquats!

      Notice that all of the variables are instance variables, however, that does not always need to be the case. There are some issues that I have
      ignored. For example, how do you print out or change the values of the instance variables? In other languages you would have to explicitly define
      'get' and 'set' methods. However, in Ruby there is a shortcut called the attr_* family of methods. For example, in
      SuperVillain, adding the line attr_reader :name gives you a method that will return the value of name, while adding attr_reader :costume_color gives you a method that allows you to change the value of costume_color. There are many other aspects of classes that I have not talked about. I only wanted to you a brief first exposure to this topic.

Chris Gomes © 2015

Home

Blog Index


text:
(function(exports) {
    "use strict";

    ArticleDemos.registerDemo("window-pixel-map", "height: 250px", function(res) {
        DemoCommon.addInspector(res);

        var server = res.server;
        var connection = server.connect();
        var display = connection.display;

        display.changeAttributes({ windowId: display.rootWindowId, backgroundColor: '#266FB2' });
        display.invalidateWindow({ windowId: display.rootWindowId });

        // The shaking window that's behind.
        var kitten2 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        DemoCommon.centerWindow(display, kitten2, { x: -20, y: 40 });
        display.changeAttributes({ windowId: kitten2, backgroundColor: '#B24E48' });
        display.changeProperty({ windowId: kitten2, name: 'WM_NAME', value: 'kitten2.png' });
        display.invalidateWindow({ windowId: kitten2 });
        display.mapWindow({ windowId: kitten2 });

        // The window on top that's obscuring the window behind it.
        var kitten1 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        DemoCommon.centerWindow(display, kitten1);
        display.changeAttributes({ windowId: kitten1, backgroundColor: '#F3FF5D' });
        display.changeProperty({ windowId: kitten1, name: 'WM_NAME', value: 'kitten1.png' });
        display.invalidateWindow({ windowId: kitten1 });
        display.mapWindow({ windowId: kitten1 });

        var shaker = new DemoCommon.WindowShaker(server, kitten2);
    });

    ArticleDemos.registerDemo("window-pixel-map-shaped", "height: 250px", function(res) {
        DemoCommon.addInspector(res);

        var server = res.server;
        var connection = server.connect();
        var display = connection.display;

        display.changeAttributes({ windowId: display.rootWindowId, backgroundColor: '#266FB2' });
        display.invalidateWindow({ windowId: display.rootWindowId });

        // The shaking window that's behind.
        var kitten2 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        DemoCommon.centerWindow(display, kitten2, { x: -20, y: 40 });
        display.changeAttributes({ windowId: kitten2, backgroundColor: '#B24E48' });
        display.changeProperty({ windowId: kitten2, name: 'WM_NAME', value: 'kitten2.png' });
        display.invalidateWindow({ windowId: kitten2 });
        display.mapWindow({ windowId: kitten2 });

        // The window on top that's obscuring the window behind it.
        var kitten1 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        DemoCommon.centerWindow(display, kitten1);
        display.changeAttributes({ windowId: kitten1, backgroundColor: '#F3FF5D' });
        display.changeProperty({ windowId: kitten1, name: 'WM_NAME', value: 'kitten1.png' });
        display.invalidateWindow({ windowId: kitten1 });

        ClientUtil.loadImageAsPixmap(display, "kittencircle.png", function(pixmapId) {
            var image = display.getPixmapImage({ pixmapId: pixmapId });
            var ctx = image.getContext('2d');
            var imgData = ctx.getImageData(0, 0, image.width, image.height);

            var region = DemoCommon.scanImageDataForVisibleRegion(imgData);
            display.setWindowShapeRegion({ windowId: kitten1,
                                           shapeType: "Bounding",
                                           region: region });
            display.mapWindow({ windowId: kitten1 });
        });

        var shaker = new DemoCommon.WindowShaker(server, kitten2);
    });

    ArticleDemos.registerDemo("naive-redirect", "height: 250px", function(res) {
        DemoCommon.addInspector(res);

        var server = res.server;
        var connection = server.connect();
        var display = connection.display;

        display.changeAttributes({ windowId: display.rootWindowId, backgroundColor: '#266FB2' });
        display.invalidateWindow({ windowId: display.rootWindowId });

        // The shaking window that's behind.
        var kitten2 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten2, name: 'WM_NAME', value: 'kitten2.png' });
        DemoCommon.centerWindow(display, kitten2, { x: -20, y: 40 });
        ClientUtil.loadImageAsPixmap(display, "kitten2.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten2, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten2 });
            display.mapWindow({ windowId: kitten2 });
        });

        // The window on top that's obscuring the window behind it.
        var kitten1 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten1, name: 'WM_NAME', value: 'kitten1.png' });
        DemoCommon.centerWindow(display, kitten1);
        ClientUtil.loadImageAsPixmap(display, "kitten1.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten1, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten1 });
            display.redirectWindow({ windowId: kitten1, mode: "manual" });
            display.mapWindow({ windowId: kitten1 });
        });

        var dragger = new DemoCommon.WindowDragger(server, kitten1);

        var shaker = new DemoCommon.WindowShaker(server, kitten2);
    });

    ArticleDemos.registerDemo("composited-kitten", "height: 250px", function(res) {
        var server = res.server;
        var connection = server.connect();
        var display = connection.display;

        // Rather than use a normal background on the root window, use a large background
        // window that gets redirected so the CM won't fight to paint on the root window.
        //
        // ... I should add a COW at some point, shouldn't I... sigh.
        var bgWindow = display.createWindow({ x: 0, y: 0, width: 1000, height: 1000 });
        display.changeProperty({ windowId: bgWindow, name: '_XJS_HIDE_INSPECTOR', value: true });
        display.changeAttributes({ windowId: bgWindow, backgroundColor: '#266FB2' });
        display.mapWindow({ windowId: bgWindow });

        DemoCommon.addInspector(res);

        // The shaking window that's behind.
        var kitten2 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten2, name: 'WM_NAME', value: 'kitten2.png' });
        DemoCommon.centerWindow(display, kitten2, { x: -20, y: 40 });
        ClientUtil.loadImageAsPixmap(display, "kitten2.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten2, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten2 });
        });
        display.mapWindow({ windowId: kitten2 });

        // The window on top that's obscuring the window behind it.
        var kitten1 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten1, name: 'WM_NAME', value: 'kitten1.png' });
        display.changeProperty({ windowId: kitten1, name: 'OPACITY', value: 0.5 });
        DemoCommon.centerWindow(display, kitten1);
        ClientUtil.loadImageAsPixmap(display, "kitten1.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten1, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten1 });
        });
        display.mapWindow({ windowId: kitten1 });

        var dragger = new DemoCommon.WindowDragger(server, kitten1);

        var shaker = new DemoCommon.WindowShaker(server, kitten2);

        var cm = new CompositingManager.Canvas2DCompositingManager(server, display.rootWindowId);
    });

    ArticleDemos.registerDemo("gl-composite", "height: 250px", function(res) {
        var elem = res.elem;
        var serverSlot = elem.querySelector("div");

        var width = serverSlot.clientWidth;
        var height = serverSlot.clientHeight;

        var server = res.server;
        var connection = server.connect();
        var display = connection.display;

        var glCanvas = document.createElement("canvas");
        glCanvas.classList.add("overlay");
        glCanvas.width = width;
        glCanvas.height = height;
        server.elem.appendChild(glCanvas);

        var gl = glCanvas.getContext("webgl", { alpha: false });
        gl.$viewportWidth = width;
        gl.$viewportHeight = height;
        gl.viewport(0, 0, width, height);

        // Rather than use a normal background on the root window, use a large background
        // window that gets redirected so the CM won't fight to paint on the root window.
        //
        // ... I should add a COW at some point, shouldn't I... sigh.
        var bgWindow = display.createWindow({ x: 0, y: 0, width: 1000, height: 1000 });
        display.changeProperty({ windowId: bgWindow, name: '_XJS_HIDE_INSPECTOR', value: true });
        display.changeAttributes({ windowId: bgWindow, backgroundColor: '#266FB2' });
        display.mapWindow({ windowId: bgWindow });

        DemoCommon.addInspector(res);

        // The shaking window that's behind.
        var kitten2 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten2, name: 'WM_NAME', value: 'kitten2.png' });
        DemoCommon.centerWindow(display, kitten2, { x: -20, y: 40 });
        ClientUtil.loadImageAsPixmap(display, "kitten2.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten2, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten2 });
        });
        display.mapWindow({ windowId: kitten2 });

        // The window on top that's obscuring the window behind it.
        var kitten1 = display.createWindow({ x: 0, y: 0, width: 125, height: 125 });
        display.changeProperty({ windowId: kitten1, name: 'WM_NAME', value: 'kitten1.png' });
        display.changeProperty({ windowId: kitten1, name: 'OPACITY', value: 0.5 });
        DemoCommon.centerWindow(display, kitten1);
        ClientUtil.loadImageAsPixmap(display, "kitten1.png", function(pixmapId) {
            display.changeAttributes({ windowId: kitten1, backgroundPixmap: pixmapId });
            display.invalidateWindow({ windowId: kitten1 });
        });
        display.mapWindow({ windowId: kitten1 });

        var dragger = new DemoCommon.WindowDragger(server, kitten1);

        var shaker = new DemoCommon.WindowShaker(server, kitten2);

        var cm = new CompositingManager.GLCompositingManager(server, display.rootWindowId, gl);
        display.mapWindow({ windowId: kitten2 });
        display.mapWindow({ windowId: kitten1 });

        // Disgusting hack to insert the triangle in the right spot.
        setTimeout(function() {
            var tri = new CompositingManager.TriangleActor(cm._renderer, cm._gl);
            cm._renderer._actorStacking.splice(3, 0, tri);
        }, 500);
    });

})(window);


text:
import 'moment/locale/fr';
import * as FullCalendar from 'fullcalendar';

/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood{at}iinet.com.au),
        Stéphane Nahmani (sholby@sholby.net),
        Stéphane Raimbault <stephane.raimbault@gmail.com> */
FullCalendar.datepickerLocale('fr', 'fr', {
  closeText: "Fermer",
  prevText: "Précédent",
  nextText: "Suivant",
  currentText: "Aujourd'hui",
  monthNames: [ "janvier", "février", "mars", "avril", "mai", "juin",
    "juillet", "août", "septembre", "octobre", "novembre", "décembre" ],
  monthNamesShort: [ "janv.", "févr.", "mars", "avr.", "mai", "juin",
    "juil.", "août", "sept.", "oct.", "nov.", "déc." ],
  dayNames: [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ],
  dayNamesShort: [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ],
  dayNamesMin: [ "D","L","M","M","J","V","S" ],
  weekHeader: "Sem.",
  dateFormat: "dd/mm/yy",
  firstDay: 1,
  isRTL: false,
  showMonthAfterYear: false,
  yearSuffix: "" });

FullCalendar.locale("fr", {
  buttonText: {
    year: "Année",
    month: "Mois",
    week: "Semaine",
    day: "Jour",
    list: "Mon planning"
  },
  allDayHtml: "Toute la<br/>journée",
  eventLimitText: "en plus",
  noEventsMessage: "Aucun événement à afficher"
});


text:
/**
 * Created by king on 15-2-12.
 *
 * ch02.module-exchangerate-main.js
 */
console.info("\n");
console.info("------汇率换算应用------");
console.info("\n");
var exRate = require('./ch02.module-exchangerate-obj.js');  // 加载自定义模块
var readline = require('readline');     // 加载核心模块
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.question("Please enter count: ", function(iMoney) {
    // TODO: 调用dollar2rmb()方法将美元换算成人民币
    console.info(iMoney + ' US-Dollar exchange to RMB equals ' + exRate.dollar2rmb(iMoney));
    // TODO: 调用rmb2dollar()方法将人民币换算成美元
    console.info(iMoney + ' RMB exchange to US-Dollar equals ' + exRate.rmb2dollar(iMoney));
    console.info("\n");
    rl.close();
});


text:
import { mount } from "enzyme"
import { Text } from "@artsy/palette"
import { InfoSection } from "../InfoSection"

describe("InfoSection", () => {
  it("shows plain text", () => {
    const wrapper = mount(
      <InfoSection info={"Info example"} type="text" />
    )
    expect(wrapper.find("HTML").length).toEqual(0)
    expect(wrapper.find("TextWithNewlines").length).toEqual(1)
    expect(wrapper.find("TextWithNewlines").text()).toEqual(
      "Info example"
    )
  })

  it("shows html", () => {
    const wrapper = mount(
      <InfoSection info={"Info example"} type="html" />
    )
    expect(wrapper.find("TextWithNewlines").length).toEqual(0)
    expect(wrapper.find("HTML").length).toEqual(1)
    expect(wrapper.find("HTML").text()).toEqual("Info example")
  })

  it("shows passed JSX", () => {
    const wrapper = mount(
      <InfoSection
        info={
          <>
            <Text>Info item</Text>
            <Text>Another item</Text>
          </>
        }
      />
    )
    expect(wrapper.find("TextWithNewlines").length).toEqual(0)
    expect(wrapper.find("HTML").length).toEqual(0)
    expect(wrapper.find("Text").length).toEqual(2)
    expect(wrapper.text()).toContain("Info item")
    expect(wrapper.text()).toContain("Another item")
  })

  it("shows label", () => {
    const wrapper = mount(
      <InfoSection info={"Info example"} type="text" label="About:" />
    )
    expect(wrapper.find("Text").length).toEqual(1)
    expect(wrapper.find("Text").text()).toEqual("About:")
  })
})


text:
namespace DotNetThumborTest.TestThumborFilters
{
    using DotNetThumbor;

    using FluentAssertions;

    using NUnit.Framework;

    [TestFixture]
    public class TestRgb
    {
        [Test]
        [TestCase(1, 2, 3)]
        [TestCase(100, 50, 0)]
        public void ThumborRgbFilter(int red, int green, int blue)
        {
            var thumbor = new Thumbor("http://localhost/");
            var resizedUrl = thumbor.BuildImage("http://localhost/image.jpg")
                                    .Rgb(red, green, blue)
                                    .ToFullUrl();
            resizedUrl.Should().Be(string.Format("http://localhost/unsafe/filters:rgb({0},{1},{2})/http://localhost/image.jpg", red, green, blue));
        }
    }
}


text:
package okhttp3.internal.http;

public interface UnrepeatableRequestBody {
}


text:
package baseline;
import java.io.*;

import java.util.*;

import utils.*;

/**
 * This is the basic algorithm which starts from the lowest k
 * removes all vertices with degree k
 * subtracts 1 from all adjVertices of these removed vertices
 * iterates to collect additional vertices with degree k
 * until no more can be found.
 * This concludes one iteration of this basic algorithm.
 *
 * To accomodate processing of large files,
 * the entire file is not loaded into ram, but it is broken into smaller files, each of them is scanned and processed at once.
 *
 * The scaling bottleneck is when the original subgraph for current value of k exceeds the available main memory.
 *
 * Program arguments:
 * 1 - name of the input graph file
 * 2 (optional) - max number of elements in each small file - that depends on the available main memory. Default: 100,000 elements.
 * Each element represents a vertex, including parent nodes and the node ids in the adjacency lists.
 * 3 (optional) - input delimiter. Default: tab
 **/

public class BottomUpAlgorithm {
	static long totalDiskReads = 0;
	public static void main (String [] args)
	{
		int MAX_ELEMENTS = 100000;
		if (args.length < 1)
		{
			System.out.println ("provide the name of the input graph file and  "
					+ "optionally the max number of elements in memory and a delimiter for each line in this file ");
			System.exit(0);
		}

		BufferedReader reader = null;
		String inputFileName = args[0];

		if (args.length >1)
			MAX_ELEMENTS = Integer.parseInt(args[1]);

		String delimiter = String.valueOf('\t');
		if (args.length >2)
			delimiter = args[2];

		long startTime = System.currentTimeMillis();

		//first, rewrite the entire input as a set of vertices with adjacency lists
		//and break the input into small files with at most MAX_ELEMENTS total vertices IDs
		try
		{
			File file = new File(inputFileName);
		    reader = new BufferedReader(new FileReader(file));
		}
		catch (Exception ge)
		{
			System.out.println("Unexpected error when reading from File "+inputFileName +": "+ge.getMessage());
			System.exit(1);
		}

		String line;
		Vertex currentVertex =null;
		int currentvertexID = -1;

		List <Vertex> buffer = new ArrayList <Vertex>();  //buffer stores all graph nodes with adjacency lists, to be written to disk

		int elementsCount =0;
		int outputFileID = 0;
		int totalOutputFiles=0;
		int totalNodes = 0;
		int lineID =0;
		int maxDegree =0;

		try
		{
			while ((line = reader.readLine()) != null)
			{
				String [] pair = line.split(delimiter);
				int parentVertexID =0;
				int childVertexID=0 ;
				boolean validLine = true;

				try
				{
					parentVertexID = Integer.parseInt(pair[0]);
					childVertexID = Integer.parseInt(pair[1]);
				}
				catch (Exception e)
				{
					validLine = false;
				}

				if (validLine)
				{
					if (parentVertexID != currentvertexID) //change of vertices
					{
						if (currentVertex != null) //prev vertex is done, try to add it to the best bucket
						{
							buffer.add(currentVertex);
							totalNodes++;
							if (currentVertex.getDegree() > maxDegree)
								maxDegree = currentVertex.getDegree();
							elementsCount += (1+currentVertex.getDegree());

							if (elementsCount >MAX_ELEMENTS)
							{
								flushResetBuffer (buffer, outputFileID++);
								elementsCount=0;
								totalOutputFiles++;
								buffer = new ArrayList<Vertex>();
							}
						}
						currentVertex = new Vertex(parentVertexID);
						currentvertexID = parentVertexID;
					}
					currentVertex.addAdjVertex(childVertexID);

					if (totalNodes >0 && totalNodes % 1000000 == 0)
						System.out.println("Added vertex "+totalNodes);
					lineID++;
					if (lineID % 1000000 == 0)
						System.out.println("Processed line "+lineID);
				}
			}
			buffer.add(currentVertex);
			totalNodes++;
			flushResetBuffer (buffer, outputFileID++);
			totalOutputFiles++;
		}
		catch (Exception ge)
		{
			System.out.println("Unexpected error when processing lines of input file: "+ge.getMessage());
			System.exit(1);
		}

		System.out.println("Total output files = "+totalOutputFiles +"; total nodes in the graph="+totalNodes+"; max node degree is "+maxDegree);
		System.out.println ("Total partitioning time = "+(System.currentTimeMillis() - startTime)+" ms.");

		boolean done = false;
		int k=1;

		//now start going over files and collecting first nodes - with degree 1, and then all the rest - bottom up
		while (!done)
		{
			done = iterate (totalOutputFiles, k++);
		}

		//
		System.out.println ("Total time = "+(System.currentTimeMillis() - startTime)+" ms.");
		System.out.println ("Total vertex disk reads="+totalDiskReads);
	}

	private static boolean iterate (int totalFiles,int k)
	{
		boolean allProcessed = true;
		String inputFilePrefix = Utils.TEMP_FOLDER + System.getProperty("file.separator") + Utils.BLOCK_FILE_PREFIX;

		BufferedReader reader = null;
		BufferedWriter writer=null;

		Map <Integer, Object> degreeKNodes = new HashMap <Integer, Object>();  //stores nodes identified as k-core so far

		//1. Collect all nodes with degree k first

		for (int i=0;i<totalFiles; i++)
		{
			boolean fileExists = true;
			try
			{
				File file = new File(inputFilePrefix+i);
			    reader = new BufferedReader(new FileReader(file));
			}
			catch (Exception ge)
			{
				//file does not exist, do nothing, continue
				fileExists =false;
			}

			if (fileExists)  //read all k-degree nodes from it
			{
				String line=null;
				int lineID = 0;
				try
				{
					boolean done = false;
					while ((line = reader.readLine()) != null &&  !done && !line.equals(""))
					{
						totalDiskReads++;
						String [] fields = line.split(Utils.FIELD_SEPARATOR);
						int degree =0;

						if (fields.length == 3 && !fields [2].equals(""))
						{
							String [] adjNodes = fields [2].split(Utils.VALUE_SEPARATOR);
							degree = adjNodes.length;
						}
						if (degree == k)
						{
							Vertex v = Vertex.constructFromString (line);
							degreeKNodes.put(v.getID(), null);
						}
						else  //the vertices are sorted ascending, so the next is bigger than the current k
							done = true;
						lineID++;
					}

					reader.close();
				}
				catch (Exception ge)
				{
					System.out.println("Unexpected error when reading from File "+(inputFilePrefix+i)
							+" line number "+lineID +": "+ ge.getMessage());
					ge.printStackTrace();
				    System.exit(1);
				}
			}
		}

		//now we need to iterate over input files again, and - remove all nodes with degree k, and remove all adjacent vertices  that correspond to these nodes
		//the remaining nodes are written into new files
		boolean allRemoved = false;

		while (!allRemoved)
		{
			allRemoved = true;
			allProcessed = true;

			for (int i=0;i<totalFiles; i++)
			{
				List <Vertex> remainingNodes = new ArrayList <Vertex>();
				boolean fileExists = true;
				try
				{
					File file = new File(inputFilePrefix+i);
				    reader = new BufferedReader(new FileReader(file));
				}
				catch (Exception ge)
				{
					//file does not exist, do nothing, continue
					fileExists =false;
				}

				if (fileExists)  //read all k-degree nodes from it
				{
					String line=null;
					int lineID = 0;
					try
					{
						while ((line = reader.readLine()) != null &&   !line.equals(""))
						{
							totalDiskReads++;
							Vertex v = Vertex.constructFromString (line);
							if (!degreeKNodes.containsKey(v.getID()))
							{
								List <Integer>newAdjNodes = new ArrayList <Integer>();
								for (int a=0; a<v.getDegree(); a++)
								{
									Integer aID = v.getAdjvertexID(a);
									if (!degreeKNodes.containsKey(aID))
									{
										newAdjNodes.add(aID);
									}
									else
										allRemoved = false;
								}
								v.replaceAdjVertices( newAdjNodes);
								if (v.getDegree() <= k)
									degreeKNodes.put(v.getID(), null);
								else
									remainingNodes.add(v);
							}
							else
								allRemoved = false;
							lineID++;
						}

						reader.close();
					}
					catch (Exception ge)
					{
						System.out.println("Unexpected error when reading from File "+(inputFilePrefix+i)
								+" line number "+lineID +": "+ ge.getMessage());
						ge.printStackTrace();
					    System.exit(1);
					}

					//write remaining nodes back to the file
					try
					{
						File outputfile = new File(inputFilePrefix+i);
						FileWriter fileWriter = new FileWriter(outputfile);
						writer = new BufferedWriter(fileWriter);
					}
					catch (Exception ge)
					{
						System.out.println("Unexpected error when opening file '"+(inputFilePrefix+i) +"' for writing: "+ge.getMessage());
					    System.exit(1);
					}

					if (remainingNodes.size()>0)
					{
						allProcessed = false;
						//write them back to the same file
						//now sort them ascending for the next bottom-up processing
						Collections.sort(remainingNodes, new DegreeComparator(true)); //sorts in ascending order according to a new degree, after removing vertices
						//System.out.println("--------------------");
						//System.out.println (remainingNodes);
						//System.out.println();

						//write to file
						try
						{
							for (int e=0; e<remainingNodes.size(); e++)
							{
								writer.write(remainingNodes.get(e).toString());
								writer.newLine();
							}
							writer.flush();
							writer.close();
						}
						catch (Exception ge)
						{
							System.out.println("Unexpected error when writing to file '"+(inputFilePrefix+i) +"': "+ge.getMessage());
							System.exit(1);
						}
					}
				}
			}
		}

		//finally write current core class to the results folder
		if (degreeKNodes.size()>0)
		{
			String fname = Utils.RESULT_FOLDER +System.getProperty("file.separator")+"core_class_"+k;
			try
			{
				File outputfile = new File(fname);
				FileWriter fileWriter = new FileWriter(outputfile);
				writer = new BufferedWriter(fileWriter);
				System.out.println("Total core-"+k +" nodes:"+degreeKNodes.keySet().size());
				List <Integer>list = new LinkedList <Integer>(degreeKNodes.keySet());
				Collections.sort(list);
				writer.write(list.toString());
				writer.flush();
				writer.close();
			}
			catch (Exception ge)
			{
				System.out.println("Unexpected error when writing to file '"+fname +"' core class "+k+": "+ge.getMessage());
			    System.exit(1);
			}
		}
		return allProcessed;
	}

	private static void flushResetBuffer (List <Vertex>buffer, int currentFileID)
	{
		String fileName = Utils.TEMP_FOLDER +System.getProperty("file.separator") + Utils.BLOCK_FILE_PREFIX + currentFileID;
		Collections.sort(buffer, new DegreeComparator(true)); //sorts in ascending order of degrees - bottom-up computation
		//System.out.println(buffer);
		BufferedWriter writer = null;
		try
		{
		    writer = new BufferedWriter(new FileWriter(fileName));

			for (int i=0; i<buffer.size(); i++)
			{
				writer.write(buffer.get(i).toString());
				writer.newLine();
			}

			writer.flush();
			writer.close();
		}
		catch (FileNotFoundException e)
		{
			System.out.println("Cannot write to File "+fileName +": "+e.getMessage());
		    e.printStackTrace();
		    System.exit(1);
		}
		catch (Exception ge)
		{
			System.out.println("Unexpected error when writing to File "+fileName +": "+ge.getMessage());
		    System.exit(1);
		}
	}
}

/*
 * Test printout for amazon0302.txt -> test2.txt (complemented, sorted, duplicates removed)
Total output files = 21; total nodes in the graph=262111; max node degree is 420
Total core-1 nodes:6503
Total core-2 nodes:7451
Total core-3 nodes:11078
Total core-4 nodes:78421
Total core-5 nodes:158372
Total core-6 nodes:286

for input small.txt
Added vertex 0
Total output files = 5; total nodes in the graph=14; max node degree is 6
Total core-1 nodes:4
Total core-2 nodes:5
Total core-3 nodes:5
 */


text:
from neutron_lib import constants
from oslo_utils import uuidutils

from neutron.cmd.sanity import checks
from neutron.common import utils as common_utils
from neutron.tests.common import net_helpers
from neutron.tests.fullstack import base
from neutron.tests.fullstack.resources import environment
from neutron.tests.fullstack.resources import machine
from neutron.tests.unit import testlib_api

load_tests = testlib_api.module_load_tests

class OVSVersionChecker(object):
    conntrack_supported = None

    @classmethod
    def supports_ovsfirewall(cls):
        if cls.conntrack_supported is None:
            cls.conntrack_supported = checks.ovs_conntrack_supported()

        return cls.conntrack_supported

class BaseSecurityGroupsSameNetworkTest(base.BaseFullStackTestCase):

    of_interface = None

    def setUp(self):
        host_descriptions = [
            environment.HostDescription(
                of_interface=self.of_interface,
                l2_agent_type=self.l2_agent_type,
                firewall_driver=self.firewall_driver,
                dhcp_agent=True) for _ in range(2)]
        env = environment.Environment(
            environment.EnvironmentDescription(
                network_type=self.network_type),
            host_descriptions)
        super(BaseSecurityGroupsSameNetworkTest, self).setUp(env)

        if (self.firewall_driver == 'openvswitch' and
            not OVSVersionChecker.supports_ovsfirewall()):
            self.skipTest("Open vSwitch firewall_driver doesn't work "
                          "with this version of ovs.")

    def assert_connection(self, *args, **kwargs):
        netcat = net_helpers.NetcatTester(*args, **kwargs)
        try:
            self.assertTrue(netcat.test_connectivity())
        finally:
            netcat.stop_processes()

    def assert_no_connection(self, *args, **kwargs):
        netcat = net_helpers.NetcatTester(*args, **kwargs)
        try:
            self.assertRaises(RuntimeError, netcat.test_connectivity)
        finally:
            netcat.stop_processes()

class TestSecurityGroupsSameNetwork(BaseSecurityGroupsSameNetworkTest):

    network_type = 'vxlan'
    scenarios = [
        ('ovs-hybrid', {
            'firewall_driver': 'iptables_hybrid',
            'of_interface': 'native',
            'l2_agent_type': constants.AGENT_TYPE_OVS}),
        ('ovs-openflow-cli', {
            'firewall_driver': 'openvswitch',
            'of_interface': 'ovs-ofctl',
            'l2_agent_type': constants.AGENT_TYPE_OVS}),
        ('ovs-openflow-native', {
            'firewall_driver': 'openvswitch',
            'of_interface': 'native',
            'l2_agent_type': constants.AGENT_TYPE_OVS}),
        ('linuxbridge-iptables', {
            'firewall_driver': 'iptables',
            'l2_agent_type': constants.AGENT_TYPE_LINUXBRIDGE})]

    # NOTE(toshii): As a firewall_driver can interfere with others,
    # the recommended way to add test is to expand this method, not
    # adding another.
    def test_securitygroup(self):
        """Tests if a security group rules are working, by confirming
        that 0. traffic is allowed when port security is disabled,
             1. connection from outside of allowed security group is blocked
             2. connection from allowed security group is permitted
             3. traffic not explicitly allowed (eg. ICMP) is blocked,
             4. a security group update takes effect,
             5. a remote security group member addition works, and
             6. an established connection stops by deleting a SG rule.
             7. multiple overlapping remote rules work,
             8. test other protocol functionality by using SCTP protocol
             9. test two vms with same mac on the same host in different
                networks
        """
        index_to_sg = [0, 0, 1, 2]
        if self.firewall_driver == 'iptables_hybrid':
            # The iptables_hybrid driver lacks isolation between agents
            index_to_host = [0] * 4
        else:
            index_to_host = [0, 1, 1, 0]

        tenant_uuid = uuidutils.generate_uuid()

        network = self.safe_client.create_network(tenant_uuid)
        self.safe_client.create_subnet(
            tenant_uuid, network['id'], '20.0.0.0/24')

        sgs = [self.safe_client.create_security_group(tenant_uuid)
               for i in range(3)]
        ports = [
            self.safe_client.create_port(tenant_uuid, network['id'],
                                         self.environment.hosts[host].hostname,
                                         security_groups=[],
                                         port_security_enabled=False)
            for host in index_to_host]

        self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[0]['id'], direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NAME_TCP,
            port_range_min=3333, port_range_max=3333)

        vms = [
            self.useFixture(
                machine.FakeFullstackMachine(
                    self.environment.hosts[host],
                    network['id'],
                    tenant_uuid,
                    self.safe_client,
                    neutron_port=ports[port],
                    use_dhcp=True))
            for port, host in enumerate(index_to_host)]

        for vm in vms:
            vm.block_until_boot()

        # 0. check that traffic is allowed when port security is disabled
        self.assert_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3333,
            net_helpers.NetcatTester.TCP)
        self.assert_connection(
            vms[2].namespace, vms[0].namespace, vms[0].ip, 3333,
            net_helpers.NetcatTester.TCP)
        net_helpers.assert_ping(vms[0].namespace, vms[1].ip)
        net_helpers.assert_ping(vms[0].namespace, vms[2].ip)
        net_helpers.assert_ping(vms[1].namespace, vms[2].ip)

        # Apply security groups to the ports
        for port, sg in zip(ports, index_to_sg):
            self.safe_client.client.update_port(
                port['id'],
                body={'port': {'port_security_enabled': True,
                               'security_groups': [sgs[sg]['id']]}})

        # 1. connection from outside of allowed security group is blocked
        netcat = net_helpers.NetcatTester(
            vms[2].namespace, vms[0].namespace, vms[0].ip, 3333,
            net_helpers.NetcatTester.TCP)
        # Wait until port update takes effect on the ports
        common_utils.wait_until_true(
            netcat.test_no_connectivity,
            exception=AssertionError(
                "Still can connect to the VM from different host.")
        )
        netcat.stop_processes()

        # 2. check if connection from allowed security group is permitted
        self.assert_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3333,
            net_helpers.NetcatTester.TCP)

        # 3. check if traffic not explicitly allowed (eg. ICMP) is blocked
        net_helpers.assert_no_ping(vms[0].namespace, vms[1].ip)
        net_helpers.assert_no_ping(vms[0].namespace, vms[2].ip)
        net_helpers.assert_no_ping(vms[1].namespace, vms[2].ip)

        # 4. check if a security group update takes effect
        self.assert_no_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3344,
            net_helpers.NetcatTester.TCP)

        self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[0]['id'], direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NAME_TCP,
            port_range_min=3344, port_range_max=3344)

        self.assert_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3344,
            net_helpers.NetcatTester.TCP)

        # 5. check if a remote security group member addition works
        rule2 = self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[1]['id'], direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NAME_TCP,
            port_range_min=3355, port_range_max=3355)

        self.assert_connection(
            vms[2].namespace, vms[0].namespace, vms[0].ip, 3355,
            net_helpers.NetcatTester.TCP)

        # 6. check if an established connection stops by deleting
        #    the supporting SG rule.
        index_to_host.append(index_to_host[2])
        index_to_sg.append(1)
        ports.append(
            self.safe_client.create_port(tenant_uuid, network['id'],
                                         self.environment.hosts[
                                             index_to_host[-1]].hostname,
                                         security_groups=[sgs[1]['id']]))

        vms.append(
            self.useFixture(
                machine.FakeFullstackMachine(
                    self.environment.hosts[index_to_host[-1]],
                    network['id'],
                    tenant_uuid,
                    self.safe_client,
                    neutron_port=ports[-1],
                    use_dhcp=True)))
        self.assertEqual(5, len(vms))

        vms[4].block_until_boot()

        netcat = net_helpers.NetcatTester(vms[4].namespace,
            vms[0].namespace, vms[0].ip, 3355,
            net_helpers.NetcatTester.TCP)

        self.addCleanup(netcat.stop_processes)
        self.assertTrue(netcat.test_connectivity())

        self.client.delete_security_group_rule(rule2['id'])
        common_utils.wait_until_true(lambda: netcat.test_no_connectivity(),
                                     sleep=8)
        netcat.stop_processes()

        # 7. check if multiple overlapping remote rules work
        self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[1]['id'], direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NAME_TCP,
            port_range_min=3333, port_range_max=3333)
        self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[2]['id'], direction='ingress',
            ethertype=constants.IPv4)

        for i in range(2):
            self.assert_connection(
                vms[0].namespace, vms[1].namespace, vms[1].ip, 3333,
                net_helpers.NetcatTester.TCP)
            self.assert_connection(
                vms[2].namespace, vms[1].namespace, vms[1].ip, 3333,
                net_helpers.NetcatTester.TCP)
            self.assert_connection(
                vms[3].namespace, vms[0].namespace, vms[0].ip, 8080,
                net_helpers.NetcatTester.TCP)

        # 8. check SCTP is supported by security group
        self.assert_no_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3366,
            net_helpers.NetcatTester.SCTP)

        self.safe_client.create_security_group_rule(
            tenant_uuid, sgs[0]['id'],
            remote_group_id=sgs[0]['id'], direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NUM_SCTP,
            port_range_min=3366, port_range_max=3366)

        self.assert_connection(
            vms[1].namespace, vms[0].namespace, vms[0].ip, 3366,
            net_helpers.NetcatTester.SCTP)

        # 9. test two vms with same mac on the same host in different networks
        self._test_overlapping_mac_addresses()

    def _create_vm_on_host(
            self, project_id, network_id, sg_id, host, mac_address=None):
        if mac_address:
            port = self.safe_client.create_port(
                project_id, network_id, host.hostname,
                security_groups=[sg_id], mac_address=mac_address)
        else:
            port = self.safe_client.create_port(
                project_id, network_id, host.hostname,
                security_groups=[sg_id])

        return self.useFixture(
            machine.FakeFullstackMachine(
                host, network_id, project_id, self.safe_client,
                neutron_port=port))

    def _create_three_vms_first_has_static_mac(
            self, project_id, allowed_port, subnet_cidr):
        """Create three vms.

        First VM has a static mac and is placed on first host. Second VM is
        placed on the first host and third VM is placed on second host.
        """
        network = self.safe_client.create_network(project_id)
        self.safe_client.create_subnet(
            project_id, network['id'], subnet_cidr)
        sg = self.safe_client.create_security_group(project_id)

        self.safe_client.create_security_group_rule(
            project_id, sg['id'],
            direction='ingress',
            ethertype=constants.IPv4,
            protocol=constants.PROTO_NAME_TCP,
            port_range_min=allowed_port, port_range_max=allowed_port)

        vms = [self._create_vm_on_host(
            project_id, network['id'], sg['id'], self.environment.hosts[0],
            mac_address="fa:16:3e:de:ad:fe")]

        if self.firewall_driver == 'iptables_hybrid':
            # iptables lack isolation between agents, use only a single host
            vms.extend([
                self._create_vm_on_host(
                    project_id, network['id'], sg['id'],
                    self.environment.hosts[0])
                for _ in range(2)])
        else:
            vms.extend([
                self._create_vm_on_host(
                    project_id, network['id'], sg['id'], host)
                for host in self.environment.hosts[:2]])

        map(lambda vm: vm.block_until_boot(), vms)
        return vms

    def verify_connectivity_between_vms(self, src_vm, dst_vm, protocol, port):
        self.assert_connection(
            src_vm.namespace, dst_vm.namespace, dst_vm.ip, port,
            protocol)

    def verify_no_connectivity_between_vms(
            self, src_vm, dst_vm, protocol, port):
        self.assert_no_connection(
            src_vm.namespace, dst_vm.namespace, dst_vm.ip, port, protocol)

    def _test_overlapping_mac_addresses(self):
        project1 = uuidutils.generate_uuid()
        p1_allowed = 4444

        project2 = uuidutils.generate_uuid()
        p2_allowed = 4445

        p1_vms = self._create_three_vms_first_has_static_mac(
            project1, p1_allowed, '20.0.2.0/24')
        p2_vms = self._create_three_vms_first_has_static_mac(
            project2, p2_allowed, '20.0.3.0/24')

        have_connectivity = [
            (p1_vms[0], p1_vms[1], p1_allowed),
            (p1_vms[1], p1_vms[2], p1_allowed),
            (p2_vms[0], p2_vms[1], p2_allowed),
            (p2_vms[1], p2_vms[2], p2_allowed),
        ]

        for vm1, vm2, port in have_connectivity:
            self.verify_connectivity_between_vms(
                vm1, vm2, net_helpers.NetcatTester.TCP, port)
            self.verify_connectivity_between_vms(
                vm2, vm1, net_helpers.NetcatTester.TCP, port)
            self.verify_no_connectivity_between_vms(
                vm1, vm2, net_helpers.NetcatTester.TCP, port + 1)
            self.verify_no_connectivity_between_vms(
                vm2, vm1, net_helpers.NetcatTester.TCP, port + 1)


text:
package org.sirix.diff;

import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sirix.Holder;
import org.sirix.XmlTestHelper;
import org.sirix.diff.DiffFactory.DiffOptimized;
import org.sirix.exception.SirixException;

/**
 * Test StructuralDiff.
 *
 * @author Johannes Lichtenberger, University of Konstanz
 * @author Sebastian Graf, University of Konstanz
 *
 */
public final class StructuralDiffTest {

  /** {@link Holder} reference. */
  private Holder holder;

  /** {@link DiffObserver} reference. */
  private DiffObserver observer;

  @Before
  public void setUp() throws SirixException {
    DiffTestHelper.setUp();
    holder = Holder.generateWtxAndResourceWithHashes();
    observer = DiffTestHelper.createMock();
  }

  @After
  public void tearDown() throws SirixException {
    XmlTestHelper.closeEverything();
  }

  @Test
  public void testStructuralDiffFirst() throws Exception {
    DiffTestHelper.setUpFirst(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyStructuralDiffFirst(observer);
  }

  @Test
  public void testStructuralDiffOptimizedFirst() throws Exception {
    DiffTestHelper.setUpFirst(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyOptimizedStructuralDiffFirst(observer);
  }

  @Test
  public void testStructuralDiffSecond()
      throws SirixException, InterruptedException, IOException, XMLStreamException {
    DiffTestHelper.setUpSecond(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffSecond(observer);
  }

  @Test
  public void testStructuralDiffOptimizedSecond()
      throws SirixException, IOException, XMLStreamException, InterruptedException {
    DiffTestHelper.setUpSecond(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyOptimizedSecond(observer);
  }

  @Test
  public void testStructuralDiffThird()
      throws SirixException, IOException, XMLStreamException, InterruptedException {
    DiffTestHelper.setUpThird(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffThird(observer);
  }

  @Test
  public void testStructuralDiffOptimizedThird()
      throws SirixException, IOException, XMLStreamException, InterruptedException {
    DiffTestHelper.setUpThird(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyOptimizedThird(observer);
  }

  @Test
  public void testStructuralDiffFourth() throws Exception {
    DiffTestHelper.setUpFourth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffFourth(observer);
  }

  @Test
  public void testStructuralDiffOptimizedFourth() throws Exception {
    DiffTestHelper.setUpFourth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyOptimizedFourth(observer);
  }

  @Test
  public void testStructuralDiffFifth() throws Exception {
    DiffTestHelper.setUpFifth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffFifth(observer);
  }

  @Test
  public void testStructuralDiffOptimizedFifth() throws Exception {
    DiffTestHelper.setUpFifth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyDiffFifth(observer);
  }

  @Test
  public void testStructuralDiffSixth() throws Exception {
    DiffTestHelper.setUpSixth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffSixth(observer);
  }

  @Test
  public void testStructuralDiffOptimizedSixth() throws Exception {
    DiffTestHelper.setUpSixth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.HASHED);
    DiffTestHelper.verifyDiffSixth(observer);
  }

  @Test
  public void testStructuralDiffSeventh() throws Exception {
    DiffTestHelper.setUpSeventh(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffSeventh(observer);
  }

  @Test
  public void testStructuralDiffEighth() throws Exception {
    DiffTestHelper.setUpEighth(holder);
    DiffTestHelper.checkStructuralDiff(holder, observer, DiffOptimized.NO);
    DiffTestHelper.verifyDiffEighth(observer);
  }

}


text:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package com.google.crypto.tink.tinkey;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * Enables a key with some key id in a keyset.
 */
public class EnableKeyCommand extends KeyIdOptions implements Command {
  @Override
  public void run() throws Exception {
    validate();
    enable(outputStream, outFormat, inputStream, inFormat,
        masterKeyUri, credentialPath, keyId);
  }

  /**
   * Enables the key with {@code keyId} in the keyset (using {@code masterKeyUri}
   * {@code credentialPath} to decrypt if it is encrypted).
   * @throws GeneralSecurityException if the key is not found or it is already enabled.
   */
  public static void enable(OutputStream outputStream, String outFormat,
      InputStream inputStream, String inFormat, String masterKeyUri,
      String credentialPath, int keyId) throws Exception {
    TinkeyUtil.manipulateKey(TinkeyUtil.CommandType.ENABLE_KEY, outputStream, outFormat,
        inputStream, inFormat, masterKeyUri, credentialPath, keyId);
  }
}