text:
package org.apache.druid.extendedset.intset;

import com.google.common.collect.Lists;
import junit.framework.Assert;
import org.apache.druid.java.util.common.StringUtils;
import org.junit.Test;

import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;

/**
 */
public class ImmutableConciseSetTest
{
  public static final int NO_COMPLEMENT_LENGTH = -1;

  @Test
  public void testWordIteratorNext1()
  {
    final int[] ints = {1, 2, 3, 4, 5};
    ConciseSet set = new ConciseSet();
    for (int i : ints) {
      set.add(i);
    }
    ImmutableConciseSet iSet = ImmutableConciseSet.newImmutableFromMutable(set);

    ImmutableConciseSet.WordIterator itr = iSet.newWordIterator();
    Assert.assertEquals(0x8000003E, itr.next());

    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testWordIteratorNext2()
  {
    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 100000; i++) {
      set.add(i);

    }
    ImmutableConciseSet iSet = ImmutableConciseSet.newImmutableFromMutable(set);

    ImmutableConciseSet.WordIterator itr = iSet.newWordIterator();
    Assert.assertEquals(0x40000C98, itr.next());
    Assert.assertEquals(0x81FFFFFF, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  /**
   * Advance to middle of a fill
   */
  @Test
  public void testWordIteratorAdvanceTo1()
  {
    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 100000; i++) {
      set.add(i);

    }
    ImmutableConciseSet iSet = ImmutableConciseSet.newImmutableFromMutable(set);

    ImmutableConciseSet.WordIterator itr = iSet.newWordIterator();
    itr.advanceTo(50);
    Assert.assertEquals(1073744998, itr.next());
    Assert.assertEquals(0x81FFFFFF, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  /**
   * Advance past a fill directly to a new literal
   */
  @Test
  public void testWordIteratorAdvanceTo2()
  {
    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 100000; i++) {
      set.add(i);

    }
    ImmutableConciseSet iSet = ImmutableConciseSet.newImmutableFromMutable(set);

    ImmutableConciseSet.WordIterator itr = iSet.newWordIterator();
    itr.advanceTo(3225);
    Assert.assertEquals(0x81FFFFFF, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneLitOneLit()
  {
    int[] words = {-1, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));

    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x40000001, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneLitPureOneFill()
  {
    int[] words = {-1, 0x40000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x40000005, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneLitDirtyOneFill()
  {
    int[] words = {-1, 0x42000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(0x42000004, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneFillOneLit()
  {
    int[] words = {0x40000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x40000005, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneFillPureOneFill()
  {
    int[] words = {0x40000004, 0x40000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x40000009, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactOneFillDirtyOneFill()
  {
    int[] words = {0x40000004, 0x42000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x40000004, itr.next());
    Assert.assertEquals(0x42000004, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroLitZeroLit()
  {
    int[] words = {0x80000000, 0x80000000, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x00000001, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroLitPureZeroFill()
  {
    int[] words = {0x80000000, 0x00000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x00000005, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroLitDirtyZeroFill()
  {
    int[] words = {0x80000000, 0x02000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x80000000, itr.next());
    Assert.assertEquals(0x02000004, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroFillZeroLit()
  {
    int[] words = {0x00000004, 0x80000000, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x00000005, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroFillPureZeroFill()
  {
    int[] words = {0x00000004, 0x00000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x00000009, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactZeroFillDirtyZeroFill()
  {
    int[] words = {0x00000004, 0x02000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x00000004, itr.next());
    Assert.assertEquals(0x02000004, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleOneBitLitZeroLit()
  {
    int[] words = {0x80000001, 0x80000000, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x02000001, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactDoubleOneBitLitZeroLit()
  {
    int[] words = {0x80000003, 0x80000000, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x80000003, itr.next());
    Assert.assertEquals(0x80000000, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleOneBitLitPureZeroFill()
  {
    int[] words = {0x80000001, 0x00000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x02000005, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactDoubleOneBitLitPureZeroFill()
  {
    int[] words = {0x80000003, 0x00000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x80000003, itr.next());
    Assert.assertEquals(0x00000004, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleOneBitLitDirtyZeroFill()
  {
    int[] words = {0x80000001, 0x02000004, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x80000001, itr.next());
    Assert.assertEquals(0x02000004, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleZeroBitLitOneLit()
  {
    int[] words = {0xFFFFFFFE, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x42000001, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactDoubleZeroBitLitOneLit()
  {
    int[] words = {0xFFFFFFEE, -1};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0xFFFFFFEE, itr.next());
    Assert.assertEquals(-1, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleZeroBitLitPureOneFill()
  {
    int[] words = {0xFFFFFFFE, 0x40000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0x42000005, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactDoubleZeroBitLitPureOneFill()
  {
    int[] words = {0xFFFFFFFC, 0x40000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0xFFFFFFFC, itr.next());
    Assert.assertEquals(0x40000004, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactSingleZeroBitLitDirtyOneFill()
  {
    int[] words = {0xFFFFFFFE, 0x42000004};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0xFFFFFFFE, itr.next());
    Assert.assertEquals(0x42000004, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  @Test
  public void testCompactTwoLiterals()
  {
    int[] words = {0xFFFFFFFE, 0xFFEFFEFF};

    ImmutableConciseSet res = ImmutableConciseSet.compact(new ImmutableConciseSet(IntBuffer.wrap(words)));
    ImmutableConciseSet.WordIterator itr = res.newWordIterator();

    Assert.assertEquals(0xFFFFFFFE, itr.next());
    Assert.assertEquals(0xFFEFFEFF, itr.next());
    Assert.assertEquals(itr.hasNext(), false);
  }

  /**
   * Set 1: zero literal, zero fill with flipped bit 33, literal
   * Set 2: zero literal, zero fill with flipped bit 34, literal
   *

   * Testing merge
   */
  @Test
  public void testUnion1()
  {
    final int[] ints1 = {33, 100000};
    final int[] ints2 = {34, 100000};
    List<Integer> expected = Arrays.asList(33, 34, 100000);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: zero literal, zero fill with flipped bit 33, literal
   * Set 2: zero literal, zero fill with flipped bit 34, literal
   *

   * Testing merge
   */
  @Test
  public void testUnion2()
  {
    final int[] ints1 = {33, 100000};
    final int[] ints2 = {34, 200000};
    List<Integer> expected = Arrays.asList(33, 34, 100000, 200000);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: zero fill, one fill
   * Set 2: zero fill, one fill with flipped bit 62
   *

   * Testing merge
   */
  @Test
  public void testUnion3()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 62; i < 10001; i++) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 63; i < 10002; i++) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 62; i < 10002; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: zero literal, one fill with flipped bit 62
   * Set 2: zero literal, literal, one fill, literal
   *

   * Testing merge
   */
  @Test
  public void testUnion4()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 63; i < 1001; i++) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 64; i < 1002; i++) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 63; i < 1002; i++) {
      expected.add(i);
    }

    ConciseSet blah = new ConciseSet();
    for (int i : expected) {
      blah.add(i);
    }
    verifyUnion(expected, sets);
  }

  /**
   * Set 1: literal
   * Set 2: zero fill, zero literal, zero fill with flipped 33 bit, zero fill with flipped 1000000 bit, literal
   * Set3: literal, zero fill with flipped 34th bit, literal
   *

   * Testing merge
   */
  @Test
  public void testUnion5()
  {
    final int[] ints1 = {1, 2, 3, 4, 5};
    final int[] ints2 = {100000, 2405983, 33};
    final int[] ints3 = {0, 4, 5, 34, 333333};
    final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4, 5, 33, 34, 100000, 333333, 2405983);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }
    ConciseSet set3 = new ConciseSet();
    for (int i : ints3) {
      set3.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2),
        ImmutableConciseSet.newImmutableFromMutable(set3)
    );

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: literal
   * Set 2: literal
   *

   * Testing merge
   */
  @Test
  public void testUnion6()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 30; i++) {
      if (i != 28) {
        set1.add(i);
      }
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 30; i++) {
      if (i != 27) {
        set2.add(i);
      }
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 30; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: zero literal, literal, one fill with flipped bit
   * Set 2: zero literal, one fill with flipped bit
   *

   * Testing merge
   */
  @Test
  public void testUnion7()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 64; i < 1005; i++) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 63; i < 99; i++) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 63; i < 1005; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: One fill with flipped 27th bit
   * Set 2: One fill with flipped 28th bit
   *

   * Testing creation of one fill with no flipped bits
   */
  @Test
  public void testUnion8()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 1000; i++) {
      if (i != 27) {
        set1.add(i);
      }
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 1000; i++) {
      if (i != 28) {
        set2.add(i);
      }
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Literal and one fill
   * Set 2: One fill with flipped 28th bit
   *

   * Testing creation of one fill with correct flipped bit
   */
  @Test
  public void testUnion9()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 1000; i++) {
      if (!(i == 27 || i == 28)) {
        set1.add(i);
      }
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 1000; i++) {
      if (i != 28) {
        set2.add(i);
      }
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1000; i++) {
      if (i != 28) {
        expected.add(i);
      }
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Multiple literals
   * Set 2: Multiple literals
   *

   * Testing merge of pure sequences of literals
   */
  @Test
  public void testUnion10()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 1000; i += 2) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 1; i < 1000; i += 2) {
      set2.add(i);
    }
    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Multiple literals
   * Set 2: Zero fill and literal
   *

   * Testing skipping of zero fills
   */
  @Test
  public void testUnion11()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 1000; i += 2) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    set2.add(10000);

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1000; i += 2) {
      expected.add(i);
    }
    expected.add(10000);

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Literal with 4 bits marked
   * Set 2: Zero fill with flipped bit 5
   *

   * Testing merge of literal and zero fill with flipped bit
   */
  @Test
  public void testUnion12()
  {
    final int[] ints1 = {1, 2, 3, 4};
    final int[] ints2 = {5, 1000};
    final List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 1000);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Literal with bit 0
   * Set 2: One fill with flipped bit 0
   *

   * Testing merge of literal and one fill with flipped bit
   */
  @Test
  public void testUnion13()
  {
    List<Integer> expected = Lists.newArrayList();
    final int[] ints1 = {0};

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 1; i < 100; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 100; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Zero fill with flipped bit 0
   * Set 2: One fill with flipped bit 0
   *

   * Testing merge of flipped bits in zero and one fills
   */
  @Test
  public void testUnion14()
  {
    List<Integer> expected = Lists.newArrayList();
    final int[] ints1 = {0, 100};

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 1; i < 100; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i <= 100; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: Zero fill with flipped bit 1
   * Set 2: Literal with 0th bit marked
   * Set 3: One Fill from 1 to 100 with flipped bit 0
   *

   * Testing merge of flipped bits in zero and one fills with a literal
   */
  @Test
  public void testUnion15()
  {
    List<Integer> expected = Lists.newArrayList();
    final int[] ints1 = {1, 100};
    final int[] ints2 = {0};

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }
    ConciseSet set3 = new ConciseSet();
    for (int i = 1; i < 100; i++) {
      set3.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2),
        ImmutableConciseSet.newImmutableFromMutable(set3)
    );

    for (int i = 0; i <= 100; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Testing merge of offset elements
   */
  @Test
  public void testUnion16()
  {
    final int[] ints1 = {1001, 1002, 1003};
    final int[] ints2 = {1034, 1035, 1036};
    List expected = Arrays.asList(1001, 1002, 1003, 1034, 1035, 1036);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    verifyUnion(expected, sets);
  }

  /**
   * Testing merge of same elements
   */
  @Test
  public void testUnion17()
  {
    final int[] ints1 = {1, 2, 3, 4, 5};
    final int[] ints2 = {1, 2, 3, 4, 5};
    List expected = Arrays.asList(1, 2, 3, 4, 5);

    ConciseSet set1 = new ConciseSet();
    for (int i : ints1) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i : ints2) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    verifyUnion(expected, sets);
  }

  @Test
  public void testUnion18()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 1000; i++) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    set2.add(1000);
    set2.add(10000);

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1001; i++) {
      expected.add(i);
    }
    expected.add(10000);

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: one fill, all ones literal
   * Set 2: zero fill, one fill, literal
   */
  @Test
  public void testUnion19()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 93; i++) {
      set1.add(i);
    }
    ConciseSet set2 = new ConciseSet();
    for (int i = 62; i < 1000; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  /**
   * Set 1: literal, one fill, literal
   * Set 2: zero fill, literal that falls within the one fill above, one fill that falls in one fill above, one fill
   */
  @Test
  public void testUnion20()
  {
    List<Integer> expected = Lists.newArrayList();
    ConciseSet set1 = new ConciseSet();
    for (int i = 0; i < 5; i++) {
      set1.add(i);
    }
    for (int i = 31; i < 1000; i++) {
      set1.add(i);
    }

    ConciseSet set2 = new ConciseSet();
    for (int i = 62; i < 68; i++) {
      set2.add(i);
    }
    for (int i = 800; i < 1000; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    for (int i = 0; i < 5; i++) {
      expected.add(i);
    }
    for (int i = 31; i < 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  @Test
  public void testUnion21()
  {
    ConciseSet set1 = new ConciseSet();
    for (int i = 32; i < 93; i++) {
      set1.add(i);
    }

    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 62; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    List<Integer> expected = Lists.newArrayList();
    for (int i = 0; i < 93; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  @Test
  public void testUnion22()
  {
    ConciseSet set1 = new ConciseSet();
    for (int i = 93; i < 1000; i++) {
      set1.add(i);
    }

    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 32; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.newImmutableFromMutable(set1),
        ImmutableConciseSet.newImmutableFromMutable(set2)
    );

    List<Integer> expected = Lists.newArrayList();
    for (int i = 0; i < 32; i++) {
      expected.add(i);
    }
    for (int i = 93; i < 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  @Test
  public void testUnion23()
  {
    ConciseSet set1 = new ConciseSet();
    set1.add(10);
    set1.add(1000);

    ConciseSet set2 = new ConciseSet();
    for (int i = 0; i < 10; i++) {
      set2.add(i);
    }
    for (int i = 11; i < 1000; i++) {
      set2.add(i);
    }

    List<ImmutableConciseSet> sets = Arrays.asList(
        ImmutableConciseSet.compact(ImmutableConciseSet.newImmutableFromMutable(set1)),
        ImmutableConciseSet.compact(ImmutableConciseSet.newImmutableFromMutable(set2))
    );
    List<Integer> expected = new ArrayList<>();
    for (int i = 0; i <= 1000; i++) {
      expected.add(i);
    }

    verifyUnion(expected, sets);
  }

  private void verifyUnion(List<Integer> expected, List<ImmutableConciseSet> sets)
  {
    List<Integer> actual = Lists.newArrayList();
    ImmutableConciseSet set = ImmutableConciseSet.union(sets);
    IntSet.IntIterator itr = set.iterator();
    while (itr.hasNext()) {
      actual.add(itr.next());
    }
    Assert.assertEquals(expected, actual);
  }

  /**
   * Basic complement with no length
   */
  @Test
  public void testComplement1()
  {
    final int[] ints = {1, 100};
    List<Integer> expected = Lists.newArrayList();

    ConciseSet set = new ConciseSet();
    for (int i : ints) {
      set.add(i);
    }

    for (int i = 0; i <= 100; i++) {
      if (i != 1 && i != 100) {
        expected.add(i);
      }
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, NO_COMPLEMENT_LENGTH);
  }

  /**
   * Complement of a single partial word
   */
  @Test
  public void testComplement2()
  {
    List<Integer> expected = Lists.newArrayList();

    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 15; i++) {
      set.add(i);
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, NO_COMPLEMENT_LENGTH);
  }

  /**
   * Complement of a single partial word with a length set in the same word
   */
  @Test
  public void testComplement3()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 21;

    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 15; i++) {
      set.add(i);
    }
    for (int i = 15; i < length; i++) {
      expected.add(i);
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of a single partial word with a length set in a different word
   */
  @Test
  public void testComplement4()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 41;

    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 15; i++) {
      set.add(i);
    }
    for (int i = 15; i < length; i++) {
      expected.add(i);
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of a single partial word with a length set to create a one fill
   */
  @Test
  public void testComplement5()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 1001;

    ConciseSet set = new ConciseSet();
    for (int i = 0; i < 15; i++) {
      set.add(i);
    }
    for (int i = 15; i < length; i++) {
      expected.add(i);
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of words with a length set to create a one fill
   */
  @Test
  public void testComplement6()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 1001;

    ConciseSet set = new ConciseSet();
    for (int i = 65; i <= 100; i++) {
      set.add(i);
    }
    for (int i = 0; i < length; i++) {
      if (i < 65 || i > 100) {
        expected.add(i);
      }
    }

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of 2 words with a length in the second word
   */
  @Test
  public void testComplement7()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 37;

    ConciseSet set = new ConciseSet();
    for (int i = 0; i <= 35; i++) {
      set.add(i);
    }
    expected.add(36);

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of a one literal with a length set to complement the next bit in the next word
   */
  @Test
  public void testComplement8()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 32;

    ConciseSet set = new ConciseSet();
    for (int i = 0; i <= 30; i++) {
      set.add(i);
    }
    expected.add(31);

    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement of a null set with a length
   */
  @Test
  public void testComplement9()
  {
    final List<Integer> lengths = new ArrayList<Integer>();
    lengths.addAll(
        Arrays.asList(
            35,
            31,
            32,
            1,
            0,
            31 * 3,
            1024,
            ConciseSetUtils.MAX_ALLOWED_INTEGER
        )
    );
    final Random random = new Random(701534702L);
    for (int i = 0; i < 5; ++i) {
      lengths.add(random.nextInt(ConciseSetUtils.MAX_ALLOWED_INTEGER + 1));
    }
    final ImmutableConciseSet emptySet = new ImmutableConciseSet();
    for (final int length : lengths) {
      final ImmutableConciseSet complement = ImmutableConciseSet.complement(emptySet, length);
      final IntSet.IntIterator intIterator = complement.iterator();
      for (int i = 0; i < length; i++) {
        final int n = intIterator.next();
        if (i != n) {
          Assert.assertEquals(StringUtils.format("Failure at bit [%d] on length [%d]", i, length), i, n);
        }
      }
      NoSuchElementException ex = null;
      try {
        intIterator.next();
      }
      catch (NoSuchElementException e) {
        ex = e;
      }
      Assert.assertNotNull(ex);
    }
  }

  /**
   * Complement of a null set to create a one fill
   */
  @Test
  public void testComplement10()
  {
    List<Integer> expected = Lists.newArrayList();
    final int length = 93;

    for (int i = 0; i < length; i++) {
      expected.add(i);
    }

    ImmutableConciseSet testSet = new ImmutableConciseSet();

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement with correct last index
   */
  @Test
  public void testComplement11()
  {
    List<Integer> expected = Lists.newArrayList();
    int length = 18930;
    for (int i = 0; i < 500; i++) {
      expected.add(i);
    }
    for (int i = 18881; i < length; i++) {
      expected.add(i);
    }

    ConciseSet set = new ConciseSet();
    for (int i = 500; i <= 18880; i++) {
      set.add(i);
    }
    ImmutableConciseSet testSet = ImmutableConciseSet.newImmutableFromMutable(set);

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement with empty set and length in first block
   */
  @Test
  public void testComplement12()
  {
    List<Integer> expected = Lists.newArrayList();
    int length = 10;
    for (int i = 0; i < 10; i++) {
      expected.add(i);
    }

    ImmutableConciseSet testSet = new ImmutableConciseSet();

    verifyComplement(expected, testSet, length);
  }

  /**
   * Complement with empty list of some length
   */
  @Test
  public void testComplement13()
  {
    List<Integer> expected = Lists.newArrayList();
    int length = 10;
    for (int i = 0; i < length; i++) {
      expected.add(i);
    }
    ImmutableConciseSet testSet = new ImmutableConciseSet();

    verifyComplement(expected, testSet, length);
  }

  private void verifyComplement(List<Integer> expected, ImmutableConciseSet set, int endIndex)
  {
    List<Integer> actual = Lists.newArrayList();

    ImmutableConciseSet res;
    if (endIndex == NO_COMPLEMENT_LENGTH) {
      res = ImmutableConciseSet.complement(set);
    } else {
      res = ImmutableConciseSet.complement(set, endIndex);
    }

    IntSet.IntIterator itr = res.iterator();
    while (itr.hasNext()) {
      actual.add(itr.next());
    }
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void testContains()
  {
    final ConciseSet conciseSet = new ConciseSet();
    final Random random = new Random(543167436715430L);
    final Set<Integer> integerSet = new HashSet<>();
    int max = -1;
    for (int i = 0; i < 100; ++i) {
      final int j = random.nextInt(1 << 20);
      integerSet.add(j);
      conciseSet.add(j);
      if (j > max) {
        max = j;
      }
    }
    final ImmutableConciseSet immutableConciseSet = ImmutableConciseSet.newImmutableFromMutable(conciseSet);
    for (int i = 0; i < max + 10; ++i) {
      final String s = Integer.toString(i);
      Assert.assertEquals(s, integerSet.contains(i), conciseSet.contains(i));
      Assert.assertEquals(s, integerSet.contains(i), immutableConciseSet.contains(i));
    }
  }
}


text:
<ivysettings>
	<property name="local-m2-dir" value="${user.home}/.m2/repository/" />
	<resolvers>
		<chain name="projectRepos">
			<filesystem name="local-m2-repo" m2compatible="true" local="true">
				<artifact pattern="${local-m2-dir}/[organisation]/[module]/[revision]/[module]-[revision].[ext]" />
				<ivy pattern="${local-m2-dir}/[organisation]/[module]/[revision]/[module]-[revision].pom" />
			</filesystem>
			<filesystem name="projectLocalRepo">
				<ivy pattern="${ivy.settings.dir}/ivy-repo/[organization]-[module]-[revision].xml" />
			</filesystem>
			<ibiblio name="maven-repo2" m2compatible="true" root="http://repo2.maven.org/maven2" />
		</chain>
	</resolvers>
	<settings defaultResolver="projectRepos" validate="false" />
	<caches defaultCacheDir="${ivy.basedir}/ivyCache" />
</ivysettings>

redpajama_set_name: RedPajamaGithub


text:
namespace voxblox {

template <typename VoxelType>
class Interpolator {
 public:
  typedef std::shared_ptr<Interpolator> Ptr;

  explicit Interpolator(const Layer<VoxelType>* layer);

  bool getGradient(const Point& pos, Point* grad,
                   const bool interpolate = false) const;

  bool getDistance(const Point& pos, FloatingPoint* distance,
                   bool interpolate = false) const;

  bool getVoxel(const Point& pos, VoxelType* voxel,
                bool interpolate = false) const;

  // This tries to use whatever information is available to interpolate the
  // distance and gradient -- if only one side is available, for instance,
  // this will still estimate a 1-sided gradient. Should give the same results
  // as getGradient() and getDistance() if all neighbors are filled.
  bool getAdaptiveDistanceAndGradient(const Point& pos, FloatingPoint* distance,
                                      Point* grad) const;

  // Without interpolation.
  bool getNearestDistanceAndWeight(const Point& pos, FloatingPoint* distance,
                                   float* weight) const;

 private:
  bool setIndexes(const Point& pos, BlockIndex* block_index,
                  InterpIndexes* voxel_indexes) const;

  // Q vector from http://spie.org/samples/PM159.pdf
  // Relates the interpolation distance of any arbitrary point inside a voxel
  // to the values of the voxel corners.
  void getQVector(const Point& voxel_pos, const Point& pos,
                  InterpVector* q_vector) const;

  bool getVoxelsAndQVector(const BlockIndex& block_index,
                           const InterpIndexes& voxel_indexes, const Point& pos,
                           const VoxelType** voxels,
                           InterpVector* q_vector) const;

  bool getVoxelsAndQVector(const Point& pos, const VoxelType** voxels,
                           InterpVector* q_vector) const;

  bool getInterpDistance(const Point& pos, FloatingPoint* distance) const;

  bool getNearestDistance(const Point& pos, FloatingPoint* distance) const;

  bool getInterpVoxel(const Point& pos, VoxelType* voxel) const;

  bool getNearestVoxel(const Point& pos, VoxelType* voxel) const;

  // Allow this class to be templated on all kinds of voxels.
  static FloatingPoint getVoxelDistance(const VoxelType& voxel);
  static float getVoxelWeight(const VoxelType& voxel);
  // Returns true if the voxel should be used in interpolation/gradient
  // calculation. False otherwise.
  static bool isVoxelValid(const VoxelType& voxel);
  static uint8_t getRed(const VoxelType& voxel);
  static uint8_t getBlue(const VoxelType& voxel);
  static uint8_t getGreen(const VoxelType& voxel);
  static uint8_t getAlpha(const VoxelType& voxel);

  template <typename TGetter>
  static FloatingPoint interpMember(const InterpVector& q_vector,
                                    const VoxelType** voxels,
                                    TGetter (*getter)(const VoxelType&));

  static VoxelType interpVoxel(const InterpVector& q_vector,
                               const VoxelType** voxels);

  const Layer<VoxelType>* layer_;
};

}  // namespace voxblox

#endif  // VOXBLOX_INTERPOLATOR_INTERPOLATOR_H_

#include "voxblox/interpolator/interpolator_inl.h"


text:
//
//  AppDelegate.m
//  ProjectEnter
//
//  Created by 邵银岭 on 15/7/31.
//  Copyright (c) 2015年 邵银岭. All rights reserved.
//

#import "UIImage+Image.h"

@implementation UIImage (Image)

/**
 *  不渲染图片
 */
+ (instancetype)imageWithOriginRenderingName:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return image;
}

+ (instancetype) imageWithRect:(CGRect)rect image:(UIImage *)image
{
    //开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);

    //描述路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];

    //把路径设置为裁剪区域
    [path addClip];

    //绘制图片
    [image drawAtPoint:CGPointZero];

    //从上下文获得图片
    image = UIGraphicsGetImageFromCurrentImageContext();

    //关闭上下文
    UIGraphicsEndImageContext();

    return image;
}

+ (instancetype) imageWithCircleBorderWH:(CGFloat)borderWH borderColor:(UIColor *)color image:(UIImage *)image
{

    CGFloat imageWH = image.size.width;

    //开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);

    //描述边框区域
    CGFloat rectWH = imageWH + 2 * borderWH;
    CGRect rect = CGRectMake(0, 0, rectWH , rectWH);

    //描述边框路径
    UIBezierPath *bigPath = [UIBezierPath bezierPathWithOvalInRect:rect];

    //边框颜色
    [color set];

    //把边框画出来
    [bigPath fill];

    // 裁剪区域
    CGRect clipRect = CGRectMake(borderWH, borderWH, imageWH, imageWH);

    //描述裁减路径
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:clipRect];
    [clipPath addClip];

    //绘制图片
    [image drawAtPoint:CGPointZero];

    //从上下文获得图片
    image = UIGraphicsGetImageFromCurrentImageContext();

    //关闭上下文
    UIGraphicsEndImageContext();

    return image;
}

@end


text:
package com.scand.realmbrowser.breadcrumbs;

import com.scand.realmbrowser.breadcrumbs.StateHolder;

/**
 * Created by amykh on 04.08.2015.
 */
public interface IOnBreadCrumbListener {
    void onStateChanged(StateHolder state);
}


text:
#ifndef _ASM_POWERPC_BOOK3S_64_HASH_H
#define _ASM_POWERPC_BOOK3S_64_HASH_H
#ifdef __KERNEL__

/*
 * Common bits between 4K and 64K pages in a linux-style PTE.
 * Additional bits may be defined in pgtable-hash64-*.h
 *
 * Note: We only support user read/write permissions. Supervisor always
 * have full read/write to pages above PAGE_OFFSET (pages below that
 * always use the user access permissions).
 *
 * We could create separate kernel read-only if we used the 3 PP bits
 * combinations that newer processors provide but we currently don't.
 */
#define H_PAGE_BUSY		0x00800 /* software: PTE & hash are busy */
#define H_PTE_NONE_MASK		_PAGE_HPTEFLAGS
#define H_PAGE_F_GIX_SHIFT	57
#define H_PAGE_F_GIX		(7ul << 57)	/* HPTE index within HPTEG */
#define H_PAGE_F_SECOND		(1ul << 60)	/* HPTE is in 2ndary HPTEG */
#define H_PAGE_HASHPTE		(1ul << 61)	/* PTE has associated HPTE */

#ifdef CONFIG_PPC_64K_PAGES
#include <asm/book3s/64/hash-64k.h>
#else
#include <asm/book3s/64/hash-4k.h>
#endif

/*
 * Size of EA range mapped by our pagetables.
 */
#define H_PGTABLE_EADDR_SIZE	(H_PTE_INDEX_SIZE + H_PMD_INDEX_SIZE + \
				 H_PUD_INDEX_SIZE + H_PGD_INDEX_SIZE + PAGE_SHIFT)
#define H_PGTABLE_RANGE		(ASM_CONST(1) << H_PGTABLE_EADDR_SIZE)

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
/*
 * only with hash we need to use the second half of pmd page table
 * to store pointer to deposited pgtable_t
 */
#define H_PMD_CACHE_INDEX	(H_PMD_INDEX_SIZE + 1)
#else
#define H_PMD_CACHE_INDEX	H_PMD_INDEX_SIZE
#endif
/*
 * Define the address range of the kernel non-linear virtual area
 */
#define H_KERN_VIRT_START ASM_CONST(0xD000000000000000)
#define H_KERN_VIRT_SIZE	ASM_CONST(0x0000100000000000)

/*
 * The vmalloc space starts at the beginning of that region, and
 * occupies half of it on hash CPUs and a quarter of it on Book3E
 * (we keep a quarter for the virtual memmap)
 */
#define H_VMALLOC_START	H_KERN_VIRT_START
#define H_VMALLOC_SIZE	(H_KERN_VIRT_SIZE >> 1)
#define H_VMALLOC_END	(H_VMALLOC_START + H_VMALLOC_SIZE)

/*
 * Region IDs
 */
#define REGION_SHIFT		60UL
#define REGION_MASK		(0xfUL << REGION_SHIFT)
#define REGION_ID(ea)		(((unsigned long)(ea)) >> REGION_SHIFT)

#define VMALLOC_REGION_ID	(REGION_ID(H_VMALLOC_START))
#define KERNEL_REGION_ID	(REGION_ID(PAGE_OFFSET))
#define VMEMMAP_REGION_ID	(0xfUL)	/* Server only */
#define USER_REGION_ID		(0UL)

/*
 * Defines the address of the vmemap area, in its own region on
 * hash table CPUs.
 */
#define H_VMEMMAP_BASE		(VMEMMAP_REGION_ID << REGION_SHIFT)

#ifdef CONFIG_PPC_MM_SLICES
#define HAVE_ARCH_UNMAPPED_AREA
#define HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
#endif /* CONFIG_PPC_MM_SLICES */

/* PTEIDX nibble */
#define _PTEIDX_SECONDARY	0x8
#define _PTEIDX_GROUP_IX	0x7

#define H_PMD_BAD_BITS		(PTE_TABLE_SIZE-1)
#define H_PUD_BAD_BITS		(PMD_TABLE_SIZE-1)

#ifndef __ASSEMBLY__
#define	hash__pmd_bad(pmd)		(pmd_val(pmd) & H_PMD_BAD_BITS)
#define	hash__pud_bad(pud)		(pud_val(pud) & H_PUD_BAD_BITS)
static inline int hash__pgd_bad(pgd_t pgd)
{
	return (pgd_val(pgd) == 0);
}

extern void hpte_need_flush(struct mm_struct *mm, unsigned long addr,
			    pte_t *ptep, unsigned long pte, int huge);
extern unsigned long htab_convert_pte_flags(unsigned long pteflags);
/* Atomic PTE updates */
static inline unsigned long hash__pte_update(struct mm_struct *mm,
					 unsigned long addr,
					 pte_t *ptep, unsigned long clr,
					 unsigned long set,
					 int huge)
{
	__be64 old_be, tmp_be;
	unsigned long old;

	__asm__ __volatile__(
	"1:	ldarx	%0,0,%3		# pte_update\n\
	and.	%1,%0,%6\n\
	bne-	1b \n\
	andc	%1,%0,%4 \n\
	or	%1,%1,%7\n\
	stdcx.	%1,0,%3 \n\
	bne-	1b"
	: "=&r" (old_be), "=&r" (tmp_be), "=m" (*ptep)
	: "r" (ptep), "r" (cpu_to_be64(clr)), "m" (*ptep),
	  "r" (cpu_to_be64(H_PAGE_BUSY)), "r" (cpu_to_be64(set))
	: "cc" );
	/* huge pages use the old page table lock */
	if (!huge)
		assert_pte_locked(mm, addr);

	old = be64_to_cpu(old_be);
	if (old & H_PAGE_HASHPTE)
		hpte_need_flush(mm, addr, ptep, old, huge);

	return old;
}

/* Set the dirty and/or accessed bits atomically in a linux PTE, this
 * function doesn't need to flush the hash entry
 */
static inline void hash__ptep_set_access_flags(pte_t *ptep, pte_t entry)
{
	__be64 old, tmp, val, mask;

	mask = cpu_to_be64(_PAGE_DIRTY | _PAGE_ACCESSED | _PAGE_READ | _PAGE_WRITE |
			   _PAGE_EXEC | _PAGE_SOFT_DIRTY);

	val = pte_raw(entry) & mask;

	__asm__ __volatile__(
	"1:	ldarx	%0,0,%4\n\
		and.	%1,%0,%6\n\
		bne-	1b \n\
		or	%0,%3,%0\n\
		stdcx.	%0,0,%4\n\
		bne-	1b"
	:"=&r" (old), "=&r" (tmp), "=m" (*ptep)
	:"r" (val), "r" (ptep), "m" (*ptep), "r" (cpu_to_be64(H_PAGE_BUSY))
	:"cc");
}

static inline int hash__pte_same(pte_t pte_a, pte_t pte_b)
{
	return (((pte_raw(pte_a) ^ pte_raw(pte_b)) & ~cpu_to_be64(_PAGE_HPTEFLAGS)) == 0);
}

static inline int hash__pte_none(pte_t pte)
{
	return (pte_val(pte) & ~H_PTE_NONE_MASK) == 0;
}

/* This low level function performs the actual PTE insertion
 * Setting the PTE depends on the MMU type and other factors. It's
 * an horrible mess that I'm not going to try to clean up now but
 * I'm keeping it in one place rather than spread around
 */
static inline void hash__set_pte_at(struct mm_struct *mm, unsigned long addr,
				  pte_t *ptep, pte_t pte, int percpu)
{
	/*
	 * Anything else just stores the PTE normally. That covers all 64-bit
	 * cases, and 32-bit non-hash with 32-bit PTEs.
	 */
	*ptep = pte;
}

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
extern void hpte_do_hugepage_flush(struct mm_struct *mm, unsigned long addr,
				   pmd_t *pmdp, unsigned long old_pmd);
#else
static inline void hpte_do_hugepage_flush(struct mm_struct *mm,
					  unsigned long addr, pmd_t *pmdp,
					  unsigned long old_pmd)
{
	WARN(1, "%s called with THP disabled\n", __func__);
}
#endif /* CONFIG_TRANSPARENT_HUGEPAGE */

extern int hash__map_kernel_page(unsigned long ea, unsigned long pa,
			     unsigned long flags);
extern int __meminit hash__vmemmap_create_mapping(unsigned long start,
					      unsigned long page_size,
					      unsigned long phys);
extern void hash__vmemmap_remove_mapping(unsigned long start,
				     unsigned long page_size);
#endif /* !__ASSEMBLY__ */
#endif /* __KERNEL__ */
#endif /* _ASM_POWERPC_BOOK3S_64_HASH_H */


text:
#ifndef __YAJL_BUF_H__
#define __YAJL_BUF_H__

/**
 * yajl_buf is a buffer with exponential growth.  the buffer ensures that
 * you are always null padded.
 */
typedef struct yajl_buf_t * yajl_buf;

/* allocate a new buffer */
yajl_buf yajl_buf_alloc(void);

/* free the buffer */
void yajl_buf_free(yajl_buf buf);

/* append a number of bytes to the buffer */
void yajl_buf_append(yajl_buf buf, const void * data, unsigned int len);

/* empty the buffer */
void yajl_buf_clear(yajl_buf buf);

/* get a pointer to the beginning of the buffer */
const unsigned char * yajl_buf_data(yajl_buf buf);

/* get the length of the buffer */
unsigned int yajl_buf_len(yajl_buf buf);

/* truncate the buffer */
void yajl_buf_truncate(yajl_buf buf, unsigned int len);

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BlackBox.Service;
using EbInstanceModel;
using IFC2X3;

namespace BlackBox.Predefined
{
    public partial class BbProject : BbProduct
    {

        private IfcProject _ifcProject;

        [EarlyBindingInstance]
        public override IfcObject IfcObject {
            get { return _ifcProject; }
            protected set
            {
                base.IfcObject = _ifcProject = value as IfcProject;
            }
        }

        //protected BbProject()
        //{
        //}

        //protected BbProject(string name)
        //    : this(Guid.NewGuid(), name, null, null, null, null)
        //{
        //}

        protected BbProject(IfcProject ifcProject)
        {
            _ifcProject = ifcProject;
        }

        protected BbProject(Guid guid, string name, string description, string objectType, string longname, string phase)
            //: this()
        {
            _ifcProject = new IfcProject
            {
                GlobalId = IfcGloballyUniqueId.ConvertToIfcGuid(guid),
                OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
                Name = name,
                Description = description,
                ObjectType = objectType,
                LongName = longname,
                Phase = phase,
                RepresentationContexts = new List<IfcRepresentationContext>(),
                UnitsInContext = BbHeaderSetting.Setting3D.IfcUnitAssignment,
            };
            _ifcProject.RepresentationContexts.Add(BbHeaderSetting.Setting3D.GeometricRepresentationContext);
        }

        public static void Retrieve()
        {
            var collection = EarlyBindingInstanceModel.GetDataByType("IfcProject");
            //if (collection.Count <= 0) throw new InvalidDataException();

            //if (collection.Count != 1)
            //    throw new InvalidDataException();

            //var theItem = collection.First();

            //var proj = theItem.Value as IfcProject;
            //var sProj = new BbProject(proj);
            //BbInstanceDB.Add(sProj);
            //return sProj;

            foreach (var sproject in collection.Select(kvp => kvp.Value).OfType<IfcProject>().Select(project => new BbProject(project)))
            {
                BbInstanceDB.AddToImport(sproject);
            }

        }

        public static BbProject Create(string name)
        {
            return Create(Guid.NewGuid(), name, null, null, null, null) ;
        }

        public static BbProject Create(Guid guid, string name, string description, string objectType, string longname, string phase)
        {
            var p = new BbProject(guid, name, description, objectType, longname, phase);
            BbInstanceDB.AddToExport(p);
            return p;
        }
    }
}


text:
"""Magnum base exception handling.

Includes decorator for re-raising Magnum-type exceptions.

"""

import functools
import json
import sys
import uuid

from keystoneclient import exceptions as keystone_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
import pecan
import six
import wsme

from magnum.common import safe_utils
from magnum.i18n import _
from magnum.i18n import _LE

LOG = logging.getLogger(__name__)

CONF = cfg.CONF

try:
    CONF.import_opt('fatal_exception_format_errors',
                    'oslo_versionedobjects.exception')
except cfg.NoSuchOptError as e:
    # Note:work around for magnum run against master branch
    # in devstack gate job, as magnum not branched yet
    # verisonobjects kilo/master different version can
    # cause issue here. As it changed import group. So
    # add here before branch to prevent gate failure.
    # Bug: #1447873
    CONF.import_opt('fatal_exception_format_errors',
                    'oslo_versionedobjects.exception',
                    group='oslo_versionedobjects')

def wrap_exception(notifier=None, event_type=None):
    """This decorator wraps a method to catch any exceptions.

    It logs the exception as well as optionally sending
    it to the notification system.
    """
    def inner(f):
        def wrapped(self, context, *args, **kw):
            # Don't store self or context in the payload, it now seems to
            # contain confidential information.
            try:
                return f(self, context, *args, **kw)
            except Exception as e:
                with excutils.save_and_reraise_exception():
                    if notifier:
                        call_dict = safe_utils.getcallargs(f, context,
                                                           *args, **kw)
                        payload = dict(exception=e,
                                       private=dict(args=call_dict)
                                       )

                        temp_type = event_type
                        if not temp_type:
                            # If f has multiple decorators, they must use
                            # functools.wraps to ensure the name is
                            # propagated.
                            temp_type = f.__name__

                        notifier.error(context, temp_type, payload)

        return functools.wraps(f)(wrapped)
    return inner

OBFUSCATED_MSG = _('Your request could not be handled '
                   'because of a problem in the server. '
                   'Error Correlation id is: %s')

def wrap_controller_exception(func, func_server_error, func_client_error):
    """This decorator wraps controllers methods to handle exceptions:

    - if an unhandled Exception or a MagnumException with an error code >=500
    is catched, raise a http 5xx ClientSideError and correlates it with a log
    message

    - if a MagnumException is catched and its error code is <500, raise a http
    4xx and logs the excp in debug mode

    """
    @functools.wraps(func)
    def wrapped(*args, **kw):
        try:
            return func(*args, **kw)
        except Exception as excp:
            if isinstance(excp, MagnumException):
                http_error_code = excp.code
            else:
                http_error_code = 500

            if http_error_code >= 500:
                # log the error message with its associated
                # correlation id
                log_correlation_id = str(uuid.uuid4())
                LOG.error(_LE("%(correlation_id)s:%(excp)s") %
                          {'correlation_id': log_correlation_id,
                           'excp': str(excp)})
                # raise a client error with an obfuscated message
                func_server_error(log_correlation_id, http_error_code)
            else:
                # raise a client error the original message
                LOG.debug(excp)
                func_client_error(excp, http_error_code)
    return wrapped

def wrap_wsme_controller_exception(func):
    """This decorator wraps wsme controllers to handle exceptions."""
    def _func_server_error(log_correlation_id, status_code):
        raise wsme.exc.ClientSideError(
            six.text_type(OBFUSCATED_MSG % log_correlation_id), status_code)

    def _func_client_error(excp, status_code):
        raise wsme.exc.ClientSideError(six.text_type(excp), status_code)

    return wrap_controller_exception(func,
                                     _func_server_error,
                                     _func_client_error)

def wrap_pecan_controller_exception(func):
    """This decorator wraps pecan controllers to handle exceptions."""
    def _func_server_error(log_correlation_id, status_code):
        pecan.response.status = status_code
        pecan.response.text = six.text_type(OBFUSCATED_MSG %
                                            log_correlation_id)

    def _func_client_error(excp, status_code):
        pecan.response.status = status_code
        pecan.response.text = six.text_type(excp)
        pecan.response.content_type = None

    return wrap_controller_exception(func,
                                     _func_server_error,
                                     _func_client_error)

def wrap_keystone_exception(func):
    """Wrap keystone exceptions and throw Magnum specific exceptions."""
    @functools.wraps(func)
    def wrapped(*args, **kw):
        try:
            return func(*args, **kw)
        except keystone_exceptions.AuthorizationFailure:
            raise AuthorizationFailure(
                client=func.__name__, message="reason: %s" % sys.exc_info()[1])
        except keystone_exceptions.ClientException:
            raise AuthorizationFailure(
                client=func.__name__,
                message="unexpected keystone client error occurred: %s"
                        % sys.exc_info()[1])
    return wrapped

class MagnumException(Exception):
    """Base Magnum Exception

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.

    """
    message = _("An unknown exception occurred.")
    code = 500

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs and hasattr(self, 'code'):
            self.kwargs['code'] = self.code

        if message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception as e:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception(_LE('Exception in string format operation, '
                              'kwargs: %s') % kwargs)
            try:
                if CONF.fatal_exception_format_errors:
                    raise e
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise e

        super(MagnumException, self).__init__(self.message)

    def __str__(self):
        if six.PY3:
            return self.message
        return self.message.encode('utf-8')

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)

class ObjectNotFound(MagnumException):
    message = _("The %(name)s %(id)s could not be found.")

class ObjectNotUnique(MagnumException):
    message = _("The %(name)s already exists.")

class ResourceNotFound(ObjectNotFound):
    message = _("The %(name)s resource %(id)s could not be found.")
    code = 404

class ResourceExists(ObjectNotUnique):
    message = _("The %(name)s resource already exists.")
    code = 409

class AuthorizationFailure(MagnumException):
    message = _("%(client)s connection failed. %(message)s")

class UnsupportedObjectError(MagnumException):
    message = _('Unsupported object type %(objtype)s')

class IncompatibleObjectVersion(MagnumException):
    message = _('Version %(objver)s of %(objname)s is not supported')

class OrphanedObjectError(MagnumException):
    message = _('Cannot call %(method)s on orphaned %(objtype)s object')

class Invalid(MagnumException):
    message = _("Unacceptable parameters.")
    code = 400

class InvalidUUID(Invalid):
    message = _("Expected a uuid but received %(uuid)s.")

class InvalidName(Invalid):
    message = _("Expected a name but received %(uuid)s.")

class InvalidDiscoveryURL(Invalid):
    message = _("Received invalid discovery URL '%(discovery_url)s' for "
                "discovery endpoint '%(discovery_endpoint)s'.")

class GetDiscoveryUrlFailed(MagnumException):
    message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")

class InvalidUuidOrName(Invalid):
    message = _("Expected a name or uuid but received %(uuid)s.")

class InvalidIdentity(Invalid):
    message = _("Expected an uuid or int but received %(identity)s.")

class InvalidCsr(Invalid):
    message = _("Received invalid csr %(csr)s.")

class HTTPNotFound(ResourceNotFound):
    pass

class Conflict(MagnumException):
    message = _('Conflict.')
    code = 409

class InvalidState(Conflict):
    message = _("Invalid resource state.")

# Cannot be templated as the error syntax varies.
# msg needs to be constructed when raised.
class InvalidParameterValue(Invalid):
    message = _("%(err)s")

class InstanceNotFound(ResourceNotFound):
    message = _("Instance %(instance)s could not be found.")

class PatchError(Invalid):
    message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")

class NotAuthorized(MagnumException):
    message = _("Not authorized.")
    code = 403

class PolicyNotAuthorized(NotAuthorized):
    message = _("Policy doesn't allow %(action)s to be performed.")

class NotAcceptable(MagnumException):
    # TODO(yuntongjin): We need to set response headers
    # in the API for this exception
    message = _("Request not acceptable.")
    code = 406

class InvalidMAC(Invalid):
    message = _("Expected a MAC address but received %(mac)s.")

class ConfigInvalid(MagnumException):
    message = _("Invalid configuration file. %(error_msg)s")

class SSHConnectFailed(MagnumException):
    message = _("Failed to establish SSH connection to host %(host)s.")

class FileSystemNotSupported(MagnumException):
    message = _("Failed to create a file system. "
                "File system %(fs)s is not supported.")

class BayModelNotFound(ResourceNotFound):
    message = _("Baymodel %(baymodel)s could not be found.")

class BayModelAlreadyExists(Conflict):
    message = _("A baymodel with UUID %(uuid)s already exists.")

class BayModelReferenced(Invalid):
    message = _("Baymodel %(baymodel)s is referenced by one or multiple bays.")

class BaymodelPublishDenied(NotAuthorized):
    message = _("Not authorized to set public flag for baymodel.")

class BayNotFound(ResourceNotFound):
    message = _("Bay %(bay)s could not be found.")

class BayAlreadyExists(Conflict):
    message = _("A bay with UUID %(uuid)s already exists.")

class ContainerNotFound(ResourceNotFound):
    message = _("Container %(container)s could not be found.")

class ContainerAlreadyExists(Conflict):
    message = _("A container with UUID %(uuid)s already exists.")

class PodNotFound(ResourceNotFound):
    message = _("Pod %(pod)s could not be found.")

class PodAlreadyExists(Conflict):
    message = _("A pod with UUID %(uuid)s already exists.")

class PodListNotFound(ResourceNotFound):
    message = _("Pod list could not be found for Bay %(bay_uuid)s.")

class PodCreationFailed(Invalid):
    message = _("Pod creation failed in Bay %(bay_uuid)s.")

class ReplicationControllerNotFound(ResourceNotFound):
    message = _("ReplicationController %(rc)s could not be found.")

class ReplicationControllerAlreadyExists(Conflict):
    message = _("A ReplicationController with UUID %(uuid)s already exists.")

class ReplicationControllerListNotFound(ResourceNotFound):
    message = _("ReplicationController list could not be found"
                " for Bay %(bay_uuid)s.")

class ReplicationControllerCreationFailed(Invalid):
    message = _("ReplicationController creation failed"
                " for Bay %(bay_uuid)s.")

class ServiceNotFound(ResourceNotFound):
    message = _("Service %(service)s could not be found.")

class ServiceAlreadyExists(Conflict):
    message = _("A service with UUID %(uuid)s already exists.")

class ServiceListNotFound(ResourceNotFound):
    message = _("Service list could not be found for Bay %(bay_uuid)s.")

class ServiceCreationFailed(Invalid):
    message = _("Service creation failed for Bay %(bay_uuid)s.")

class ContainerException(Exception):
    pass

class NotSupported(MagnumException):
    message = _("%(operation)s is not supported.")
    code = 400

class BayTypeNotSupported(MagnumException):
    message = _("Bay type (%(server_type)s, %(os)s, %(coe)s)"
                " not supported.")

class BayTypeNotEnabled(MagnumException):
    message = _("Bay type (%(server_type)s, %(os)s, %(coe)s)"
                " not enabled.")

class RequiredParameterNotProvided(MagnumException):
    message = _("Required parameter %(heat_param)s not provided.")

class Urllib2InvalidScheme(MagnumException):
    message = _("The urllib2 URL %(url)s has an invalid scheme.")

class OperationInProgress(Invalid):
    message = _("Bay %(bay_name)s already has an operation in progress.")

class ImageNotFound(ResourceNotFound):
    """The code here changed to 400 according to the latest document."""
    message = _("Image %(image_id)s could not be found.")
    code = 400

class ImageNotAuthorized(MagnumException):
    message = _("Not authorized for image %(image_id)s.")

class OSDistroFieldNotFound(ResourceNotFound):
    """The code here changed to 400 according to the latest document."""
    message = _("Image %(image_id)s doesn't contain os_distro field.")
    code = 400

class KubernetesAPIFailed(MagnumException):
    def __init__(self, message=None, err=None, **kwargs):
        if err:
            if err.body:
                message = json.loads(err.body)['message']
            else:
                message = err.reason
            self.__class__.code = err.status
        else:
            self.__class__.code = kwargs.get('code')
        super(KubernetesAPIFailed, self).__init__(message, **kwargs)

class X509KeyPairNotFound(ResourceNotFound):
    message = _("A key pair %(keypair)s could not be found.")

class X509KeyPairAlreadyExists(Conflict):
    message = _("A key pair with UUID %(uuid)s already exists.")

class CertificateStorageException(MagnumException):
    message = _("Could not store certificate: %(msg)s")

class CertificateValidationError(Invalid):
    message = _("Extension '%(extension)s' not allowed")

class KeyPairNotFound(ResourceNotFound):
    message = _("Unable to find keypair %(keypair)s.")

class MagnumServiceNotFound(ResourceNotFound):
    message = _("A magnum service %(magnum_service_id)s could not be found.")

class MagnumServiceAlreadyExists(Conflict):
    message = _("A magnum service with ID %(id)s already exists.")

class UnsupportedK8sQuantityFormat(MagnumException):
    message = _("Unsupported quantity format for k8s bay.")

class UnsupportedDockerQuantityFormat(MagnumException):
    message = _("Unsupported quantity format for Swarm bay.")

class FlavorNotFound(ResourceNotFound):
    """The code here changed to 400 according to the latest document."""
    message = _("Unable to find flavor %(flavor)s.")
    code = 400

class NetworkNotFound(ResourceNotFound):
    """The code here changed to 400 according to the latest document."""
    message = _("Unable to find network %(network)s.")
    code = 400

class TrustCreateFailed(MagnumException):
    message = _("Failed to create trust for trustee %(trustee_user_id)s.")

class TrustDeleteFailed(MagnumException):
    message = _("Failed to delete trust %(trust_id)s.")

class TrusteeCreateFailed(MagnumException):
    message = _("Failed to create trustee %(username)s "
                "in domain %(domain_id)s")

class TrusteeDeleteFailed(MagnumException):
    message = _("Failed to delete trustee %(trustee_id)s")

class QuotaAlreadyExists(Conflict):
    message = _("Quota for project %(project_id)s already exists "
                "for resource %(resource)s.")

class RegionsListFailed(MagnumException):
    message = _("Failed to list regions.")

class TrusteeOrTrustToBayFailed(MagnumException):
    message = _("Failed to create trustee or trust for Bay: %(bay_uuid)s")

class CertificatesToBayFailed(MagnumException):
    message = _("Failed to create certificates for Bay: %(bay_uuid)s")


text:
Category:  Widgets
...

## Vector Graphics with Dojo's GFX

Vector graphics can have many advantages, including flawless scaling with maximum portability.
The problem with vector graphic creation is that it can be difficult—but not so with Dojo's GFX library.
GFX provides a simple and flexible API (along with other utilities) for creating, animating, and managing amazing vector graphics.

### Getting Started

[Vector graphics](http://en.wikipedia.org/wiki/Vector_graphics)—the use of geometric "primitives" or
shapes—is a time-honored way of creating images by using mathematical formulae to describe how to render something;
unlike raster-based images (such as PNG and JPG files), which use a two dimensional array of colors.  Often
vector-based images (such as those made with a program like Illustrator or InkScape) are more efficient because
they are not rendered until the viewing device interprets the math behind it.

There are several advantages to using vector graphics as opposed to fixed JPG/GIF images:

*   **Seamless Scalability**: no loss of quality when enlarging or shrinking;
*   **Portability**: vector graphics are easily portable and may be rendered in many formats (SVG, Canvas, VML, etc.);
*   **Programmable**: you don't need to be a Photoshop or Illustrator expert to quickly create vector graphics.

> Vector graphics have been in use for a long time; one of the most common examples is the use of [PostScript](http://en.wikipedia.org/wiki/PostScript)
to describe how to print something.

The Dojo Toolkit features `dojox/gfx` (GFX), a vector graphic creation library capable of creating extremely powerful
vector graphics.  Features of GFX include:

*   Works on almost all devices
*   Can render images (including charts) with SVG, VML, Silverlight, or Canvas.
*   Evaluates the client and uses whichever renderer will work most efficiently
*   Allows for the developer to decide which renderer to use
*   Allows for linear and radial gradients within shapes (and even works in Internet Explorer!)

> `dojox/gfx` also includes experimental SVG rendering for older versions of Internet Explorer
through the use of the [SVGWeb](http://code.google.com/p/svgweb/) project.

GFX was created to accomplish visual tasks that are not easily accomplished with basic CSS and HTML, all while avoiding
Flash and keeping the API simple.

### Creating an Image using `dojox/gfx`

The following is a general timeline for the creation of most vector graphics:

1.  Create the surface (or "canvas")
2.  Create the shapes (paths, lines, rectangles, text, etc.)
3.  Create groups of shapes (grouping shapes together)
4.  Animate shapes or groups of shapes (transform, scale, etc.)
5.  Add shape events

To use the GFX library, there's one simple resource to `require`:

```js
require("dojox/gfx", function(gfx) {

});
```

If a specific rendering priority is preferred, it may be added to the `dojoConfig` object that is created before loading Dojo:

```html
<script>
    dojoConfig = {
        async: true,
        gfxRenderer: "svg,silverlight,vml" // svg gets priority
    };
</script>
<script src="/path/to/dojo/dojo.js"></script>
```

With GFX available within the page, let's explore each part of a GFX graphic timeline, focusing on both the concepts and the syntax.

### Creating the Surface

We consider the surface to be the "canvas" of the graphic; it hosts all of the graphic's shapes. To create a surface, simply code:

```html
<script>
    // Create a GFX surface
    // Arguments:  node, width, height
    require(["dojox/gfx", "dojo/domReady!"], function(gfx) {
        gfx.createSurface("surfaceElement", 400, 400);
    });
</script>

<!-- DOM element which will become the surface -->
<div id="surfaceElement"></div>
```

That's all that's needed to create the surface!  Each rendering engine (SVG, VML) will generate its own code.  For example, the SVG renderer will output:

```html
<svg width="400" height="400"><defs></defs></svg>
```

...while the VML rendering engine will output:

```html
<group style="position: absolute; width: 400px; display: inline-block; height: 400px">
    <rect style="width: 400px; height: 400px; top: 0px; left: 0px"/>
</group>
```

...and the Canvas engine will render:

```html
<canvas width="400" height="400"></canvas>
```

View Demo

### Creating Shapes

With a surface created, the next step is creating shapes.  GFX provides many shapes, including:

*   **[Rect](/api/?qs=1.10/dojox/gfx/shape.Rect)**: A basic rectangle
*   **[Circle](/api/?qs=1.10/dojox/gfx/shape.Circle)**: A basic circle
*   **[Ellipse](/api/?qs=1.10/dojox/gfx/shape.Ellipse)**: A basic ellipse, more flexible than a circle
*   **[Line](/api/?qs=1.10/dojox/gfx/shape.Line)**: A basic line
*   **[PolyLine](/api/?qs=1.10/dojox/gfx/shape.Polyline)**: A multi-point line
*   **[Image](/api/?qs=1.10/dojox/gfx/shape.Image)**: The Image shape allows for loading of bitmap images
*   **[Text](/api/?qs=1.10/dojox/gfx/shape.Text)**: Allows for creation of text
*   **[TextPath](/api/?qs=1.10/dojox/gfx/path.TextPath)**: A shape that flows text along an arbitrary path. TextPath properties are based on the text shape properties
*   **[Path](/api/?qs=1.10/dojox/gfx/path.Path)**: Most versatile geometric shape, which can emulate all other geometric shapes

> Text support within the Canvas rendering engine was added in Dojo 1.6—which is especially useful, since Android does not
presently support SVG.

`dojox/gfx` has implemented a factory pattern for shape creation. Creating a shape is as easy
as `gfx.create_ShapeName_(properties)`.  For example, creating a rectangle would look like:

```js
// Create a basic 200px wide, 100px tall rectangle at position 100x, 50y
var rectangle = surface.createRect({ x: 100, y: 50, width: 200, height: 100 });
```

When a shape is created, Dojo generates the the necessary objects within the rendering environment and provides references to them
for future modification and management.  The method from above returns the following object:

![Dojo GFX](images/createScreen.png)

Rectangle shape properties

Any number of shapes can be created on a given surface.  Let's create a series of shapes:

```js
// Create a GFX surface
// Arguments:  node, width, height
var surface = gfx.createSurface("surfaceElement", 400, 400);

// Create a rectangle
surface.createRect({ x: 100, y: 50, width: 200, height: 100 })
	.setFill("yellow")
	.setStroke("blue");

// Add a circle
surface.createCircle({ cx: 100, cy: 300, r:50 })
	.setFill("green")
	.setStroke("pink");

// Now an ellipse
surface.createEllipse({ cx: 300, cy: 200, rx:50, r:25 })
	.setFill("#fff")
	.setStroke("#999");

// And a line
surface.createLine({ x1: 10, y1: 50, x2:400, y2:400 })
	.setStroke("green");

// How about a polyline?
surface.createPolyline([
	{x: 250, y: 250},
	{x: 300, y: 300},
	{x: 250, y: 350},
	{x: 200, y: 300},
	{x: 110, y: 250}
]).setStroke("blue");

// Add in an image
surface.createImage({
	x:100, y:300, width: 123, height: 56, src: "../images/logo.png"
});

// With some text
surface.createText({ x: 64, y: 220, text: "Vector Graphics Rock!", align: "start" })
	.setFont({ family: "Arial", size: "20pt", weight: "bold" }) //set font
	.setFill("blue");

// And an advanced textpath
var textShape = surface.createTextPath({ text: "TextPath!" })
	.moveTo(125, 70)
	.lineTo(285, 20)
	.setFont({ family: "Verdana", size: "2em" })
	.setFill("black");

// And a simple path
surface.createPath("m100 100 100 0 0 100c0 50-50 50-100 0s-50-100 0-100z")
	.setStroke("black");
```

View Demo

> Each shape type has its own creation properties; visit the [dojox/gfx](/reference-guide/1.10/dojox/gfx.html)
reference guide to see options for your specific shape.  Note also that Path shapes use the
[SVG Path syntax](http://www.w3.org/TR/SVG/paths.html) when using a string as the main argument.

Shapes generated by `dojox/gfx` also include numerous methods for modification.  A few key methods include:

*   **applyTransform**: Allows for transforming of a shape (scaling and skewing, for example)
*   **getFill/setFill**: Get and set fill colors
*   **getStroke/setStroke**: Get and set stroke colors
*   **moveToBack/moveToFront**: Moves shapes based on "z-indexing"

More details about these methods will be provided later within this tutorial.

> Moving shapes from back to front (and vice-versa) is not quite the same as the `z-index` in CSS; it depends on the rendering engine
being used to draw the shapes.

### Styling Shapes

Creating shapes is easy, but more important than creating the shape is making it look good.  The shape objects created by
`dojox/gfx` provides a number of methods to change fill, stroke, and font properties.  These methods allow the
developer to style a shape to their heart's content.

#### Filling a Shape

The `setFill` method allows for a named color, hex color, linear gradient, or radial gradient to color (or fill) a shape.

```js
// Create a circle with a set "blue" color
surface.createCircle({ cx: 50, cy: 50, rx:50, r:25 }).setFill("blue");

// Crate a circle with a set hex color
surface.createCircle({ cx: 300, cy: 300, rx:50, r:25 }).setFill("#f00");

// Create a circle with a linear gradient
surface.createRect({ x: 180, y: 40, width: 200, height: 100 }).
setFill({ type:"linear",
	x1:0,
	y1:0,   //x: 0=>0, consistent gradient horizontally
	x2:0,   //y: 0=>420, changing gradient vertically
	y2:420,
	colors: [
		{ offset: 0,   color: "#003b80" },
		{ offset: 0.5, color: "#0072e5" },
		{ offset: 1,   color: "#4ea1fc" }
	]
});

// Create a circle with a radial gradient
surface.createEllipse({
	cx: 120,
	cy: 260,
	rx: 100,
	ry: 100
}).setFill({
	type: "radial",
	cx: 150,
	cy: 200,
	colors: [
		{ offset: 0,   color: "#4ea1fc" },
		{ offset: 0.5, color: "#0072e5" },
		{ offset: 1,   color: "#003b80" }
	]
});
```
View Demo

> The `colors` array accepts objects with `offset` and `color` keys.  The `offset` property represents a number between 0 and 1, and the `color` property represents the color at that offset.  You may provide any number of `colors` objects.

#### Setting a Stroke on a Shape

The `setStroke` method styles the shape's stroke (like a border or outline).  The `setStroke` method accepts a color string (hex, named color, rgb, etc.)  or an object with more specific stroke properties:

```js
// Create a GFX surface
// Arguments:  node, width, height
var surface = gfx.createSurface("surfaceElement", 400, 400);

// Create a rectangle with a basic black border
surface.createRect({x: 100, y: 50, width: 200, height: 100 }).setStroke("#000");

// Create a circle with a 3-pixel dotted red border
surface.createCircle({ cx: 300, cy: 300, rx: 50, r: 25 }).setStroke({
	style: "Dot", width: 3, cap: "round", color: "#f00"
});

// Create a circle with a 3-pixel dotted red border
surface.createCircle({ cx: 150, cy: 250, rx: 100, r: 50 }).setStroke({
	style: "Dash", width: 3, cap: "butt", color: "#00f"
});
```

Properties may include:

*   **style**: the style of the line (solid, dotted, dashed)
*   **width**: the width of stroke in pixels
*   **color**: the stroke's color
*   **cap**: the shape of the end of the stroke

View Demo

#### Choosing a Font

Both the Text and TextPath shapes allow for a specific font family, size, and weight.  Usage of `setFont` is easy:

```js
// Create the initial text, set the font to 20pt Arial Bold, and fill it blue
surface.createText({ x: 64, y: 220, text: "This is my text", align: "start"}).
setFont({ family: "Arial", size: "20pt", weight: "bold" }).
setFill("blue");
```

The font properties are formatted and work very much like CSS properties you use every day!

### Grouping Shapes Together

Individual shapes may be "glued" together in groups, so that the shapes within a group can be treated like they are a single shape.
Groups are especially important when animating related shapes and attaching events to said shapes.  The best thing about using groups is
that they feature the same animation methods as individual shapes:

```js
// Create a GFX surface
// Arguments:  node, width, height
var surface = gfx.createSurface("surfaceElement", 400, 400);

// Create a group
var group = surface.createGroup();

// Add a shape directly to the group instead of the surface
var rectShape = group.createRect({ x: 0, y: 0, width: 200, height: 100 })
	.setFill("#0000ae");
```

Shapes can also be added to the group at any time:

```js
// Create the shape on the surface
var rectShape = shape.createRect({ x: 0, y: 0, width: 200, height: 100 })
	.setFill("#0000ae");

// Move it to the group!
group.add(rectShape);
```

Groups are especially useful when creating moveable shapes:

```js
// Require the resource
require("dojox/gfx", "dojox/gfx/Moveable", function(gfx, Moveable) {

	// Make all shapes within the group move together!
	new Moveable(group);

});
```

The above snippet allows users to click and hold any shape within the group to move every shape in the group around.

View Demo

### Animations and Transformations

The real power of the GFX library lies within its animation capabilities.  GFX's animations are extremely powerful and smooth,
and capable of many animations—including simple stroke and fill animations, scaling, rotating, and skewing.  The `dojox/gfx/fx`
resource was created to allow for both simple and complex animations.

The first step in creating GFX animations is requiring the resource:

```js
// Require the powerful gfx.fx resource
require(["dojox/gfx", "dojox/gfx/fx"], function(gfx, gfxFx) {

});
```

> Transform capabilities are hosted by each individual shape, so no additional resources are required for scaling, skewing, etc.

#### Fill, Stroke, and Font Animations

The `dojox/gfx/fx` resource provides `animateFill`, `animateFont`, and `animateStroke`
methods for easy animation of each shape property:

```js
// Create a circle, a dojox/gfx.fx instance, play it immediately
var circle = surface.createCircle({ cx: 50, cy: 50, rx: 50, r: 25 })
	.setFill("blue");
gfxFx.animateFill({
	shape: circle,
	duration: 500,
	color: { start: "blue", end: "green" }
}).play();

// Create a rectangle, animate its stroke
var rectangle = surface.createRect({ x: 100, y: 50, width: 200, height: 100 })
	.setStroke("yellow");
gfxFx.animateStroke({
	shape: rectangle,
	duration: 500,
	color: { start: "yellow", end: "pink" },
	width: { end: 15 },
	join:  { values: ["miter", "bevel", "round"] }
}).play();

// Create text, animate it
var text = surface.createText({
	x: 64, y: 220, text: "Vector Graphics Rock!", align: "start"
}).setFont({ family: "Arial", size: "20pt", weight: "bold" })
	.setFill("red");
gfxFx.animateFont({
	shape: text,
	duration: 500,
	variant: { values: ["normal", "small-caps"] },
	size:  { end: 10, units: "pt" },
	color: "green"
}).play();
```

Each method has its own properties relative to the property (stroke, fill, text) being changed.  Also note that gradient
backgrounds cannot be animated;  solid colors are animated flawlessly.

View Demo

#### Rotating a Shape

Shape rotation is also incredibly easy with GFX's animation API.  The `rotateAt` and `rotategAt`
animations allow for rotating shapes or groups of shapes around a given center-point.  The `gfxFx.animateTransform`
method will assemble the animation, and the play method will start it.

```js
// Create a group
var group = surface.createGroup();

// Create a circle
var circle1 = group.createCircle({ cx: 100, cy: 300, r: 50 }).setFill("green");
var circle2 = group.createCircle({ cx: 100, cy: 100, r: 50 }).setFill("blue");
var circle3 = group.createCircle({ cx: 300, cy: 300, r: 50 }).setFill("black");
var circle4 = group.createCircle({ cx: 300, cy: 100, r: 50 }).setFill("yellow");

// Create an animation of the group
var animation = new gfxFx.animateTransform({
    duration: 700,
    shape: group,
    transform: [{
        name: "rotategAt",
        start: [0, 200, 200], // Starts at 0 degree rotation at center-point 200x200
        end: [360, 200, 200]  // Ends at 360 degrees
    }]
});

// Showtime!
animation.play();
```

The `transform` property passed to `gfxFx.animateTransform` allows for any number of animations to be added.

View Demo

> If you are wondering why there are `rotateAt` and `rotategAt` methods, it is because geometry with
JavaScript is usually _radian_-based; but most developers find it easier to think in terms of _degrees_. Both
rotate a shape around a specific point on the surface.

#### Scaling and Skewing

The process of shrinking, enlarging, and skewing GFX graphics is simple.  Use the `gfx.matrix.scale` method to scale
the image, providing `x` and `y` values for the amount to scale on each axis:

```js
// Double the size of the shape
shapeGroup.applyTransform(gfx.matrix.scale({ x: 2, y: 2 }));

// Shrink the shape to half size
shapeGroup.applyTransform(gfx.matrix.scale({ x: 2, y: 0.5 }));
```

The `applyTransform` method of a shape is used to perform the transformation.  The graphic will be flawlessly resized!
Skewing (transforming or moving points of a shape along a single axis) is just as easy:

```js
// Skews the group at -20 degrees
shapeGroup.applyTransform(gfx.matrix.skewYg(-20));
```

View Demo

> The `gfx.matrix` resource contains numerous helpers to invert, rotate, scale, and skew shapes so that you don't
need to know the complex math equations behind setting up any shape modifications or transformations.

### Events

Events are particularly important in `dojox/gfx` as they allow for triggering movement and display changes within groups.
Many of the [charting plugins](../charting) are triggered by events on GFX-created shapes.  You can add events to GFX-created nodes or groups using `shape.on and group.on`, which extends `dojo/on`.

#### shape.on

The `shape.on` method works very much like a native event handler.  Provide a shape and event type:

```js
// Add a circle
var circle = group.createCircle({ cx: 100, cy: 300, r: 50 })
	.setFill("green").setStroke("pink");

// Add a click event to the circle to change its fill!
circle.on("click", function(e) {
	circle.setFill("red");
});
```

#### group.on

The `group.on` method of GFX groups allows for `dojo/on`-style event listeners:

```js
// Get the eventSource to find out what element the event occurred on
group.on("click", function(e) {
    //our shape was clicked, now do something!
}, true);
```

The event object is very much like a standard DOM event object.  The `target` property provides the GFX-generated DOM element which was clicked.

View Demo

> The Silverlight rendering engine supports the following events: `onclick`, `onmouseenter`, `onmouseleave`, `onmousedown`, `onmouseup`, `onmousemove`, `onkeydown`, and `onkeyup`. If you want to target the broadest range of renderers, you are advised to restrict yourself to
this list of events.

### Create the Dojo Logo with GFX

If we have the Dojo Toolkit logo in an SVG format, the path information describing the shapes of that logo can be extracted and used to
create a GFX-based image.  The following is a portion of that SVG file:

```html
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1100px" height="700px" viewBox="0 0 1100 700" enable-background="new 0 0 1100 700" xml:space="preserve">
    <g>
        <g>
            <path fill="#010101" d="M826.698,536.736v11.722h12.71v6.758h-12.71v26.25c0,6.065,1.718,9.483,6.659,9.483    c2.427,0,3.834-0.203,5.147-0.61l0.406,6.759c-1.721,0.621-4.439,1.211-7.876,1.211c-4.145,0-7.466-1.404-9.575-3.729    c-2.429-2.729-3.442-7.062-3.442-12.82v-26.555h-7.576v-6.756h7.576v-8.996L826.698,536.736z"/>
            <path fill="#010101" d="M868.708,598.43c-13.119,0-23.418-9.695-23.418-25.142c0-16.354,10.801-25.938,24.225-25.938    c14.039,0,23.525,10.196,23.525,25.036c0,18.175-12.623,26.05-24.229,26.05h-0.103V598.43L868.708,598.43z M869.115,591.764    c8.481,0,14.846-7.975,14.846-19.089c0-8.267-4.146-18.686-14.643-18.686c-10.396,0-14.931,9.694-14.931,18.976    c0,10.717,6.052,18.783,14.638,18.783h0.09V591.764L869.115,591.764z"/>
            <path fill="#010101" d="M924.162,598.43c-13.119,0-23.406-9.695-23.406-25.142c0-16.354,10.801-25.938,24.213-25.938    c14.039,0,23.517,10.196,23.517,25.036c0,18.175-12.611,26.05-24.216,26.05h-0.106L924.162,598.43L924.162,598.43z     M924.574,591.764c8.487,0,14.834-7.975,14.834-19.089c0-8.267-4.129-18.686-14.638-18.686c-10.395,0-14.94,9.694-14.94,18.976    c0,10.717,6.063,18.783,14.643,18.783h0.103L924.574,591.764L924.574,591.764z"/>

            <!-- more SVG below this shape... -->

        </g>
    </g>
</svg>
```

Judging by the SVG above, it's easy to deduce that:

*   The canvas is approximately 1100 pixels wide and 700 pixels tall.
*   The letters should be drawn with paths (`surface.createPath`)
*   The fill color of each letter (per the logo) is `#010101`.  This example will use a gradient fill, however.

Using the path information in the logo is simple:

```js
// Arguments:  node, width, height
var surface = gfx.createSurface("surfaceElement",1100,700);

// Regular fill
var regularFill = { type: "linear", x1: 0, y1: 0, x2: 0, y2: 900, colors: [{ offset: 0, color: "#555" }, { offset: 1, color: "#000"}] };

// Create group too contain each letter of "toolkit"
var tkGroup = surface.createGroup();

// Tiny letter "t" in "toolkit"
var letterToolkitT = tkGroup.createPath("M826.698,536.736v11.722h12.71v6.758h-12.71v26.25c0,6.065,1.718,9.483,6.659,9.483    c2.427,0,3.834-0.203,5.147-0.61l0.406,6.759c-1.721,0.621-4.439,1.211-7.876,1.211c-4.145,0-7.466-1.404-9.575-3.729    c-2.429-2.729-3.442-7.062-3.442-12.82v-26.555h-7.576v-6.756h7.576v-8.996L826.698,536.736z").setFill(regularFill).setStroke("#000");

// "o"
var letterToolkitO1 = tkGroup.createPath("M868.708,598.43c-13.119,0-23.418-9.695-23.418-25.142c0-16.354,10.801-25.938,24.225-25.938    c14.039,0,23.525,10.196,23.525,25.036c0,18.175-12.623,26.05-24.229,26.05h-0.103V598.43L868.708,598.43z M869.115,591.764    c8.481,0,14.846-7.975,14.846-19.089c0-8.267-4.146-18.686-14.643-18.686c-10.396,0-14.931,9.694-14.931,18.976    c0,10.717,6.052,18.783,14.638,18.783h0.09V591.764L869.115,591.764z").setFill(regularFill).setStroke("#000");

// More "letter" shapes here...
```

When all of the paths are drawn to the surface, the following vector graphic will be created:

[![Dojo GFX Logo](images/gfxlogo.png)](demo/logo.html)

GFX logo created from SVG paths

When the information describing the Dojo Toolkit logo is loaded, it may be converted to any of the supported renderers effortlessly by
changing GFX's default rendering engine order.  The graphic shapes and properties may also be animated or modified as desired.
[This demo](demo/logo.html) uses many of the animation techniques described in this tutorial to modify and animate the
Dojo Toolkit logo.

View Demo - Dojo Logo

View Demo - London Ajax Logo

### Conclusion

Dojo's GFX library provides the ability to create simple vector graphics or more complex vector graphic groups. The Dojo Toolkit's
[advanced charting](../charting) and drawing libraries are based on the power of GFX.  No matter what your medium, the Dojo
Toolkit provides an easy to use API for creating, animating, and managing your vector graphics!

### GFX Resources

Looking for more detail about Dojo's GFX library? Check out these great resources:

*   [GFX Resource Guide](/reference-guide/1.10/dojox/gfx.html)
*   [Dive Into Dojo GFX](http://www.sitepen.com/blog/2010/12/30/dive-into-dojo-gfx/)
*   [GFX API Documentation](/api/?qs=1.10/dojox/gfx)
*   [GFX FX API Documentation](/api/?qs=1.10/dojox/gfx/fx)
*   [GFX Animations Matrix API Documentation](/api/?qs=1.10/dojox/gfx/matrix)
*   [GFX Tests](http://download.dojotoolkit.org/release-1.10.4/dojo-release-1.10.4/dojox/gfx/tests/)


text: java -jar /var/lib/partsunlimited/ordering-service-0.1.0.jar &>/dev/null &


text:
const char *samtools_version(void);
void error(const char *format, ...);

#endif


text:
class MonetaryExchangePeriod < Sequel::Model
  plugin :oplog, primary_key: [:monetary_exchange_period_sid,
                               :parent_monetary_unit_code]
  plugin :conformance_validator

  set_primary_key  [:monetary_exchange_period_sid, :parent_monetary_unit_code]
end


text:
import pytest

from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
    InstitutionFactory,
    UserFactory,
)

@pytest.mark.django_db
class TestInstitutionUsersList:

    def test_return_all_users(self, app):
        institution = InstitutionFactory()

        user_one = UserFactory()
        user_one.affiliated_institutions.add(institution)
        user_one.save()

        user_two = UserFactory()
        user_two.affiliated_institutions.add(institution)
        user_two.save()

        url = '/{0}institutions/{1}/users/'.format(API_BASE, institution._id)
        res = app.get(url)

        assert res.status_code == 200

        ids = [each['id'] for each in res.json['data']]
        assert len(res.json['data']) == 2
        assert user_one._id in ids
        assert user_two._id in ids


text:
1.1 Released! Download at http://www.open3mod.com

_Skim down for info on how to contribute._

Open 3D Model Viewer
========

A general-purpose 3D model viewer. Based on
[Open Asset Import Library] (https://github.com/assimp/assimp), it supports
reading about __fourty 3D file formats__, including __FBX, DXF, Collada, Obj, X, PLY, 3DS, LWO, LWS, STL__
and  __IFC__ ([full list] (http://assimp.sourceforge.net/main_features_formats.html)).

![Screenshot of open3mod (09-05-2013)](http://s1.directupload.net/images/130509/44lqi4p9.png)

__Some key features:__

 - Powerful 3D preview that leverages modern rendering and lighting technologies and thus gives a good impression of how
   scenes would look in a modern 3D game, or even in non-realtime renderings.
 - Skeletal animation playback at arbitrary speed or single-step.
 - Efficient tools to inspect the scene or parts of it. Filtering and isolating elements is made as easy as possible.
 - Tabbed UI, so multiple scenes can be open at the same time
 - Replace textures and fix missing paths by Drag & Drop
 - Multiple viewports (up to 4) and different camera modes such as orbit cameras or even First-Person
 - A multitude of texture file formats is supported through DevIL. Textures are being loaded asynchronously, so there
   are no extra waiting times if you only care about geometry
 - Export of scenes (or parts of scenes) is supported. Output formats include Collada, PLY, STL, OBJ
   (as of now).

License
----------------------

3-clause BSD license. Read `LICENSE` for the details, but it boils down to "use as you like but reproduce the copyright notice".

Contribute
----------------------

Contributions to the projects are highly appreciated. Simply fork the project on Github, hack, and send me a PR.

As a starter, lots of open3mod features (such as high-quality rendering) have been started and are present in the codebase, but are currently disabled. Contact me if you'd like to help out, but don't know where to start.


text:
'''Compatiblity for Python versions.

Some of this code is "lifted" from CherryPy.
'''
import sys
import json
from sys import stdout

_encoding = 'UTF-8'

if sys.version_info >= (3, 0):
    from io import BytesIO as MemoryIO
    xrange = range

    def py3_btou(n, encoding=_encoding):
        return n.decode(encoding)

    def py3_utob(n, encoding=_encoding):
        return bytes(n, encoding)

    unicode = str
    long = int

    def py3_json_dump(obj, indent):
        json.dump(obj, stdout, indent=indent)

else:  # Python 2x
    from cStringIO import StringIO as MemoryIO  # NOQA
    xrange = xrange

    def py2_btou(n, encoding=_encoding):
        return unicode(n, encoding)

    def py2_utob(n, encoding=_encoding):
        return n.encode(encoding)

    unicode = unicode
    long = long

    _outenc = getattr(stdout, 'encoding', None) or _encoding

    def py2_json_dump(obj, indent):
        json.dump(obj, stdout, indent=indent, encoding=_outenc)

# We do it this way and not just redifine function since Cython do not like it
if sys.version_info >= (3, 0):
    btou = py3_btou
    utob = py3_utob
    json_dump = py3_json_dump
else:
    btou = py2_btou
    utob = py2_utob
    json_dump = py2_json_dump