text:
require "base64"

module CFoundry
  module LoginHelpers
    def login_prompts
      @base.uaa.prompts
    end

    def login(username, password)
      @base.token = AuthToken.from_uaa_token_info(@base.uaa.authorize(username, password))
    end
  end
end


text:
First read the entire tutorial

#### deprecated_serializable types

- Both value & pointer
  - int
  - long int
  - long long
  - float
  - double
  - bool
  - string
  - char
  - custom serializable classes

- Only value
  - vector <any_of_the_above>
  - vector <any_of_the_above*>

- Magical features
  - inheritance of custom serializable classes (any depth)
  - polymorphism of custom serializable classes

#<cldoc:Tutorials::Serialization::Getting started>
How the info is stored and basics about process

#### Serialization modes

Taking advantages of the json hash and vector support, serialization is implemented in two different ways,
giving flexibility to the programmer to choose the best in each case.

- _Vector-like_ : The information is put in a vector, so it position dependent

  ```
  [5, false, "We're no strangers to love"]
  ```

- _Hash-like_ : The information has a key for each element so it can be handle by its "name" no matter order

  ```
  {
    "hours" : 5,
    "arrived-yet" : false,
    "rckrll" : "We're no strangers to love"
  }
  ```

Note that in json the root of a file must be always a hash, so if you want to serialize in vector way you must
always handle one path (at least).

```json
{
  "path-to-elements-serialized-as-vectors" : [
    5,
    false,
    "We're no strangers to love"
  ]
}
```
#### Understanding the process

Serialization process is divided in two sections

- a) To translate information between serializable objects and <json::JsonTree>
- b) To translate the information between <json::JsonTree> and a file / string

Depending if you are `Serializing In` (from file / string to c++ objects) or `Serializing Out`
(from c++ object to file / string) the steps order is **b, a** or **a, b**.
Lets explain more precissely each one:

**Serialization** is archived due to the combination of the inheritance from json::serializable and
the explicit declaration of the involved parameters of your custom class in between two special macros.
One of the macros adds to your class the method `serialize` which receives a <json::JsonTree> and depending
of the situation can

  - copy the values of the attributes of the serializable object in it. Also respecting the inner existing hierarchy.
  - initialize the parameters of the object with the data of the JsonTree

So when the method execution has finished, also has done it the Serialization process.

**String management** is made by <json::JsonTree.toText> and <json::JsonTree::parseString> functions.
It is auto included in the file handling process so you don't need to worry about this phase unless you
explicitly need a string. (For example for debugging reasons)

**File handling** is done entirely by a <json::Parser> and can do nothing more (or less) than it.
That means you can do things like putting serializable objects data and other stuff or many not own relationed classes in the same file.

A dedicated section to what can be done at this ambit can be found at <Tutorials::Serialization::File management>

#<cldoc:Tutorials::Serialization::Show me the code!>
Simple serialization, vector-like

This example shows how to serialize a class with one parameter in the vector way using a
file called "file.json" to store / retrieve the information.

#### json file, "file.json"
As we previously said, the root can't be a vector.
```json
{
  "some_path" : [
    10
  ]
}
```
#### code
```c++
#include <iostream>
#include "./deprecated_serializable.hpp"                 // include this file

class A : public json::deprecated_serializable {         // derivate from 'deprecated_serializable'
private:
  int parameter;                              // this parameter will be serialized
  int nonSerializableParameter;               // this will not

  DEPRECATED_SERIAL_START                                // declare the parameters to be serialized in between the macros
    parameter
  DEPRECATED_SERIAL_END                                  // we close without declaring 'noSerializableParameter', so its not serialized
public:
  void changeContent () { parameter = 14; }
};

int main (void) {
  A obj;
  obj.serializeIn("file.json", "some_path");   // reads "file.json", generate an inner 'JsonTree' and use it to initialize the parameters of 'obj'
  std::cout << obj.toText() << std::endl;      // prints object's content
  obj.changeContent();                         // changes the value of 'parameter' to 14
  obj.serializeOut("file.json", "other_path"); // rewrites "file.json" with the information of the object 'obj', at path 'some_path'
}
```
#### output
```
[
  10
]

```
#### modified json file, "file.json"
```json
{
  "other_path" : [
    14
  ]
}
```
Note that information **is not** appended to the file, the path "some_path" is lost and the new file isn't like this:
```json
{
  "some_path" : [
    10
  ]
  "other_path" : [
    14
  ]
}
```
Check <Tutorials::Serialization::Files management> to know how to archive that.

#<cldoc:Tutorials::Serialization::Using multiple parameters>
Using multiple parameters. Vector-like
How to serialize multiple heterogeneous parameters of one non-abstract class using a file called "file.json" to store / retrieve the information.

As we are using the _vector-like_ aproximation, we must know exactly the order of the parameters both in json file and code.

#### json file, "file.json"
```json
{
  "some_path" : [
    10,
    true,
    0.5661,
    "And though your dead and gone, believe me, your memory will carry on"
  ]
}
```
#### code
```c++
#include <iostream>
#include <string>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {         // derivate from 'deprecated_serializable'
private:
  int         number;
  bool        boolean;
  double      precision;
  std::string blckprde;

  DEPRECATED_SERIAL_START                                // the parameters must be in the same order than in file
    number,                                   // note the comma after every element except last. Just like json
    boolean,
    precision,
    blckprde
  DEPRECATED_SERIAL_END
public:
  void printContent () {
    std::cout << number    << std::endl
              << boolean   << std::endl
              << precision  << std::endl
              << blckprde  << std::endl;
  }
};

int main (void) {
  A obj;
  obj.serializeIn("file.json", "some_path");   // reads "file.json" file
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json", "other_path"); // rewrites "file.json" with the information of the object 'obj', at path 'some_path'
}
```
#### output
```
[
  10, true,
  0.5661000000000000476,
  "And though your dead and gone, believe me, your memory will carry on"
]
```

#### modified json file, "file.json"
```json
{
  "other_path" : [
    78,
    false,
    10.09999999999999964,
    "We'll carry on"
  ]
}
```
#<cldoc:Tutorials::Serialization::Hash aproximation>
Unordered name dependent serialization

Same as previous example but using hash-like serialization
Note that in this case we can put the elements directly on the root

#### json file, "file.json"
```json
{
  "integer"    : 10,
  "likeThis"   : true,
  "accurancy"  : 0.5661,
  "songLyrics" : "And though your dead and gone, believe me, your memory will carry on"
}
```
#### code
```c++
#include <iostream>
#include <string>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {               // derivate from 'deprecated_serializable'
private:
  int         number;
  bool        boolean;
  double      precision;
  std::string blckprde;

  DEPRECATED_SERIAL_START                                      // asociate each parameter with its name (which must be the same as in 'file.json')
    "likeThis",   boolean,                          // note the comma in between the name and its parameter.
    "accurancy",  precision,                        // parameters are order independent
    "songLyrics", blckprde,                         // the macro is the same
    "integer",    number                            // last element has no comma
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    number    = 78;
    boolean   = false;
    precision = 10.1;
    blckprde  = "We'll carry on";
  }
};

int main (void) {
  A obj;
  obj.serializeIn("file.json");  // as the elements are at root, we don't need to specify the path
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json"); // rewrites "file.json" with the information of the object 'obj', at path 'some_path'
}
```

#### output
Note the order of the elements has changed and now is the same than used in **DEPRECATED_SERIAL_START** macro. Obviously that is not a problem
if we wanted to run the program again as it would be if we used _vector-like_ mode.
```
{
  "likeThis" : true,
  "accurancy" : 0.5661000000000000476,
  "songLyrics" : "And though your dead and gone, believe me, your memory will carry on",
  "integer" : 10
}
```

#### modified json file, "file.json"
```json
{
  "likeThis" : false,
  "accurancy" : 10.09999999999999964,
  "songLyrics" : "We'll carry on",
  "integer" : 78
}
```

#<cldoc:Tutorials::Serialization::File management>
Reusing files for multiple purposes

In the previous example we used <json::deprecated_serializable::serializeIn> and <json::deprecated_serializable::serializeOut> for file handling.
Those functions are overload (click on them to have more info) and are thinked to use them in two ways

- Fast single object serialization, the one used in previous code:
  ```c++
  A obj; // consider A as a serializable class

  obj.serializeIn ("file_to_open", "path_for_using_as_root")
  obj.serializeOut ("file_to_open", "path_for_using_as_root")
  ```
  This mode opens the file and read / overwrite it with the info of the class 'obj'

- Raw <json::JsonTree> serialization
  ```c++
  A obj; // consider A as a serializable class

  json::Parser parser;
  json::JsonTree tree;
  ...
  // Raw traitment
  ...
  obj.serializeIn (tree, "path_for_using_as_root")
  obj.serializeOut (tree, "path_for_using_as_root")
  ```
  This mode allows you to use one single <json::JsonTree> for several objects serialization.
  (If you don't know how to use <json::Parser> and <json::JsonTree>, check <Tutorials::File Manipulation>)

Here is an example of how to serialize two non related classes in the same file

---

#### json file, "file.json"
```json
{
  "first_path" : [
    10, 20
  ],
  "second_path" : {
    "key" : "A minor",
    "verse" : "I cry out for magic, I feel it dancing in the light"
  }
}
```
#### code
```c++
#include <iostream>
#include <string>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {
private:
  int numberA;
  int numberB;

  DEPRECATED_SERIAL_START
    numberA,
    numberB
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    numberA = 1;
    numberB = 2;
  }
};

class B : public json::deprecated_serializable {
private:
  std::string key;
  std::string verse;

  DEPRECATED_SERIAL_START
    "key", key,
    "verse", verse
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    key = "D minor";
    verse = "Uncovering things that wer sacred, manifest on this earth";
  }
};

int main (void) {
  A objA;
  B objB;

  json::Parser parser;
  json::JsonTree tree;

  parser.parseFile("pruebas/file.json", tree);  // reads file and generates the hierarchy

  objA.serializeIn (tree, "first_path");        // initialize objA using only the info at 'first_path'
  objB.serializeIn (tree, "second_path");       // initialize objB using only the info at 'first_path'

  // At this point both objects are initialized with their respective values

  std::cout << objA.toText() << std::endl;
  std::cout << objB.toText() << std::endl;

  objA.changeContent();
  objB.changeContent();

  // Now the values have changed, we must create the hierarchy again

  objA.serializeOut(tree, "first_path");
  objB.serializeOut(tree, "second_path");

  parser.saveFile("pruebas/file.json", tree);
  // alternatively json::Parser::saveFile("pruebas/file.json", tree);
}
```
#### output
```
[
  1, 2
]
{
  "key" : "D minor",
  "verse" : "Uncovering things that wer sacred, manifest on this earth"
}
```
#### modified json file, "file.json"
```
{
  "first_path" : [
    1, 2
  ],
  "second_path" : {
    "key" : "D minor",
    "verse" : "Uncovering things that were sacred, manifest on this earth"
  }
}
```

#<cldoc:Tutorials::Serialization::Using complex parameters, Vector-like>
Serializaing n dimensional vectors

You can use n dimensional vectors of vectors, the library can handle it for you!

#### json file, "file.json"
```json
{
  "content" : [
    [
      [1, 3, 4],
      [6, 4, 1],
      [4, 0, 0]
    ]
  ]
}
```

Note this is a 2 dimensional vector **inside a vector of serializable parameters** (content)

#### code
```c++
#include <iostream>
#include <vector>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {               // derivate from 'deprecated_serializable'
private:
  std::vector <std::vector <int> > matrix;          // you can use the depth you want

  DEPRECATED_SERIAL_START
    matrix
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    for (int i = 0; i < matrix.size(); i++) {
      for (int j = 0; j < matrix[i].size(); j++) {
        matrix[i][j] = i * matrix.size() + j;
      }
    }
  }
};

int main (void) {
  A obj;
  obj.serializeIn("file.json", "content");
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json", "content");
}
```
#### output
```
[
  [
    [
      1, 3, 4
    ],
    [
      6, 4, 1
    ],
    [
      4, 0, 0
    ]
  ]
]
```
#### modified json file, "file.json"
```json
{
  "content" : [
    [
      [
        0, 1, 2
      ],
      [
        3, 4, 5
      ],
      [
        6, 7, 8
      ]
    ]
  ]
}
```

#<cldoc:Tutorials::Serialization::Using complex parameters, Hash-like>
Serializaing n dimensional vectors

You can use n dimensional vectors of vectors, the library can handle it for you!

#### json file, "file.json"
```json
{
  "two-dimensional-matrix" : [
    [1, 3, 4],
    [6, 4, 1],
    [4, 0, 0]
  ]
}

```
#### code
```c++
#include <iostream>
#include <vector>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {               // derivate from 'deprecated_serializable'
private:
  std::vector <std::vector <int> > matrix;          // you can use the depth you want

  DEPRECATED_SERIAL_START
    "two-dimensional-matrix", matrix
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    for (int i = 0; i < matrix.size(); i++) {
      for (int j = 0; j < matrix[i].size(); j++) {
        matrix[i][j] = i * matrix.size() + j;
      }
    }
  }
};

int main (void) {
  A obj;
  obj.serializeIn("file.json");
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json");
}
```
#### output
```
{
  "two-dimensional-matrix" : [
    [
      1, 3, 4
    ],
    [
      6, 4, 1
    ],
    [
      4, 0, 0
    ]
  ]
}
```
#### modified json file, "file.json"
```json
{
  "two-dimensional-matrix" : [
    [
      0, 1, 2
    ],
    [
      3, 4, 5
    ],
    [
      6, 7, 8
    ]
  ]
}
```

#<cldoc:Tutorials::Serialization::Using serializable classes as parameters>
Also mixing hash-like and vector-like serialization

The following example shows you how to use serializable classes as parameters
mixing vector-like and hash-like modes.

Class 'Hangar' has a vector that stores many instances of 'Rocket'.
The first class uses the hash method while second uses the vector one.

Hangar also has an instance of a 'Personal' which is hash-like serialized

#### json file, "file.json"
```
{
  "temperature" : 15.6,
  "rockets" : [
    [ "Saturn V" ],
    [ "Soyuz"    ],
    [ "Proton"   ],
    [ "R7"       ],
    [ "Falcon 9" ]
  ],
  "personal" : {
    "engineers"     : 12,
    "security"      : 4,
    "enough-people" : false
  }
}
```
The 'rockets' vector has many vectors in it because the 'Rocket' class is serialized vector-like, the code show this clearly
#### code
```
#include <iostream>
#include <vector>
#include <string>
#include "deprecated_serializable.hpp"

class Rocket : public json::deprecated_serializable {               // vector serialization
private:
  string name;

  DEPRECATED_SERIAL_START
    name
  DEPRECATED_SERIAL_END
public:
  void changeContent () { name = "myNewName"; }
};

class Personal : public json::deprecated_serializable {              // hash serialization
private:
  int engi;
  int sec;
  bool enough;

  DEPRECATED_SERIAL_START
    "engineers", engi,
    "security", sec,
    "enough-people", enough
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    engi   = 100;
    sec    = 200;
    enough = true;
  }
};

class Hangar : public json::deprecated_serializable {                // hash serialization
private:
  vector <Rocket> elements;
  Personal people;
  float temp;

  DEPRECATED_SERIAL_START
    "personal", people,
    "rockets", elements,
    "temperature", temp
  DEPRECATED_SERIAL_END

public:
  void changeContent () {
    temp = 0;
    for (Rocket& r : elements) {
      r.changeContent();
    }
    people.changeContent();
  }
};

int main (void) {
  Hangar obj;
  obj.serializeIn("file.json");
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json");
}
```
#### output
```
{
  "personal" : {
    "engineers" : 12,
    "security" : 4,
    "enough-people" : false
  },
  "rockets" : [
    [
      "Saturn V"
    ],
    [
      "Soyuz"
    ],
    [
      "Proton"
    ],
    [
      "R7"
    ],
    [
      "Falcon 9"
    ]
  ],
  "temperature" : 15.60000038146972656
}
```
#### modified json file, "file.json"
```json
{
  "personal" : {
    "engineers" : 100,
    "security" : 200,
    "enough-people" : true
  },
  "rockets" : [
    [
      "myNewName"
    ],
    [
      "myNewName"
    ],
    [
      "myNewName"
    ],
    [
      "myNewName"
    ],
    [
      "myNewName"
    ]
  ],
  "temperature" : 0
}
```
#<cldoc:Tutorials::Serialization::Inheriting serializable ability>
No multiple inheritance supported yet

There is a new macro for this case (see <Tutorials::Serialization::Serializing pointers of serializable classes>> to know why):

  `DEPRECATED_SERIAL_START_INHERITED (this_derived_class, base_class)`

To reminding it, think the order is the same than the c++ inheritance declaration
```c++
class derived_class : public base_class {
  DEPRECATED_SERIAL_START_INHERITED (derived_class, base_class)
  ...
  DEPRECATED_SERIAL_END
};

```
- Serialization occurs starting from the base class to derived
- You **cannot** mix vector-like and hash-like modes. The used in base class must be used for derived ones.

For this example, we have a base serializable class 'A' which has an integer as parameter and a derived class 'B'
which has a string parameter. As the 'A' parameters **and the serializable macros** are declared protected,
to serialize 'B' implies to serialize its 'A' parameters

#### json file, "file.json"
```
{
  "content" : [
    12, "Run"
  ]
}
```
where 12 is the integer parameter of 'A' and "Run" the string parameter of 'B'

#### code
```
#include <iostream>
#include <vector>
#include <string>
#include "deprecated_serializable.hpp"

class A : public json::deprecated_serializable {
protected:                              // because we want parameters and macro functions to be accessible by B class
  int number;

  DEPRECATED_SERIAL_START
    number
  DEPRECATED_SERIAL_END
public:
  virtual void changeContent () { number = 90; }
};

class B : public A {
private:
  std::string word;

  DEPRECATED_SERIAL_START_INHERITED (B, A)          // new macro for inheritance cases
    word
  DEPRECATED_SERIAL_END
public:
  void changeContent () {
    number = 90;
    word = "to the hills";
  }
};

int main (void) {
  B obj;
  obj.serializeIn("file.json", "content");
  std::cout << obj.toText() << std::endl;
  obj.changeContent();
  obj.serializeOut("file.json", "content");
}
```
#### output
```
[
  12, "Run"
]
```
#### modified json file, "file.json"
```json
{
  "content" : [
    90, "to the hills"
  ]
}
```

#<cldoc:Tutorials::Serialization::Serializing pointers of basic types>
Non serializable class pointer case

You can use pointers of any type seen in previous examples excepting vectors:

```
  vector <x*> allowed
  vector <x>* not allowed
```

The serialization process checks types of the pointers and tries to do `new` for each one.

Note that pointers **cannot be used for arrays** of elements **yet** due the methods cannot know the lenght of that array,
so only the first element is serialized.

#### json file, "file.json"
```
{
  "content" : [
    10, "oh by the way, which one is pink?",
    false,
    [
      1, 2, 3, 4
    ]
  ]
}
```
#### code
```c++
#include <iostream>
#include <vector>
#include <string>
#include "deprecated_serializable.hpp"

class B : public json::deprecated_serializable {
private:
  int* number;
  std::string* word;
  bool* boolean;
  A* element;
  vector<int*> vec1;

  DEPRECATED_SERIAL_START
    number,
    word,
    boolean,
    vec1,
  DEPRECATED_SERIAL_END
};

int main (void) {
  A obj;
  obj.serializeIn("file.json", "content");
  std::cout << obj.toText() << std::endl;
}
```
#### output
```
[
  10, "oh by the way, which one is pink?",
  false,
  [
    1, 2, 3, 4
  ]
]
```

#<cldoc:Tutorials::Serialization::Serializing pointers of serializable classes>
The polymorphic problem

## Explanation

Imagine we have this program:
```
class A : public json::deprecated_serializable;
class B : public A;
class C : public A;

class M : public json::deprecated_serializable {
  A* a;
  DEPRECATED_SERIAL_START;
    a                     // this could be an A, a B or a C
  DEPRECATED_SERIAL_END;
```

How do we know if we are serializing an A, B or C?
At execution time we can't ask for a list of derived classes for correctly trait this situation.

The solution adopted consist in explicitily specificate when inheritance occurs (and that is why the
DEPRECATED_SERIAL_START_INHERITED macro exist). This allow the serialization methods to manage the serializable inheritance
as seen in <Tutorials::Serialization::Inheriting serializable ability>, however, this isn't enough, and we
must use one last macro (promise, this is last) in order to tell the 'Seralizable' methods how
to create a new 'B' or 'C' once they know if is a B or a C what is required. (Thats because serialization methods
use templates and tries to do `new t` when the parameter is a pointer). The new macro is:

```
INHERITS (this_class)

```
And must be declared as first element in .cpp file of every class or inmediately after the class declaration.
For example, the previous program now would be
```
class A : public json::deprecated_serializable;

class B : public A;
INHERITS (A)              // tells serializable static method there is a B class

class C : public A;       // tells serializable static method there is a C class
INHERITS (C)

class M : public json::deprecated_serializable {
  A* a;
  DEPRECATED_SERIAL_START;
    a                     // this could be an A, a B or a C
  DEPRECATED_SERIAL_END;

```
The purpose of this is to create a 'dictionary' of derived pointer-used classes so when the serialization reach
the situation of having to manage an A*, but knows it really contains a B*, can truly create a B. And how
will know that? Well, json will say. deprecated_serializable pointers are stored as:
```
{
  "$classType" : "B",
  "$classContent" : [/{

  ]/}
}
```
So, they are **always** hash serialized, but its content could be vector or hash, so all we learned still works here,
the difference is it will not be aplied at the root of the serialized element but in it's '$classContent' path.

## Example

#### json file, "file.json"
```
{
  "content" : [
    {
      "$classType" : "Rover",
      "$classContent" : [
        "Opportunity",
        "Mars"
      ]
    },
    {
      "$classType" : "Rocket",
      "$classContent" : [
        "Zenit",
        0,
        2
      ]
    },
    {
      "$classType" : "SpaceShip",
      "$classContent" : [
        "Shenzou",
        1,
      ]
    }
  ]
}
```
#### code
```c++
#include <iostream>
#include <vector>
#include <string>
#include "deprecated_serializable.hpp"

class AwesomeVehicle : public json::deprecated_serializable {
protected:
  string name;

  DEPRECATED_SERIAL_START
    name
  DEPRECATED_SERIAL_END
};

class Rocket : public AwesomeVehicle {
private:
  int boosters;
  int stages;

  DEPRECATED_SERIAL_START_INHERITED (Rocket, AwesomeVehicle)
    boosters,
    stages
  DEPRECATED_SERIAL_END
};

INHERITS (Rocket)                                    // Do not forget

class SpaceShip : public AwesomeVehicle {
private:
  int crew;

  DEPRECATED_SERIAL_START_INHERITED (SpaceShip, AwesomeVehicle)
    crew
  DEPRECATED_SERIAL_END
};

INHERITS (SpaceShip)                                 // Do not forget

class Rover : public AwesomeVehicle {
private:
  std::string celestial_body;

  DEPRECATED_SERIAL_START_INHERITED (Rover, AwesomeVehicle)
    celestial_body
  DEPRECATED_SERIAL_END
};

INHERITS (Rover)                                     // Do not forget

class ProudOfScience : public json::deprecated_serializable{
private:
  std::vector <AwesomeVehicle*> spaceStuff;

  DEPRECATED_SERIAL_START
    "content", spaceStuff
  DEPRECATED_SERIAL_END
};

int main (void) {
  ProudOfScience obj;
  obj.serializeIn("file.json");
  std::cout << obj.toText() << std::endl;
  //obj.serializeOut("file.json", "content");
}
```
#### ouput
```
{
  "content" : [
    {
      "$classType" : "Rover",
      "$classContent" : [
        "Opportunity",
        "Mars"
      ]
    },
    {
      "$classType" : "Rocket",
      "$classContent" : [
        "Zenit",
        0, 2
      ]
    },
    {
      "$classType" : "SpaceShip",
      "$classContent" : [
        "Shenzou",
        1
      ]
    }
  ]
}
```

redpajama_set_name: RedPajamaGithub


text:
package coreos

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
)

func NewFakeVersion(t *testing.T, version string) *Version {
	body := fmt.Sprintf("COREOS_VERSION=%s", version)
	subject := &Version{}
	subject.Client = NewTestClient(t, "https://stable.release.core-os.net/amd64-usr/current/version.txt", body, nil)
	return subject
}

func NewFakeRelease(t *testing.T, version string) *Release {
	body := fmt.Sprintf(`
	{
		"%s": {
		  "release_date": "2019-01-23 20:20:00 +0000",
		  "major_software": {
			"kernel": ["4.19.34"],
			"docker": ["18.06.3"],
			"etcd": ["3.3.12"],
			"fleet": [""]
		  },
		  "release_notes": "No updates"
		}
	}`, version)
	subject := &Release{}
	subject.Client = NewTestClient(t, "https://coreos.com/releases/releases-stable.json", body, nil)
	return subject
}

func NewTestClient(t *testing.T, baseURL, body string, count *int) *http.Client {
	fn := func(req *http.Request) *http.Response {
		assert.Equal(t, req.URL.String(), baseURL)
		if count != nil {
			*count = *count + 1
		}
		return &http.Response{
			StatusCode: 200,
			Body:       io.NopCloser(bytes.NewBufferString(body)),
			Header:     make(http.Header),
		}
	}

	return &http.Client{
		Transport: RoundTripFunc(fn),
	}
}

type RoundTripFunc func(req *http.Request) *http.Response

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
	return f(req), nil
}


text:
package edu.wustl.common.participant.bizlogic;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

import org.apache.commons.codec.language.Metaphone;

import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.exception.ApplicationException;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.exception.ErrorKey;
import edu.wustl.common.participant.domain.IParticipant;
import edu.wustl.common.participant.domain.ISite;
import edu.wustl.common.participant.utility.Constants;
import edu.wustl.common.participant.domain.IRace;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.Status;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.DAO;
import edu.wustl.dao.HibernateDAO;
import edu.wustl.dao.QueryWhereClause;
import edu.wustl.dao.condition.EqualClause;
import edu.wustl.dao.exception.AuditException;
import edu.wustl.dao.exception.DAOException;
import edu.wustl.common.participant.domain.IParticipantMedicalIdentifier;
import edu.wustl.common.participant.utility.ParticipantManagerException;
import edu.wustl.common.participant.utility.ParticipantManagerUtility;

/**
 * The Class CommonParticipantBizlogic.
 */
public class CommonParticipantBizlogic extends CommonDefaultBizLogic
{

	/** The Constant logger. */
	private static final Logger logger = Logger.getCommonLogger(CommonParticipantBizlogic.class);

	/**
	 * Insert.
	 * @param obj Participant Object
	 * @param dao DAo Object
	 * @param ParticipantMedicalIdentifier Object
	 *
	 * @return the i participant
	 *
	 * @throws BizLogicException the biz logic exception
	 * @throws DAOException the DAO exception
	 */
	public static IParticipant insert(final Object obj, final DAO dao,
			final IParticipantMedicalIdentifier pmi) throws BizLogicException, DAOException
	{
		final IParticipant participant = (IParticipant) obj;
		setMetaPhoneCode(participant);
		Collection<IParticipantMedicalIdentifier<IParticipant, ISite>> pmiCollection = participant
				.getParticipantMedicalIdentifierCollection();
		if (pmiCollection == null)
		{
			pmiCollection = new LinkedHashSet<IParticipantMedicalIdentifier<IParticipant, ISite>>();
		}
		if (pmiCollection.isEmpty())
		{
			pmi.setMedicalRecordNumber(null);
			pmi.setSite(null);
			pmiCollection.add(pmi);
		}
		checkForSiteIdentifierInPMI(dao, pmiCollection);
		final Iterator<IParticipantMedicalIdentifier<IParticipant, ISite>> iterator = pmiCollection
				.iterator();
		while (iterator.hasNext())
		{
			final IParticipantMedicalIdentifier<IParticipant, ISite> pmIdentifier = iterator.next();
			pmIdentifier.setParticipant(participant);
		}
		dao.insert(participant);
		return participant;
	}

	/**
	 * For Bulk Operations: retrieving site_id from site_name.
	 * Check For Site Identifier In PMI.
	 * @param dao DAO
	 * @param pmiCollection Collection of ParticipantMedicalIdentifier
	 * @throws DAOException DAOException
	 * @throws BizLogicException BizLogicException
	 */
	private static void checkForSiteIdentifierInPMI(final DAO dao,
			final Collection<IParticipantMedicalIdentifier<IParticipant, ISite>> pmiCollection)
			throws DAOException, BizLogicException
	{
		final Iterator<IParticipantMedicalIdentifier<IParticipant, ISite>> pmiIterator = pmiCollection
				.iterator();
		while (pmiIterator.hasNext())
		{
			final IParticipantMedicalIdentifier<IParticipant, ISite> pmIdentifier = pmiIterator
					.next();
			if (pmIdentifier.getSite() != null && (pmIdentifier.getSite().getId() != null
					|| pmIdentifier.getSite().getName() != null))
			{
				final ISite site = pmIdentifier.getSite();
				final String sourceObjectName = ISite.class.getName();
				final String[] selectColumnName ={"id","name"};
				final QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName);
			//	List<ColumnValueBean> columnValueBeans = new ArrayList<ColumnValueBean>();
				String errMsg = "";
				String errKey = "";
				if(site.getName() != null)
				{
					errKey = "invalid.site.name";
					errMsg = site.getName();
					queryWhereClause.addCondition(new EqualClause("name", site.getName()));
				//	columnValueBeans.add(new ColumnValueBean("name",site.getName()));
				}
				else
				{
					errKey = "errors.item.format";
					errMsg = "Site Identifier";
					queryWhereClause.addCondition(new EqualClause("id", site.getId()));
				//	columnValueBeans.add(new ColumnValueBean("id",site.getId()));
				}

				final List list = ((HibernateDAO) dao).retrieve(sourceObjectName, selectColumnName,
						queryWhereClause);

				if (!list.isEmpty())
				{
					final Object[] valArr = (Object[]) list.get(0);
					site.setId((Long) valArr[0]);
					site.setName((String)valArr[1]);
					pmIdentifier.setSite(site);
				}
				else
				{
					throw new BizLogicException(ErrorKey.getErrorKey(errKey), null,errMsg);
				}
			}
		}
	}

	/**
	 * Updates the persistent object in the database.
	 *
	 * @param dao - DAO object
	 * @param participant the participant
	 * @param oldParticipant the old participant
	 *
	 * @throws BizLogicException throws BizLogicException
	 * @throws DAOException the DAO exception
	 */
	public static void update(final DAO dao, final IParticipant participant,
			final IParticipant oldParticipant) throws BizLogicException, DAOException
	{

		setMetaPhoneCode(participant);
		dao.update(participant, oldParticipant);
	}

	/**
	 * Sets the meta phone code.
	 *
	 * @param participant the new meta phone code
	 */
	private static void setMetaPhoneCode(final IParticipant participant)
	{
		final Metaphone metaPhoneObj = new Metaphone();
		final String lNameMetaPhone = metaPhoneObj.metaphone(participant.getLastName());
		participant.setMetaPhoneCode(lNameMetaPhone);
	}

	/**
	 * Update ParticipantMedicalIdentifier.
	 * @param dao DAo Object
	 * @param pmIdentifier ParticipantMedicalIdentifier Identifier
	 * @throws DAOException the DAO exception
	 */
	public static void updatePMI(final DAO dao,
			final IParticipantMedicalIdentifier<IParticipant, ISite> pmIdentifier)
			throws DAOException
	{
		if (pmIdentifier.getId() != null)
		{
			dao.update(pmIdentifier);
		}
		else if (pmIdentifier.getId() == null || pmIdentifier.getId().equals(""))
		{
			dao.insert(pmIdentifier);
		}
	}

	/**
	 * Validate.
	 *
	 * @param dao : DAO object. Overriding the parent class's method to validate
	 * the enumerated attribute values.
	 * @param participant the participant
	 * @param operation the operation
	 * @param validator the validator
	 *
	 * @return true, if validate
	 *
	 * @throws BizLogicException the biz logic exception
	 */
	public static boolean validate(final IParticipant participant, final DAO dao,
			final String operation, final Validator validator) throws BizLogicException
	{
		String message = "";
		if (participant == null)
		{

			throw new BizLogicException(null, null, "domain.object.null.err.msg", "Participant");
		}

		String errorKeyForBirthDate = "";
		String errorKeyForDeathDate = "";

		final String birthDate = Utility.parseDateToString(participant.getBirthDate(),
				CommonServiceLocator.getInstance().getDatePattern());
		if (!Validator.isEmpty(birthDate))
		{
			errorKeyForBirthDate = validator.validateDate(birthDate, true);
			if (errorKeyForBirthDate.trim().length() > 0)
			{
				message = ApplicationProperties.getValue("participant.birthDate");
				throw new BizLogicException(null, null, errorKeyForBirthDate, message);
			}
		}

		final String deathDate = Utility.parseDateToString(participant.getDeathDate(),
				CommonServiceLocator.getInstance().getDatePattern());
		if (!Validator.isEmpty(deathDate))
		{
			errorKeyForDeathDate = validator.validateDate(deathDate, true);
			if (errorKeyForDeathDate.trim().length() > 0)
			{
				message = ApplicationProperties.getValue("participant.deathDate");
				throw new BizLogicException(null, null, errorKeyForDeathDate, message);
			}
		}

		if (participant.getVitalStatus() == null || !participant.getVitalStatus().equals("Dead"))
		{
			if (!Validator.isEmpty(deathDate))
			{
				throw new BizLogicException(null, null, "participant.invalid.enddate", "");
			}
		}
		if ((!Validator.isEmpty(birthDate) && !Validator.isEmpty(deathDate))
				&& (errorKeyForDeathDate.trim().length() == 0 && errorKeyForBirthDate.trim()
						.length() == 0))
		{
			final boolean errorKey1 = validator.compareDates(Utility.parseDateToString(participant
					.getBirthDate(), CommonServiceLocator.getInstance().getDatePattern()), Utility
					.parseDateToString(participant.getDeathDate(), CommonServiceLocator
							.getInstance().getDatePattern()));

			if (!errorKey1)
			{

				throw new BizLogicException(null, null, "participant.invaliddate", "");
			}
		}

		if (!Validator.isEmpty(participant.getSocialSecurityNumber()))
		{
			if (!validator.isValidSSN(participant.getSocialSecurityNumber()))
			{
				message = ApplicationProperties.getValue("participant.socialSecurityNumber");
				throw new BizLogicException(null, null, "errors.invalid", message);
			}
		}

		if (!Validator.isEmpty(participant.getVitalStatus()))
		{
			final List vitalStatusList = CDEManager.getCDEManager().getPermissibleValueList(
					Constants.CDE_VITAL_STATUS, null);
			if (!Validator.isEnumeratedOrNullValue(vitalStatusList, participant.getVitalStatus()))
			{
				throw new BizLogicException(null, null, "participant.vitalstatus.errMsg", "");
			}
		}

		if (!Validator.isEmpty(participant.getGender()))
		{
			final List genderList = CDEManager.getCDEManager().getPermissibleValueList(
					Constants.CDE_NAME_GENDER, null);

			if (!Validator.isEnumeratedOrNullValue(genderList, participant.getGender()))
			{
				throw new BizLogicException(null, null, "participant.gender.errMsg", "");
			}
		}

		if (!Validator.isEmpty(participant.getSexGenotype()))
		{
			final List genotypeList = CDEManager.getCDEManager().getPermissibleValueList(
					Constants.CDE_NAME_GENOTYPE, null);
			if (!Validator.isEnumeratedOrNullValue(genotypeList, participant.getSexGenotype()))
			{
				throw new BizLogicException(null, null, "participant.genotype.errMsg", "");
			}
		}

		final Collection paticipantMedCol = participant.getParticipantMedicalIdentifierCollection();
		//Created a new PMI collection for bulk operation functionality.
		final Collection newPMICollection = new LinkedHashSet();
		if (paticipantMedCol != null && !paticipantMedCol.isEmpty())
		{
			final Iterator itr = paticipantMedCol.iterator();
			while (itr.hasNext())
			{
				final IParticipantMedicalIdentifier<IParticipant, ISite> partiMedobj = (IParticipantMedicalIdentifier<IParticipant, ISite>) itr
						.next();
				final ISite site = partiMedobj.getSite();
				final String medicalRecordNo = partiMedobj.getMedicalRecordNumber();
				if (validator.isEmpty(medicalRecordNo) || site == null ||
						(site.getId() == null&&(site.getName()==null&&!"".equals(site.getName()))))
				{
					if (partiMedobj.getId() == null)
					{
						throw new BizLogicException(null, null,
								"errors.participant.extiden.missing", "");
					}
				}
				else
				{
					newPMICollection.add(partiMedobj);
				}
			}
		}
		participant.setParticipantMedicalIdentifierCollection(newPMICollection);

		final Collection raceCollection = participant.getRaceCollection();
		if (raceCollection != null && !raceCollection.isEmpty())
		{
			final List raceList = CDEManager.getCDEManager().getPermissibleValueList(
					Constants.CDE_NAME_RACE, null);
			final Iterator itr = raceCollection.iterator();
			while (itr.hasNext())
			{
				final IRace race = (IRace) itr.next();
				if (race != null)
				{
					final String raceName = race.getRaceName();
					if (!Validator.isEmpty(raceName)
							&& !Validator.isEnumeratedOrNullValue(raceList, raceName))
					{
						throw new BizLogicException(null, null, "participant.race.errMsg", "");
					}
				}
			}
		}

		if (!Validator.isEmpty(participant.getEthnicity()))
		{
			final List ethnicityList = CDEManager.getCDEManager().getPermissibleValueList(
					Constants.CDE_NAME_ETHNICITY, null);
			if (!Validator.isEnumeratedOrNullValue(ethnicityList, participant.getEthnicity()))
			{
				throw new BizLogicException(null, null, "participant.ethnicity.errMsg", "");
			}
		}

		if (operation.equals(Constants.ADD))
		{
			if (!Status.ACTIVITY_STATUS_ACTIVE.toString().equals(participant.getActivityStatus()))
			{
				throw new BizLogicException(null, null, "activityStatus.active.errMsg", "");
			}
		}
		else
		{
			if (!Validator.isEnumeratedValue(Constants.ACTIVITY_STATUS_VALUES, participant
					.getActivityStatus()))
			{
				throw new BizLogicException(null, null, "activityStatus.errMsg", "");
			}
		}
		return true;
	}

	/**
	 * Modify participant object.
	 *
	 * @param dao the dao
	 * @param sessionDataBean the session data bean
	 * @param participant the participant
	 *
	 * @throws BizLogicException the biz logic exception
	 */
	public void modifyParticipantObject(final DAO dao, final SessionDataBean sessionDataBean,
			final IParticipant participant, final IParticipant oldParticipant)
			throws BizLogicException
	{
		try
		{
			updateParticipant(dao, sessionDataBean, participant, oldParticipant);
		}
		catch (DAOException e)
		{
			throw new BizLogicException(e);
		}
		catch (BizLogicException biz)
		{
			logger.debug(biz.getMessage(), biz);
			throw getBizLogicException(biz, biz.getErrorKeyName(), biz.getMsgValues());

		}
		catch (Exception exception)
		{
			throw getBizLogicException(exception, "Error while updating object", "");
		}
	}

	/**
	 * This method will update Participant Object.
	 *
	 * @param participant Participant object
	 * @param oldParticipant Persistent participant object
	 * @param dao DAO Object
	 * @param sessionDataBean SessionDataBean Object
	 *
	 * @return AuditManager
	 *
	 * @throws BizLogicException BizLogicException Exception
	 * @throws DAOException DAOException Exception
	 * @throws AuditException AuditException Exception
	 */
	private void updateParticipant(final DAO dao, final SessionDataBean sessionDataBean,
			final IParticipant participant, final IParticipant oldParticipant)
			throws BizLogicException, DAOException
	{
		update(dao, participant, oldParticipant);
	}

	/**
	 * check not null.
	 *
	 * @param object object
	 *
	 * @return boolean
	 */

	public static boolean isNullobject(Object object)
	{
		boolean result = true;
		if (object != null)
		{
			result = false;
		}
		return result;
	}

	/**
	 * Sets the participant medical identifier default.
	 *
	 * @param partMedIdentifier the part med identifier
	 *
	 * @throws BizLogicException the biz logic exception
	 * @throws edu.wustl.common.participant.utility.ParticipantManagerException
	 */
	public static void setParticipantMedicalIdentifierDefault(
			IParticipantMedicalIdentifier<IParticipant, ISite> partMedIdentifier)
			throws BizLogicException, ParticipantManagerException
	{
		if (isNullobject(partMedIdentifier.getSite()))
		{
			final ISite site = (ISite) ParticipantManagerUtility.getSiteInstance();
			partMedIdentifier.setSite(site);
		}
	}

	/**
	 * Post insert.
	 *
	 * @param obj the obj
	 * @param sessionDataBean the session data bean
	 * @throws ApplicationException
	 */
	public static void postInsert(final Object obj, LinkedHashSet<Long> userIdSet)
			throws BizLogicException
	{

	}

	/**
	 * Pre update.
	 *
	 * @param obj the obj
	 * @param sessionDataBean the session data bean
	 * @throws BizLogicException
	 * @throws ApplicationException
	 */
	public static void preUpdate(Object oldObj, Object obj, SessionDataBean sessionDataBean) throws BizLogicException
	{

	}

	/**
	 * Post update.
	 *
	 * @param obj the obj
	 * @param sessionDataBean the session data bean
	 *
	 * @throws BizLogicException the biz logic exception
	 */
	public static void postUpdate(Object oldObj, Object currentObj, SessionDataBean sessionDataBean)
			throws BizLogicException
	{

	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <?php //require '../vendor/raveren/kint/Kint.class.php';?>

    <title><?php wp_title( '|', true, 'right' ); ?></title>

    <link href="<?php echo get_stylesheet_directory_uri() . "/style.css";?>" rel="stylesheet" type="text/css">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ page.base_url }}assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="{{ page.base_url }}assets/ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{{ page.base_url }}assets/ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="{{ page.base_url }}assets/ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="{{ page.base_url }}assets/ico/favicon.png">

    <?php if ( is_admin_bar_showing() ) echo '

'; // Fix menu overlap bug..  ?>

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>
        <a class="navbar-brand" href="<?php home_url();?>"><?php bloginfo('name');?>
    <?php
    wp_nav_menu( array(
                'theme_location' => 'header-menu',
                'container_class' => 'nav-collapse collapse',
                'menu_class' => 'nav navbar-nav' ,
                'fallback_cb' => 'default_menu'
            )
        );
    ?>


text:
<!DOCTYPE HTML>

		<meta charset="UTF-8" />
		<title>File Carving</title>
		<link href="../../styles/prism.css" rel="stylesheet" />
		<link href="../../styles/style.css" rel="stylesheet" />

File Carving 1

Intro to File Carving

File carving is the process of searching for files on the basis of binary content rather than metadata. You should read the lesson on File Structures before continuing. As we know, file are composed of binary data. The only way a computer knows where each file is and how big a file is is through the use of metadata. Metadata, like those stored by the Windows Master File Table (MFT) tells exactly where a file is, how large a file is, when the file was last modified, and other related information. File carving is necessary when metadata is not available to the investigator or that the metadata is corrupt

The Three Methods of Carving

There are three main ways that file carvers operate.

1. Header -> Trailer or Header -> Size search.

A common way to crave files is to search for headers and carve to the trailers. This is present in JPGs and other file formats with identifiable headers and trailers.

Figure 1: JPG header and trailer

A file carver will simply scan for the hex signature FF D8 FF (E0) and then carve to FF D9. In the example below, the file carver will only scan from the header of the PNG to the EOF. It will ignore any data following the EOF.

Figure 2: PNG header and EOF

However, some files don't have set trailers. In the case of BMPs (which have headers and no trailers), a file carver may simply choose to estimate a maximum file size or to complete a check to see if an image is completely carved based on size information.

2. Structure based carving.

This method is more applicable to files that do not have a trailer. File carvers will often read the header and attempt to use information following the header to determine how large a file is or when to stop carving.

3. Content based carving.

This is one of the more advanced methods of carving employed by file carvers. This will use content structure like html tags, language recognition, chi-squared analysis, and information entropy to determine the start and end of a file.

Using File Carvers

There are many file carvers available for use. Some of them are made specifically for images. The two carvers that have proved to be especially useful are Scalpel and Foremost. They are very easy to install on Linux but require compiling on Windows. Being a nice person, I compiled them for you and even included a larger and more comprehensive signature list. You can download them here - carvers.7z.

Using file carvers is very easy. The common commands are shown below. Also, you can run cmd.bat in the respective folders to spawn CMD in the current directory.

Further Readings and References

"File Carving" - http://www.forensicswiki.org/wiki/File_Carving

Tool: Scalpel 2.0 - https://github.com/machn1k/Scalpel-2.0

Tool: Foremost - http://foremost.sourceforge.net/

		<?php include('../../footer.php')?>


text:
from pymongo import MongoClient
from config import MONGO
from os import environ

# 检测系统中环境存在mongo docker的连接环境变量时,使用mongo docker的环境变量,而不使用配置文件的连接信息.

MONGO_ADDR = environ.get("MONGO_PORT_27017_TCP_ADDR", None)
if MONGO_ADDR is None:
    MONGO_ADDR = MONGO["HOST"]

MONGO_PORT = environ.get("MONGO_PORT_27017_TCP_PORT", None)
if MONGO_PORT is None:
    MONGO_PORT = MONGO["PORT"]

_client = MongoClient(MONGO_ADDR, int(MONGO_PORT), connect=False)

def insert_collection(name, data):
    """
    根据给定的集合名称,插入数据至该集合中.
    :param name: 集合名称
    :param data: 数据或数据列表
    :return:
    """
    db = _client.get_database(MONGO["DB"])
    collection = db.get_collection(name)

    if isinstance(data, list):
        collection.insert_many(data)
    elif isinstance(data, dict):
        collection.insert(data)


text:
<md-dialog aria-label="Mango">

干得不错!

            项目创建完成

            <md-button  ng-disabled="vm.loading" ng-click="vm.cancel()" class="green--btn" translate="MODULES_PROJECTMANAGE_CONFIRM">
                确定
            </md-button>

</md-dialog>


text:
namespace gameplay
{

AnimationController::AnimationController()
    : _state(STOPPED)
{
}

AnimationController::~AnimationController()
{
}

void AnimationController::stopAllAnimations()
{
    std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
    while (clipIter != _runningClips.end())
    {
        AnimationClip* clip = *clipIter;
        GP_ASSERT(clip);
        clip->stop();
        clipIter++;
    }
}

AnimationController::State AnimationController::getState() const
{
    return _state;
}

void AnimationController::initialize()
{
    _state = IDLE;
}

void AnimationController::finalize()
{
    std::list<AnimationClip*>::iterator itr = _runningClips.begin();
    for ( ; itr != _runningClips.end(); itr++)
    {
        AnimationClip* clip = *itr;
        SAFE_RELEASE(clip);
    }
    _runningClips.clear();
    _state = STOPPED;
}

void AnimationController::resume()
{
    if (_runningClips.empty())
        _state = IDLE;
    else
        _state = RUNNING;
}

void AnimationController::pause()
{
    _state = PAUSED;
}

void AnimationController::schedule(AnimationClip* clip)
{
    if (_runningClips.empty())
    {
        _state = RUNNING;
    }

    GP_ASSERT(clip);
    clip->addRef();
    _runningClips.push_back(clip);
}

void AnimationController::unschedule(AnimationClip* clip)
{
    std::list<AnimationClip*>::iterator clipItr = _runningClips.begin();
    while (clipItr != _runningClips.end())
    {
        AnimationClip* rClip = (*clipItr);
        if (rClip == clip)
        {
            _runningClips.erase(clipItr);
            SAFE_RELEASE(clip);
            break;
        }
        clipItr++;
    }

    if (_runningClips.empty())
        _state = IDLE;
}

void AnimationController::update(float elapsedTime)
{
    if (_state != RUNNING)
        return;

    Transform::suspendTransformChanged();

    // Loop through running clips and call update() on them.
    std::list<AnimationClip*>::iterator clipIter = _runningClips.begin();
    while (clipIter != _runningClips.end())
    {
        AnimationClip* clip = (*clipIter);
        GP_ASSERT(clip);
        clip->addRef();
        if (clip->isClipStateBitSet(AnimationClip::CLIP_IS_RESTARTED_BIT))
        {   // If the CLIP_IS_RESTARTED_BIT is set, we should end the clip and
            // move it from where it is in the running clips list to the back.
            clip->onEnd();
            clip->setClipStateBit(AnimationClip::CLIP_IS_PLAYING_BIT);
            _runningClips.push_back(clip);
            clipIter = _runningClips.erase(clipIter);
        }
        else if (clip->update(elapsedTime))
        {
            clip->release();
            clipIter = _runningClips.erase(clipIter);
        }
        else
        {
            clipIter++;
        }
        clip->release();
    }

    Transform::resumeTransformChanged();

    if (_runningClips.empty())
        _state = IDLE;
}

}


text:
import logging
logger = logging.getLogger(__name__)
logger_client = logging.getLogger('.'.join([__name__, 'client']))
logger_server = logging.getLogger('.'.join([__name__, 'server']))

from spyne import BODY_STYLE_EMPTY
from spyne import BODY_STYLE_BARE
from spyne import BODY_STYLE_WRAPPED
from spyne.error import Fault, Redirect
from spyne.interface import Interface
from spyne import EventManager
from spyne.util.appreg import register_application
from spyne.error import RespawnError

def get_fault_string_from_exception(e):
    # haha.
    return "Internal Error"

def return_traceback_in_unhandled_exceptions():
    """Call this function first thing in your main function to return original
    python errors to your clients in case of unhandled exceptions.
    """

    global get_fault_string_from_exception

    import traceback
    def _get_fault_string_from_exception(e):
        return traceback.format_exc()
    get_fault_string_from_exception = _get_fault_string_from_exception

class Application(object):
    """The Application class is the glue between one or more service
    definitions, input and output protocols.

    :param services:     An iterable of ServiceBase subclasses that defines
                         the exposed services.
    :param tns:          The targetNamespace attribute of the exposed
                         service.
    :param name:         The optional name attribute of the exposed service.
                         The default is the name of the application class
                         which is by default 'Application'.
    :param in_protocol:  A ProtocolBase instance that denotes the input
                         protocol. It's only optional for NullServer transport.
    :param out_protocol: A ProtocolBase instance that denotes the output
                         protocol. It's only optional for NullServer transport.
    :param config:       An arbitrary python object to store random global data.

    Supported events:
        * ``method_call``:
            Called right before the service method is executed

        * ``method_return_object``:
            Called right after the service method is executed

        * ``method_exception_object``:
            Called when an exception occurred in a service method, before the
            exception is serialized.

        * ``method_context_created``:
            Called from the constructor of the MethodContext instance.

        * ``method_context_closed``:
            Called from the ``close()`` function of the MethodContext instance,
            which in turn is called by the transport when the response is fully
            sent to the client (or in the client case, the response is fully
            received from server).
    """

    transport = None

    def __init__(self, services, tns, name=None,
                          in_protocol=None, out_protocol=None, config=None):
        self.services = tuple(services)
        self.tns = tns
        self.name = name
        self.config = config

        if self.name is None:
            self.name = self.__class__.__name__.split('.')[-1]

        self.event_manager = EventManager(self)
        self.error_handler = None

        self.interface = Interface(self)
        self.in_protocol = in_protocol
        self.out_protocol = out_protocol

        if self.in_protocol is None:
            from spyne.protocol import ProtocolBase
            self.in_protocol = ProtocolBase()
        self.in_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.in_protocol.message = self.in_protocol.REQUEST

        if self.out_protocol is None:
            from spyne.protocol import ProtocolBase
            self.out_protocol = ProtocolBase()
        self.out_protocol.set_app(self)
        # FIXME: this normally is another parameter to set_app but it's kept
        # separate for backwards compatibility reasons.
        self.out_protocol.message = self.out_protocol.RESPONSE

        register_application(self)

    def process_request(self, ctx):
        """Takes a MethodContext instance. Returns the response to the request
        as a native python object. If the function throws an exception, it
        returns None and sets the exception object to ctx.out_error.

        Overriding this method would break event management. So this is not
        meant to be overridden unless you know what you're doing.
        """

        try:
            # fire events
            self.event_manager.fire_event('method_call', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event('method_call', ctx)

            # call user method
            ctx.out_object = self.call_wrapper(ctx)

            # out object is always an iterable of return values. see
            # MethodContext docstrings for more info
            if ctx.descriptor.body_style is not BODY_STYLE_WRAPPED or \
                                len(ctx.descriptor.out_message._type_info) <= 1:
                # if it's not a wrapped method, OR there's just one return type
                # we wrap it ourselves
                ctx.out_object = [ctx.out_object]

            # Now that the processing is switched to the outgoing message,
            # point ctx.protocol to ctx.out_protocol
            ctx.protocol = ctx.outprot_ctx

            # fire events
            self.event_manager.fire_event('method_return_object', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event(
                                                    'method_return_object', ctx)
        except Redirect as e:
            try:
                e.do_redirect()

                ctx.out_object = [None]

                # Now that the processing is switched to the outgoing message,
                # point ctx.protocol to ctx.out_protocol
                ctx.protocol = ctx.outprot_ctx

                # fire events
                self.event_manager.fire_event('method_redirect', ctx)
                if ctx.service_class is not None:
                    ctx.service_class.event_manager.fire_event(
                                                         'method_redirect', ctx)

            except Exception as e:
                logger_server.exception(e)
                ctx.out_error = Fault('Server',
                                             get_fault_string_from_exception(e))

                # fire events
                self.event_manager.fire_event('method_redirect_exception', ctx)
                if ctx.service_class is not None:
                    ctx.service_class.event_manager.fire_event(
                                               'method_redirect_exception', ctx)

        except Fault as e:
            if e.faultcode == 'Client' or e.faultcode.startswith('Client.'):
                logger_client.exception(e)
            else:
                logger.exception(e)

            ctx.out_error = e

            # fire events
            self.event_manager.fire_event('method_exception_object', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event(
                                               'method_exception_object', ctx)

        # we don't catch BaseException because we're not interested in
        # "system-exiting" exceptions. See:
        # https://docs.python.org/2/library/exceptions.html#exceptions.Exception
        except Exception as e:
            logger_server.exception(e)

            ctx.out_error = Fault('Server', get_fault_string_from_exception(e))

            # fire events
            self.event_manager.fire_event('method_exception_object', ctx)
            if ctx.service_class is not None:
                ctx.service_class.event_manager.fire_event(
                                                'method_exception_object', ctx)

    def call_wrapper(self, ctx):
        """This method calls the call_wrapper method in the service definition.
        This can be overridden to make an application-wide custom exception
        management.
        """

        if ctx.descriptor.body_style is BODY_STYLE_BARE:
            ctx.in_object = [ctx.in_object]
        elif ctx.descriptor.body_style is BODY_STYLE_EMPTY:
            ctx.in_object = []

        retval = None

        # service rpc
        if ctx.descriptor.no_self:
            retval = ctx.descriptor.service_class.call_wrapper(ctx)

        # class rpc
        else:
            cls = ctx.descriptor.parent_class
            if cls.__orig__ is not None:
                cls = cls.__orig__

            inst = cls.__respawn__(ctx)
            if inst is None:
                raise RespawnError('{%s}%s' %
                                     (cls.get_namespace(), cls.get_type_name()))
            in_cls = ctx.descriptor.in_message

            args = ctx.in_object
            if args is None:
                args = []

            elif ctx.descriptor.body_style is BODY_STYLE_WRAPPED and \
                                        len(in_cls.get_flat_type_info(in_cls)) <= 1:
                args = []

            else:
                args = args[1:]

            if ctx.descriptor.service_class is not None:
                ctx.in_object = [inst, ctx]
                ctx.in_object.extend(args)

                # hack to make sure inst goes first
                ctx.descriptor.no_ctx = True
                retval = ctx.descriptor.service_class.call_wrapper(ctx)

            elif ctx.function is not None:
                if ctx.descriptor.no_ctx:
                    retval = ctx.function(inst, *args)
                else:
                    retval = ctx.function(inst, ctx, *args)

        return retval

    def _has_callbacks(self):
        return self.interface._has_callbacks()

    def reinitialize(self, server):
        seen = set()

        from spyne import MethodDescriptor
        for d in self.interface.method_id_map.values():
            assert isinstance(d, MethodDescriptor)

            if d.aux is not None and not id(d.aux) in seen:
                d.aux.initialize(server)
                seen.add(id(d.aux))

            if d.service_class is not None and not id(d.service_class) in seen:
                d.service_class.initialize(server)
                seen.add(id(d.service_class))

    def __hash__(self):
        return hash(tuple((id(s) for s in self.services)))


text:
package com.intellij.openapi.roots.ui.configuration.classpath;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.ui.configuration.*;
import com.intellij.openapi.roots.ui.configuration.dependencyAnalysis.AnalyzeDependenciesDialog;
import com.intellij.openapi.roots.ui.configuration.libraryEditor.ChooseModulesDialog;
import com.intellij.openapi.roots.ui.configuration.libraryEditor.EditExistingLibraryDialog;
import com.intellij.openapi.roots.ui.configuration.projectRoot.FindUsagesInProjectStructureActionBase;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ModuleStructureConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.LibraryProjectStructureElement;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ModuleProjectStructureElement;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.SdkProjectStructureElement;
import com.intellij.openapi.roots.ui.util.CellAppearance;
import com.intellij.openapi.roots.ui.util.OrderEntryCellAppearanceUtils;
import com.intellij.openapi.ui.ComboBoxTableRenderer;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ui.Table;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ClasspathPanelImpl extends JPanel implements ClasspathPanel {
  private final Table myEntryTable;
  private final ClasspathTableModel myModel;
  private final EventDispatcher<OrderPanelListener> myListeners = EventDispatcher.create(OrderPanelListener.class);
  private List<AddItemPopupAction<?>> myPopupActions = null;
  private JButton myEditButton;
  private final ModuleConfigurationState myState;

  public ClasspathPanelImpl(ModuleConfigurationState state) {
    super(new BorderLayout());

    myState = state;
    myModel = new ClasspathTableModel(state, getStructureConfigurableContext());
    myEntryTable = new Table(myModel);
    myEntryTable.setShowGrid(false);
    myEntryTable.setDragEnabled(false);
    myEntryTable.setShowHorizontalLines(false);
    myEntryTable.setShowVerticalLines(false);
    myEntryTable.setIntercellSpacing(new Dimension(0, 0));

    myEntryTable.setDefaultRenderer(ClasspathTableItem.class, new TableItemRenderer(getStructureConfigurableContext()));
    myEntryTable.setDefaultRenderer(Boolean.class, new ExportFlagRenderer(myEntryTable.getDefaultRenderer(Boolean.class)));

    JComboBox scopeEditor = new JComboBox(new EnumComboBoxModel<DependencyScope>(DependencyScope.class));
    myEntryTable.setDefaultEditor(DependencyScope.class, new DefaultCellEditor(scopeEditor));
    myEntryTable.setDefaultRenderer(DependencyScope.class, new ComboBoxTableRenderer<DependencyScope>(DependencyScope.values()) {
        @Override
        protected String getTextFor(@NotNull final DependencyScope value) {
          return value.getDisplayName();
        }
      });

    myEntryTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    new SpeedSearchBase<Table>(myEntryTable) {
      public int getSelectedIndex() {
        return myEntryTable.getSelectedRow();
      }

      @Override
      protected int convertIndexToModel(int viewIndex) {
        return myEntryTable.convertRowIndexToModel(viewIndex);
      }

      public Object[] getAllElements() {
        final int count = myModel.getRowCount();
        Object[] elements = new Object[count];
        for (int idx = 0; idx < count; idx++) {
          elements[idx] = myModel.getItemAt(idx);
        }
        return elements;
      }

      public String getElementText(Object element) {
        return getCellAppearance((ClasspathTableItem<?>)element, getStructureConfigurableContext(), false).getText();
      }

      public void selectElement(Object element, String selectedText) {
        final int count = myModel.getRowCount();
        for (int row = 0; row < count; row++) {
          if (element.equals(myModel.getItemAt(row))) {
            final int viewRow = myEntryTable.convertRowIndexToView(row);
            myEntryTable.getSelectionModel().setSelectionInterval(viewRow, viewRow);
            TableUtil.scrollSelectionToVisible(myEntryTable);
            break;
          }
        }
      }
    };

    setFixedColumnWidth(ClasspathTableModel.EXPORT_COLUMN, ClasspathTableModel.EXPORT_COLUMN_NAME);
    setFixedColumnWidth(ClasspathTableModel.SCOPE_COLUMN, DependencyScope.COMPILE.toString() + "     ");  // leave space for combobox border

    myEntryTable.registerKeyboardAction(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          final int[] selectedRows = myEntryTable.getSelectedRows();
          boolean currentlyMarked = true;
          for (final int selectedRow : selectedRows) {
            final ClasspathTableItem<?> item = myModel.getItemAt(myEntryTable.convertRowIndexToModel(selectedRow));
            if (selectedRow < 0 || !item.isExportable()) {
              return;
            }
            currentlyMarked &= item.isExported();
          }
          for (final int selectedRow : selectedRows) {
            myModel.getItemAt(myEntryTable.convertRowIndexToModel(selectedRow)).setExported(!currentlyMarked);
          }
          myModel.fireTableDataChanged();
          TableUtil.selectRows(myEntryTable, selectedRows);
        }
      },
      KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
      WHEN_FOCUSED
    );

    add(ScrollPaneFactory.createScrollPane(myEntryTable), BorderLayout.CENTER);
    add(createButtonsBlock(), BorderLayout.EAST);

    if (myEntryTable.getRowCount() > 0) {
      myEntryTable.getSelectionModel().setSelectionInterval(0,0);
    }

    myEntryTable.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2){
          navigate(true);
        }
      }
    });

    DefaultActionGroup actionGroup = new DefaultActionGroup();
    final AnAction navigateAction = new AnAction(ProjectBundle.message("classpath.panel.navigate.action.text")) {
      public void actionPerformed(AnActionEvent e) {
        navigate(false);
      }

      public void update(AnActionEvent e) {
        final Presentation presentation = e.getPresentation();
        presentation.setEnabled(false);
        if (myEntryTable.getSelectedRowCount() != 1) return;
        final OrderEntry entry = myModel.getItemAt(myEntryTable.getSelectedRow()).getEntry();
        if (entry != null && entry.isValid()){
          if (!(entry instanceof ModuleSourceOrderEntry)){
            presentation.setEnabled(true);
          }
        }
      }
    };
    navigateAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(),
                                             myEntryTable);
    actionGroup.add(navigateAction);
    actionGroup.add(new MyFindUsagesAction());
    PopupHandler.installPopupHandler(myEntryTable, actionGroup, ActionPlaces.UNKNOWN, ActionManager.getInstance());
  }

  private void setFixedColumnWidth(final int columnIndex, final String textToMeasure) {
    final FontMetrics fontMetrics = myEntryTable.getFontMetrics(myEntryTable.getFont());
    final int width = fontMetrics.stringWidth(" " + textToMeasure + " ") + 4;
    final TableColumn checkboxColumn = myEntryTable.getTableHeader().getColumnModel().getColumn(columnIndex);
    checkboxColumn.setWidth(width);
    checkboxColumn.setPreferredWidth(width);
    checkboxColumn.setMaxWidth(width);
    checkboxColumn.setMinWidth(width);
  }

  private void navigate(boolean openLibraryEditor) {
    final int selectedRow = myEntryTable.getSelectedRow();
    final OrderEntry entry = myModel.getItemAt(selectedRow).getEntry();
    final ProjectStructureConfigurable rootConfigurable = ProjectStructureConfigurable.getInstance(myState.getProject());
    if (entry instanceof ModuleOrderEntry){
      Module module = ((ModuleOrderEntry)entry).getModule();
      if (module != null) {
        rootConfigurable.select(module.getName(), null, true);
      }
    }
    else if (entry instanceof LibraryOrderEntry){
      if (!openLibraryEditor) {
        rootConfigurable.select((LibraryOrderEntry)entry, true);
      }
      else {
        myEditButton.doClick();
      }
    }
    else if (entry instanceof JdkOrderEntry) {
      Sdk jdk = ((JdkOrderEntry)entry).getJdk();
      if (jdk != null) {
        rootConfigurable.select(jdk, true);
      }
    }
  }

  private JComponent createButtonsBlock() {
    final boolean isAnalyzeShown = ((ApplicationEx)ApplicationManager.getApplication()).isInternal();

    final JButton addButton = new JButton(ProjectBundle.message("button.add"));
    final JButton removeButton = new JButton(ProjectBundle.message("button.remove"));
    myEditButton = new JButton(ProjectBundle.message("module.classpath.button.edit"));
    final JButton upButton = new JButton(ProjectBundle.message("module.classpath.button.move.up"));
    final JButton downButton = new JButton(ProjectBundle.message("module.classpath.button.move.down"));
    final JButton analyzeButton = isAnalyzeShown ? new JButton(ProjectBundle.message("classpath.panel.analyze")) : null;

    final JPanel panel = new JPanel(new GridBagLayout());
    panel.add(addButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    panel.add(removeButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    panel.add(myEditButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    panel.add(upButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    panel.add(downButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, isAnalyzeShown ? 0.0 : 0.1, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    if( isAnalyzeShown) {
      panel.add(analyzeButton, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 0), 0, 0));
    }

    myEntryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
          return;
        }
        final int[] selectedRows = myEntryTable.getSelectedRows();
        boolean removeButtonEnabled = true;
        int minRow = myEntryTable.getRowCount() + 1;
        int maxRow = -1;
        for (final int selectedRow : selectedRows) {
          minRow = Math.min(minRow, selectedRow);
          maxRow = Math.max(maxRow, selectedRow);
          final ClasspathTableItem<?> item = myModel.getItemAt(selectedRow);
          if (!item.isRemovable()) {
            removeButtonEnabled = false;
          }
        }
        upButton.setEnabled(minRow > 0 && minRow < myEntryTable.getRowCount());
        downButton.setEnabled(maxRow >= 0 && maxRow < myEntryTable.getRowCount() - 1);
        removeButton.setEnabled(removeButtonEnabled);
        ClasspathTableItem<?> selectedItem = selectedRows.length == 1 ? myModel.getItemAt(selectedRows[0]) : null;
        myEditButton.setEnabled(selectedItem != null && selectedItem.isEditable());
      }
    });

    upButton.addActionListener(new ClasspathPanelAction(this) {
      @Override
      public void run() {
        moveSelectedRows(-1);
      }
    });
    downButton.addActionListener(new ClasspathPanelAction(this) {
      @Override
      public void run() {
        moveSelectedRows(+1);
      }
    });

    if(isAnalyzeShown) {
      analyzeButton.addActionListener(new ClasspathPanelAction(this) {
        @Override
        public void run() {
          AnalyzeDependenciesDialog.show(getRootModel().getModule());
        }
      });
    }

    addKeyboardShortcut(myEntryTable, removeButton, KeyEvent.VK_DELETE, 0);
    addKeyboardShortcut(myEntryTable, addButton, KeyEvent.VK_INSERT, 0);
    addKeyboardShortcut(myEntryTable, upButton, KeyEvent.VK_UP, KeyEvent.CTRL_DOWN_MASK);
    addKeyboardShortcut(myEntryTable, downButton, KeyEvent.VK_DOWN, KeyEvent.CTRL_DOWN_MASK);

    addButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        initPopupActions();
        final JBPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<AddItemPopupAction<?>>(null, myPopupActions) {
          @Override
          public Icon getIconFor(AddItemPopupAction<?> aValue) {
            return aValue.getIcon();
          }

          @Override
          public boolean hasSubstep(AddItemPopupAction<?> selectedValue) {
            return selectedValue.hasSubStep();
          }

          public boolean isMnemonicsNavigationEnabled() {
            return true;
          }
          public PopupStep onChosen(final AddItemPopupAction<?> selectedValue, final boolean finalChoice) {
            if (selectedValue.hasSubStep()) {
              return selectedValue.createSubStep();
            }
            return doFinalStep(new Runnable() {
              public void run() {
                selectedValue.execute();
              }
            });
          }
          @NotNull
          public String getTextFor(AddItemPopupAction<?> value) {
            return "&" + value.getIndex() + "  " + value.getTitle();
          }
        });
        popup.showUnderneathOf(addButton);
      }
    });

    removeButton.addActionListener(new ClasspathPanelAction(this) {
      @Override
      public void run() {
        final List removedRows = TableUtil.removeSelectedItems(myEntryTable);
        if (removedRows.isEmpty()) {
          return;
        }
        for (final Object removedRow : removedRows) {
          final ClasspathTableItem<?> item = (ClasspathTableItem<?>)((Object[])removedRow)[ClasspathTableModel.ITEM_COLUMN];
          final OrderEntry orderEntry = item.getEntry();
          if (orderEntry == null) {
            continue;
          }

          getRootModel().removeOrderEntry(orderEntry);
        }
        final int[] selectedRows = myEntryTable.getSelectedRows();
        myModel.fireTableDataChanged();
        TableUtil.selectRows(myEntryTable, selectedRows);
        final StructureConfigurableContext context = ModuleStructureConfigurable.getInstance(myState.getProject()).getContext();
        context.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(context, getRootModel().getModule()));
      }
    });

    myEditButton.addActionListener(new ActionListener() {
      public void actionPerformed(final ActionEvent e) {
        final int row = myEntryTable.getSelectedRow();
        final ClasspathTableItem<?> item = myModel.getItemAt(row);
        final OrderEntry entry = item.getEntry();
        if (!(entry instanceof LibraryOrderEntry)) return;

        final Library library = ((LibraryOrderEntry)entry).getLibrary();
        if (library == null) {
          return;
        }
        final LibraryTableModifiableModelProvider provider;
        final LibraryTable table = library.getTable();
        if (table == null) {
          final LibraryTable moduleLibraryTable = getRootModel().getModuleLibraryTable();
          provider = new LibraryTableModifiableModelProvider() {
            public LibraryTable.ModifiableModel getModifiableModel() {
              return moduleLibraryTable.getModifiableModel();
            }

          };
        }
        else {
          provider = getStructureConfigurableContext().createModifiableModelProvider(table.getTableLevel());
        }
        EditExistingLibraryDialog dialog = EditExistingLibraryDialog.createDialog(ClasspathPanelImpl.this, provider, library, myState.getProject());
        dialog.setContextModule(getRootModel().getModule());
        dialog.show();
        myEntryTable.repaint();
        ModuleStructureConfigurable.getInstance(myState.getProject()).getTree().repaint();
      }
    });
    return panel;
  }

  private static void addKeyboardShortcut(final JComponent target, final JButton button, final int keyEvent, final int modifiers) {
    target.registerKeyboardAction(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          if (button.isEnabled()) {
            button.doClick();
          }
        }
      },
      KeyStroke.getKeyStroke(keyEvent, modifiers),
      WHEN_FOCUSED
    );
  }

  @Override
  public void runClasspathPanelAction(Runnable action) {
    try {
      disableModelUpdate();
      action.run();
    }
    finally {
      enableModelUpdate();
      myEntryTable.requestFocus();
    }
  }

  @Override
  public void addItems(List<ClasspathTableItem<?>> toAdd) {
    for (ClasspathTableItem<?> item : toAdd) {
      myModel.addItem(item);
    }
    myModel.fireTableDataChanged();
    final ListSelectionModel selectionModel = myEntryTable.getSelectionModel();
    selectionModel.setSelectionInterval(myModel.getRowCount() - toAdd.size(), myModel.getRowCount() - 1);
    TableUtil.scrollSelectionToVisible(myEntryTable);

    final StructureConfigurableContext context = ModuleStructureConfigurable.getInstance(myState.getProject()).getContext();
    context.getDaemonAnalyzer().queueUpdate(new ModuleProjectStructureElement(context, getRootModel().getModule()));
  }

  @Override
  public ModifiableRootModel getRootModel() {
    return myState.getRootModel();
  }

  @Override
  public Project getProject() {
    return myState.getProject();
  }

  @Override
  public JComponent getComponent() {
    return this;
  }

  public void rootsChanged() {
    forceInitFromModel();
  }

  private void initPopupActions() {
    if (myPopupActions == null) {
      int actionIndex = 1;
      final List<AddItemPopupAction<?>> actions = new ArrayList<AddItemPopupAction<?>>();
      final StructureConfigurableContext context = getStructureConfigurableContext();
      actions.add(new AddSingleEntryModuleLibraryAction(this, actionIndex++, context));
      actions.add(new AddLibraryAction(this, actionIndex++, ProjectBundle.message("classpath.add.library.action"), context));
      actions.add(new AddItemPopupAction<Module>(this, actionIndex, ProjectBundle.message("classpath.add.module.dependency.action"),
                                                 StdModuleTypes.JAVA.getNodeIcon(false)) {
          protected ClasspathTableItem<?> createTableItem(final Module item) {
            return ClasspathTableItem.createItem(getRootModel().addModuleOrderEntry(item), context);
          }
          protected ClasspathElementChooser<Module> createChooser() {
            final List<Module> chooseItems = getDependencyModules();
            if (chooseItems.isEmpty()) {
              Messages.showMessageDialog(ClasspathPanelImpl.this, ProjectBundle.message("message.no.module.dependency.candidates"), getTitle(), Messages.getInformationIcon());
              return null;
            }
            return new ModuleChooser(chooseItems, ProjectBundle.message("classpath.chooser.title.add.module.dependency"));
          }
        }
      );

      myPopupActions = actions;
    }
  }

  private StructureConfigurableContext getStructureConfigurableContext() {
    return ProjectStructureConfigurable.getInstance(myState.getProject()).getContext();
  }

  private void enableModelUpdate() {
    myInsideChange--;
  }

  private void disableModelUpdate() {
    myInsideChange++;
  }

  public void addListener(OrderPanelListener listener) {
    myListeners.addListener(listener);
  }

  public void removeListener(OrderPanelListener listener) {
    myListeners.removeListener(listener);
  }

  private void moveSelectedRows(int increment) {
    if (increment == 0) {
      return;
    }
    if (myEntryTable.isEditing()){
      myEntryTable.getCellEditor().stopCellEditing();
    }
    final ListSelectionModel selectionModel = myEntryTable.getSelectionModel();
    for(int row = increment < 0? 0 : myModel.getRowCount() - 1; increment < 0? row < myModel.getRowCount() : row >= 0; row +=
      increment < 0? +1 : -1){
      if (selectionModel.isSelectedIndex(row)) {
        final int newRow = moveRow(row, increment);
        selectionModel.removeSelectionInterval(row, row);
        selectionModel.addSelectionInterval(newRow, newRow);
      }
    }
    myModel.fireTableRowsUpdated(0, myModel.getRowCount() - 1);
    Rectangle cellRect = myEntryTable.getCellRect(selectionModel.getMinSelectionIndex(), 0, true);
    if (cellRect != null) {
      myEntryTable.scrollRectToVisible(cellRect);
    }
    myEntryTable.repaint();
    myListeners.getMulticaster().entryMoved();
  }

  public void selectOrderEntry(@NotNull OrderEntry entry) {
    for (int row = 0; row < myModel.getRowCount(); row++) {
      if (entry.getPresentableName().equals(myModel.getItemAt(row).getEntry().getPresentableName())) {
        myEntryTable.getSelectionModel().setSelectionInterval(row, row);
        TableUtil.scrollSelectionToVisible(myEntryTable);
      }
    }
    IdeFocusManager.getInstance(myState.getProject()).requestFocus(myEntryTable, true);
  }

  private int moveRow(final int row, final int increment) {
    int newIndex = Math.abs(row + increment) % myModel.getRowCount();
    final ClasspathTableItem<?> item = myModel.removeDataRow(row);
    myModel.addItemAt(item, newIndex);
    return newIndex;
  }

  public void stopEditing() {
    TableUtil.stopEditing(myEntryTable);
  }

  public List<OrderEntry> getEntries() {
    final int count = myModel.getRowCount();
    final List<OrderEntry> entries = new ArrayList<OrderEntry>(count);
    for (int row = 0; row < count; row++) {
      final OrderEntry entry = myModel.getItemAt(row).getEntry();
      if (entry != null) {
        entries.add(entry);
      }
    }
    return entries;
  }

  private int myInsideChange = 0;
  public void initFromModel() {
    if (myInsideChange == 0) {
      forceInitFromModel();
    }
  }

  public void forceInitFromModel() {
    final int[] selection = myEntryTable.getSelectedRows();
    myModel.clear();
    myModel.init();
    myModel.fireTableDataChanged();
    TableUtil.selectRows(myEntryTable, selection);
  }

  private List<Module> getDependencyModules() {
    final int rowCount = myModel.getRowCount();
    final Set<String> filtered = new HashSet<String>(rowCount);
    for (int row = 0; row < rowCount; row++) {
      final OrderEntry entry = myModel.getItemAt(row).getEntry();
      if (entry instanceof ModuleOrderEntry) {
        filtered.add(((ModuleOrderEntry)entry).getModuleName());
      }
    }
    final ModulesProvider modulesProvider = myState.getModulesProvider();
    final Module self = modulesProvider.getModule(getRootModel().getModule().getName());
    filtered.add(self.getName());

    final Module[] modules = modulesProvider.getModules();
    final List<Module> elements = new ArrayList<Module>(modules.length);
    for (final Module module : modules) {
      if (!filtered.contains(module.getName())) {
        elements.add(module);
      }
    }
    return elements;
  }

  private static CellAppearance getCellAppearance(final ClasspathTableItem<?> item,
                                                  StructureConfigurableContext context,
                                                  final boolean selected) {
    if (item instanceof InvalidJdkItem) {
      return OrderEntryCellAppearanceUtils.forJdk(null, false, selected);
    }
    else {
      return ProjectStructureDialogCellAppearanceUtils.forOrderEntry(item.getEntry(), context, selected);
    }
  }

  private static class TableItemRenderer extends ColoredTableCellRenderer {
    private final Border NO_FOCUS_BORDER = BorderFactory.createEmptyBorder(1, 1, 1, 1);
    private StructureConfigurableContext myContext;

    public TableItemRenderer(StructureConfigurableContext context) {
      myContext = context;
    }

    protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
      setPaintFocusBorder(false);
      setFocusBorderAroundIcon(true);
      setBorder(NO_FOCUS_BORDER);
      if (value instanceof ClasspathTableItem<?>) {
        final ClasspathTableItem<?> tableItem = (ClasspathTableItem<?>)value;
        getCellAppearance(tableItem, myContext, selected).customize(this);
        String tooltip = tableItem.getTooltipText();
        if (tooltip != null) {
          setToolTipText(tooltip);
        }
      }
    }
  }

  private static class ExportFlagRenderer implements TableCellRenderer {
    private final TableCellRenderer myDelegate;
    private final JPanel myBlankPanel;

    public ExportFlagRenderer(TableCellRenderer delegate) {
      myDelegate = delegate;
      myBlankPanel = new JPanel();
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      if (!table.isCellEditable(row, column)) {
        myBlankPanel.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
        return myBlankPanel;
      }
      return myDelegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
  }

  private class ModuleChooser extends ChooseModulesDialog implements ClasspathElementChooser<Module> {
    public ModuleChooser(final List<Module> items, final String title) {
      super(ClasspathPanelImpl.this, items, title);
    }

    public void doChoose() {
      show();
    }

    public void dispose() {
      super.dispose();
    }
  }

  private class MyFindUsagesAction extends FindUsagesInProjectStructureActionBase {
    private MyFindUsagesAction() {
      super(myEntryTable, myState.getProject());
    }

    protected boolean isEnabled() {
      return getSelectedElement() != null;
    }

    protected ProjectStructureElement getSelectedElement() {
      int row = myEntryTable.getSelectedRow();
      if (0 <= row && row < myModel.getRowCount()) {
        ClasspathTableItem<?> item = myModel.getItemAt(row);
        final OrderEntry entry = item.getEntry();
        if (entry instanceof LibraryOrderEntry) {
          final Library library = ((LibraryOrderEntry)entry).getLibrary();
          if (library != null) {
            return new LibraryProjectStructureElement(getContext(), library);
          }
        }
        else if (entry instanceof ModuleOrderEntry) {
          final Module module = ((ModuleOrderEntry)entry).getModule();
          if (module != null) {
            return new ModuleProjectStructureElement(getContext(), module);
          }
        }
        else if (entry instanceof JdkOrderEntry) {
          final Sdk jdk = ((JdkOrderEntry)entry).getJdk();
          if (jdk != null) {
            return new SdkProjectStructureElement(getContext(), jdk);
          }
        }
      }
      return null;
    }

    protected RelativePoint getPointToShowResults() {
      Rectangle rect = myEntryTable.getCellRect(myEntryTable.getSelectedRow(), 1, false);
      Point location = rect.getLocation();
      location.y += rect.height;
      return new RelativePoint(myEntryTable, location);
    }
  }

}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

Example
## [0.0.x] 2017-04-26
### Summary
 * This is a quick summary for people to understand what this release is about.

### Fixed
 * Fixed broke thing 1 (DevMattm)

### Added
 * Added cool new feature (DevMattm)

### Changed
 * Changed something to make more awesome (DevMattm)

-------------------------------------------------------------------------
-------------------------------------------------------------------------

##[0.1.0]
 * Add DicomImage class
 * Add logger (Lumberjack)
 * Add id csv

##[0.0.1]
 * Add gitignore
 * Create README.md, CHANGELOG.md, AUTHORS and LICENSE
 * Add config file
 * Write polyjuice.py
 * Add DicomCaretaker class


text:
package errorlog

import (
	"errors"
	"net/http"

	"github.com/op/go-logging"
	"github.com/tobi/airbrake-go"
)

func AirbrakeRecoverer(apiKey string) func(http.Handler) http.Handler {
	airbrake.ApiKey = apiKey
	f := func(h http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			if apiKey != "" {
				defer airbrake.CapturePanic(r)
			}
			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
	return f
}

type AirbrakeBackend struct {
	ApiKey string
}

func NewAirbrakeBackend(apiKey string) *AirbrakeBackend {
	backend := &AirbrakeBackend{
		ApiKey: apiKey,
	}
	airbrake.ApiKey = backend.ApiKey
	return backend
}

func (b *AirbrakeBackend) Log(level logging.Level, calldepth int, rec *logging.Record) error {
	e := errors.New(rec.Formatted(calldepth + 1))
	return airbrake.Notify(e)
}


text:
import 'ionic';

let settings = {
  websiteHost: 'http://www.cc98.org/',
  staticFileHost: 'http://file.cc98.org/',
  apiEndpoint: 'http://api.cc98.org/',
  authorizeEndpoint: 'http://login.cc98.org/oauth/authorize',
  tokenEndpoint: 'http://login.cc98.org/oauth/token'
};

export default angular
  .module('settings', [])
  .value('settings', settings);