text:
import { GraphQLError } from 'graphql';
export declare function isApolloError(err: Error): err is ApolloError;
export declare class ApolloError extends Error {
    message: string;
    graphQLErrors: GraphQLError[];
    networkError: Error | null;
    extraInfo: any;
    constructor({graphQLErrors, networkError, errorMessage, extraInfo}: {
        graphQLErrors?: GraphQLError[];
        networkError?: Error | null;
        errorMessage?: string;
        extraInfo?: any;
    });
}


text:
package eu.cyfronoid.core.property;

public class PropertyBuilder<T> {
    private boolean isAllowSetNotNull = true;
    private boolean isAllowGetNull = true;
    private String valueName;

    public static <T> Property<T> create() {
        return new PropertyBuilder<T>().build();
    }

    public static <T> Property<T> create(String name) {
        return new PropertyBuilder<T>().setName(name).build();
    }

    public static <T> Property<T> createSafe() {
        return new PropertyBuilder<T>().doNotAllowGetNull().doNotAllowSetNotNull().build();
    }

    public static <T> Property<T> createSafe(String name) {
        return new PropertyBuilder<T>().doNotAllowGetNull().doNotAllowSetNotNull().setName(name).build();
    }

    public PropertyBuilder<T> setName(String name) {
        valueName = name;
        return this;
    }

    public PropertyBuilder<T> doNotAllowSetNotNull() {
        isAllowSetNotNull = false;
        return this;
    }

    public PropertyBuilder<T> doNotAllowGetNull() {
        isAllowGetNull = false;
        return this;
    }

    public Property<T> build() {
        return new Property<T>() {
            private boolean allowSetNotNull = isAllowSetNotNull;
            private boolean allowGetNull = isAllowGetNull;
            private String name = valueName;
            private T value;

            public void set(T value) {
                if(this.value != null && !allowSetNotNull) {
                    throw new IllegalArgumentException("It is not allowed to set the value if it is already set. Value name: " + getName());
                }
                this.value = value;
            }

            public T get() {
                if(value == null && !allowGetNull) {
                    throw new IllegalArgumentException("It is not allowed to get the value if it is not set yet. Use isNotNull() first. Value name: " + getName());
                }
                return value;
            }

            public boolean isNotNull() {
                return value != null;
            }

            public boolean isNull() {
                return value == null;
            }

            @Override
            public String toString() {
                return String.valueOf(get());
            }

            private String getName() {
                return name != null ? name : "<not set>";
            }

        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Blueprint = require('ember-cli/lib/models/blueprint');
var isPackageMissing = require('ember-cli-is-package-missing');

module.exports = {
  description: 'Creates an extended version of Embers HTTP Mocks, including a DataStore',

  normalizeEntityName: function() {},

  // Largely borrowed from http-mock blueprint
  beforeInstall: function(options) {
    var serverBlueprint = Blueprint.lookup('server', {
      ui: this.ui,
      analytics: this.analytics,
      project: this.project
    });

    return serverBlueprint.install(options);
  },

  afterInstall: function(options) {

    if (!options.dryRun && isPackageMissing(this, 'express')) {
      return this.addPackagesToProject([
        { name: 'express', target: '^4.8.5' },
        { name: 'body-parser' }
      ]);
    }

  }

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  // afterInstall: function(options) {
  //   // Perform extra work here.
  // }
};


text: Rails.application.config.session_store :cookie_store, key: '_found_20150625_session'


text:
from PIL import Image, ImageDraw, ImageFont
import random
import math, string

class RandomChar():
    """用于随机生成汉字"""

    @staticmethod
    def Unicode():
        val = random.randint(0x4E00, 0x9FBF)
        return unichr(val)

    @staticmethod
    def GB2312():
        head = random.randint(0xB0, 0xCF)
        body = random.randint(0xA, 0xF)
        tail = random.randint(0, 0xF)
        val = (head << 8) | (body << 4) | tail
        str = "%x" % val
        return str.decode('hex').decode('gb2312')

class ImageChar():
    def __init__(self, fontColor=(0, 0, 0),
                 size=(100, 40),
                 fontPath='wqy.ttc',
                 bgColor=(255, 255, 255),
                 fontSize=20):
        self.size = size
        self.fontPath = fontPath
        self.bgColor = bgColor
        self.fontSize = fontSize
        self.fontColor = fontColor
        self.font = ImageFont.truetype(self.fontSize)
        self.image = Image.new('RGB', size, bgColor)

    def rotate(self):
        self.image.rotate(random.randint(0, 30), expand=0)

    def drawText(self, pos, txt, fill):
        draw = ImageDraw.Draw(self.image)
        draw.text(pos, txt, font=self.font, fill=fill)
        del draw

    def randRGB(self):
        return (random.randint(0, 255),
                random.randint(0, 255),
                random.randint(0, 255))

    def randPoint(self):
        (width, height) = self.size
        return (random.randint(0, width), random.randint(0, height))

    def randLine(self, num):
        draw = ImageDraw.Draw(self.image)
        for i in range(0, num):
            draw.line([self.randPoint(), self.randPoint()], self.randRGB())
        del draw

    def randChinese(self, num):
        gap = 5
        start = 0
        for i in range(0, num):
            char = RandomChar().GB2312()
            x = start + self.fontSize * i + random.randint(0, gap) + gap * i
            self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
            self.rotate()
        self.randLine(18)

    def save(self, path):
        self.image.save(path)

if __name__ == '__main__':
    ImageChar(fontPath=None).save("a.png")


text:
<?xml version='1.0' encoding='UTF-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>net.sf.m-m-m</groupId>
    <artifactId>mmm-util-modules</artifactId>
    <version>dev-SNAPSHOT</version>
    <relativePath>../modules/pom.xml</relativePath>
  </parent>
  <artifactId>mmm-util-exception</artifactId>
  <version>${net.sf.mmm.util.version}</version>
  <packaging>jar</packaging>
  <name>${project.artifactId}</name>
  <description>provides generic reusable exceptions with native-language-support (NLS).</description>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>mmm-util-nls</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>mmm-util-reflect</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- JSR 303 optional for ValidationErrorUserException -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- Spring-context optional for OptimisticLockingException -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- Spring-orm optional for OptimisticLockingExceptionSpring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- Hibernate optional for OptimisticLockingExceptionHibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>mmm-util-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
#include "TaskScheduler.hpp"

namespace NUClear {
namespace threading {

    TaskScheduler::TaskScheduler() : running(true) {}

    void TaskScheduler::shutdown() {
        {
            std::lock_guard<std::mutex> lock(mutex);
            running = false;
        }
        condition.notify_all();
    }

    void TaskScheduler::submit(std::unique_ptr<ReactionTask>&& task) {

        // We do not accept new tasks once we are shutdown
        if (running) {

            /* Mutex Scope */ {
                std::lock_guard<std::mutex> lock(mutex);
                queue.push(std::forward<std::unique_ptr<ReactionTask>>(task));
            }
        }

        // Notify a thread that it can proceed
        condition.notify_one();
    }

    std::unique_ptr<ReactionTask> TaskScheduler::get_task() {

        // Obtain the lock
        std::unique_lock<std::mutex> lock(mutex);

        // While our queue is empty
        while (queue.empty()) {

            // If the queue is empty we either wait or shutdown
            if (!running) {

                // Notify any other threads that might be waiting on this condition
                condition.notify_all();

                // Return a nullptr to signify there is nothing on the queue
                return nullptr;
            }

            // Wait for something to happen!
            condition.wait(lock);
        }

        // Return the type
        // If you're wondering why all the ridiculousness, it's because priority queue is not as feature complete as it
        // should be its 'top' method returns a const reference (which we can't use to move a unique pointer)
        std::unique_ptr<ReactionTask> task(
            std::move(const_cast<std::unique_ptr<ReactionTask>&>(queue.top())));  // NOLINT
        queue.pop();

        return task;
    }
}  // namespace threading
}  // namespace NUClear


text:
Pux
=============
Pux is a high performance PHP router.

Pux is 48.5x faster than symfony router in static route dispatching, 31x faster in regular expression dispatching. (with pux extension installed)

(Benchmark code and details here https://github.com/c9s/router-benchmark/blob/master/code)

Pux tries not to consume computation time to build all routes dynamically (like
Symfony/Routing, although the RouteCompiler of Symfony/Routing caches the
compiled patterns, but there are still a lot of function call and class
loading from your application code. however, function calls are pretty slow in PHP).

[![Build Status](https://travis-ci.org/c9s/Pux.png?branch=master)](https://travis-ci.org/c9s/Pux)

Why It's Faster
---------------

- Pux uses simpler data structure (indexed array) to store the patterns and flags.
    (In PHP internals, `zend_hash_index_find` is faster than `zend_hash_find`).

- When matching routes, symfony uses a lot of function calls for each route:

    https://github.com/symfony/Routing/blob/master/Matcher/UrlMatcher.php#L124

    Pux fetches the pattern from an indexed-array:

    https://github.com/c9s/Pux/blob/master/src/Pux/Mux.php#L189

- Even you enabled APC or other bytecode cache extension, you are still calling
  methods and functions in the runtime. Pux reduces the route building to one
  static method call. `__set_state`.

- Pux separates static routes and dynamic routes automatically, Pux uses hash
  table to look up static routes without looping the whole route array.

- Pux\\Mux is written in C extension, method calls are faster!

- With C extension, there is no class loading overhead.

- Pux compiles your routes to plain PHP array, the compiled routes can be
  loaded very fast. you don't need to call functions to register your routes before using it.

Why It's Here
--------------------
Most of us use a lot of machines to run our applications, however, it uses too much energy and too many resources.

By using Pux, you can also decrease your expense of servers on cloud.

Also we believe that running softwares on slower machines should be easy as possible.

Some people thinks routing is not the bottleneck, the truth is this project
does not claim routing is the bottleneck.

Actually the bottleneck is always different in different applications, if you
have a lot of heavy db requests, then your bottleneck is your db; if you have a
lot of complex computation, then the bottleneck should be your algorithm.

You might start wondering since the bottleneck is not routing, why do we
implement route dispatcher in C extension? The answer is simple, if you put a
pure PHP routing component with some empty callbacks and use apache benchmark
tool to see how many requests you can handle per second, you will find out the
routing component consumes a lot of computation time and the request number
will decrease quite a few. (and it does nothing, all it does is ... just
routing!)

So Pux tries to reduce the overheads of loading PHP classes and the runtime
method/function calls, and you can run your application faster without the overheads.

Features
--------------------

- Zero dependency.
- Low memory footprint (only 6KB with simple routes and extension installed) .
- High performance of dispatching routes.
- PCRE pattern path support. (Sinatra-style)
- Request method condition support.
- Domain condition support.
- https condition support.

Routing Path Format
---------------------

    /post
    /post/:id                  => matches /post/33
    /post/:id(/:title)         => matches /post/33, /post/33/post%20title
    /post/:id(\.:format)       => matches /post/33, /post/33.json .. /post/33.xml

Installation
--------------------
You can install Pux with composer by defining the following requirement in your composer.json:

```json
{
    "require": {
        "corneltek/pux": "~1.3"
    }
}
```

### Install Extension

To install pux extension to boost the performance:

```sh
git clone https://github.com/c9s/Pux.git
cd Pux/ext
phpize
./configure
make && make install
```

Or you can configure the optimization flag to gain more when running `configure` command.:

```sh
CFLAGS="-O3" ./configure
```

Then setup your php.ini config to load pux extension:

```ini
extension=pux.so
```

Synopsis
------------

The routing usage is dead simple:

```php
require 'vendor/autoload.php'; // use PCRE patterns you need Pux\PatternCompiler class.
use Pux\Executor;

class ProductController {
    public function listAction() {
        return 'product list';
    }
    public function itemAction($id) {
        return "product $id";
    }
}
$mux = new Pux\Mux;
$mux->add('/product', ['ProductController','listAction']);
$mux->add('/product/:id', ['ProductController','itemAction'] , [
    'require' => [ 'id' => '\d+', ],
    'default' => [ 'id' => '1', ]
]);
$route = $mux->dispatch('/product/1');
Executor::execute($route);
```

Examples
--------------------

### Basic Example

```php
require 'vendor/autoload.php';
use Pux\Mux;
use Pux\Executor;
$mux = new Mux;
$mux->get('/get', ['HelloController','helloAction']);
$mux->post('/post', ['HelloController','helloAction']);
$mux->put('/put', ['HelloController','helloAction']);
$route = $mux->dispatch( $_SERVER['PATH_INFO'] );
echo Executor::execute($route);
```

### Through Compiled Mux

Define your routing definition in `routes.php`:

```php
require 'vendor/autoload.php';
use Pux\Mux;
$mux = new Mux;
$mux->get('/get', ['HelloController','helloAction']);
return $mux;
```

Run pux command to compile your routing definition:

```sh
curl -O https://raw.github.com/c9s/Pux/master/pux
chmod +x pux
pux compile -o mux.php routes.php
```

Load the mux object from your application code:

```php
require 'vendor/autoload.php';
$mux = require 'mux.php';
$route = $mux->dispatch( $_SERVER['PATH_INFO'] );
echo Executor::execute($route);
```

> Please note that if you need PCRE pattern support for route, you must load `Pux/PatternCompiler.php` before you use.

Mux
-----
Mux is where you define your routes, and you can mount multiple mux to a parent one.

```php
$mainMux = new Mux;
$mainMux->expand = true;

$pageMux = new Mux;
$pageMux->add('/page1', [ 'PageController', 'page1' ]);
$pageMux->add('/page2', [ 'PageController', 'page2' ]);

$mainMux->mount('/sub', $pageMux);

foreach( ['/sub/page1', '/sub/page2'] as $p ) {
    $r = $mainMux->dispatch($p);
    ok($r, "Matched route for $p");
}
```

The `expand` option means whether to expand/merge submux routes to the parent mux.

When expand is enabled, it improves dispatch performance when you
have a lot of sub mux to dispatch.

### Sorting routes

You need to sort routes when not using compiled routes, it's because pux sorts
longer path to front:

```php
$pageMux = new Mux;
$pageMux->add('/', [ 'PageController', 'page1' ]);
$pageMux->add('/pa', [ 'PageController', 'page1' ]);
$pageMux->add('/page', [ 'PageController', 'page1' ]);
$pageMux->sort();
```

This sorts routes to:

```
/page
/pa
/
```

So pux first compares `/page`, `/pa`, than `/`.

### Different String Comparison Strategies

When expand is enabled, the pattern comparison strategy for
strings will match the full string.

When expand is disabled, the pattern comparison strategy for
strings will match the prefix.

APCDispatcher
----------------------
Although Pux\\Mux is already fast, you can still add APCDispatcher to boost the
performance, which is to avoid re-lookup route.

This is pretty useful when you have a lot of PCRE routes.

```
use Pux\Dispatcher\APCDispatcher;
$dispatcher = new APCDispatcher($mux, array(
    'namespace' => 'app_',
    'expiry' => ...,
));
$route = $dispatcher->dispatch('/request/uri');
var_dump($route);
```

Persistent Dispatcher
---------------------
Rather than reload the mux object from php file everytime (or load from APC), there still a lot of overhead.

Pux provides a persistent way to dispatch your route and keep the routes array in the persistent memory:

```php
$r = pux_persistent_dispatch('hello', 'hello_mux.php', '/hello');
```

> Please note that the `hello_mux.php` must be a compiled mux PHP file.
> The `pux_persistent_dispatch` is only available in extension.

Controller
--------------------

Pux provides a simple fast controller in C extension, you can mount your controller methods to paths automatically:

```php
class ProductController extends \Pux\Controller
{
    // translate to path ""
    public function indexAction() { }

    // translate to path "/add"
    public function addAction() { }

    // translate to path "/del"
    public function delAction() { }
}

$mux = new Pux\Mux;
$mux->mount( '/product' , $controller->expand() );

$mux->dispatch('/product');       // ProductController->indexAction
$mux->dispatch('/product/add');   // ProductController->addAction
$mux->dispatch('/product/del');   // ProductController->delAction
```

MuxCompiler
--------------------

In your route definition file `hello_routes.php`, you simply return the Mux object at the end of file:

```php
<?php
// load your composer autoload if it's needed
// require '../vendor/autoload.php';
use Pux\Mux;
use Pux\Executor;
$mux = new Mux;
$mux->get('/hello', ['HelloController','helloAction']);
return $mux;
```

Pux provides a command-line tool for you to compile your route definitions.

    pux compile -o hello_mux.php hello_routes.php

In your application, you may load the compiled mux (router) through only one line:

```php
<?php
$mux = require "hello_mux.php";
$route = $mux->dispatch('/hello');
```

This can be very very fast if you have pux extension installed.

Dispatching Strategy
--------------------

There are two route dispatching strategies in Pux while Symfony/Routing only
provides PCRE pattern matching:

1. Plain string comparison.
2. PCRE pattern comparison.

You've already knew that PCRE pattern matching is slower than plain string comparison, although PHP PCRE caches the compiled patterns.

The plain string comparison is designed for static routing paths, it
improves the performance while you have a lot of simple routes.

The PCRE pattern comparison is used when you have some dynamic routing paths,
for example, you can put some place holders in your routing path, and pass
these path arguments to your controller later.

Pux sorts and compiles your routes to single cache file, it also uses longest
matching so it sorts patterns by pattern length in descending order before compiling the
routes to cache.

Pux uses indexed array as the data structure for storing route information so it's faster.

## Benchmarks

Testing with route dispatch only. (no controller)

Hardware:

- iMac Mid 2011
- Processor  2.5 GHz Intel Core i5
- Memory  12 GB 1333 MHz DDR3
- Software  OS X 10.9.1 (13B42)

Environment:

- PHP 5.5.6 + APC

### Dispatch Speed

With one static route:

    n=10000
    Running pux extension (dispatch) - . 97487.768426386/s
    Running symfony/routing (dispatch) - . 2456.3512428418/s

                                    Rate   Mem pux extension (dispatch) symfony/routing (dispatch)
      pux extension (dispatch)  97.49K/s    0B                       --                        -2%
    symfony/routing (dispatch)   2.46K/s  524K                    3968%                         --

    ================================== Bar Chart ==================================

        pux extension (dispatch)  97.49K/s | ████████████████████████████████████████████████████████████  |
      symfony/routing (dispatch)   2.46K/s | █                                                             |

    ============================== System Information ==============================

    PHP Version: 5.5.6
    CPU Brand String: Intel(R) Core(TM) i5-3427U CPU @ 1.80GHz

    With XDebug Extension.

With one pcre route:

    n=5000
    Running pux extension (dispatch) - . 68264.888935184/s
    Running symfony/routing (dispatch) - . 2245.5539220463/s

                                    Rate   Mem pux extension (dispatch) symfony/routing (dispatch)
      pux extension (dispatch)  68.26K/s    3M                       --                        -3%
    symfony/routing (dispatch)   2.25K/s  786K                    3040%                         --

    ================================== Bar Chart ==================================

        pux extension (dispatch)  68.26K/s | ████████████████████████████████████████████████████████████  |
      symfony/routing (dispatch)   2.25K/s | █                                                             |

    ============================== System Information ==============================

    PHP Version: 5.5.6
    CPU Brand String: Intel(R) Core(TM) i5-3427U CPU @ 1.80GHz

Compare to other PHP routers (test code: <https://github.com/c9s/router-benchmark/blob/master/code/dispatch.php> ):

<pre>
n=10000
Runing php array - . 138796.45654569/s
Runing pux - . 124982.98519026/s
Runing klein - . 1801.5070399717/s
Runing ham - . 13566.734991391/s
Runing aura - . 39657.986477172/s
Runing symfony/routing - . 1934.2415677861/s

                     Rate   Mem php array pux aura ham symfony/routing klein
      php array  138.8K/s    0B        ---90% -28% -9%             -1%   -1%
            pux 124.98K/s    0B      111%  -- -31%-10%             -1%   -1%
           aura  39.66K/s    0B      349%315%   ---34%             -4%   -4%
            ham  13.57K/s    0B     1023%921% 292%  --            -14%  -13%
symfony/routing   1.93K/s  786K     7175%6461%2050%701%              --  -93%
          klein    1.8K/s  262K     7704%6937%2201%753%            107%    --

================================== Bar Chart ==================================

        php array  138.8K/s | ████████████████████████████████████████████████████████████  |
              pux 124.98K/s | ██████████████████████████████████████████████████████        |
             aura  39.66K/s | █████████████████                                             |
              ham  13.57K/s | █████                                                         |
  symfony/routing   1.93K/s |                                                               |
            klein    1.8K/s |                                                               |

============================== System Information ==============================

PHP Version: 5.5.6
CPU Brand String: Intel(R) Core(TM) i5-3427U CPU @ 1.80GHz

With XDebug Extension.
</pre>

### Through Apache

Please see benchmark details here: <https://github.com/c9s/router-benchmark>


text:
A reddit bot that responds to movie quotes from comments in [/r/PrequelMemes](https://www.reddit.com/r/PrequelMemes). It uses [**Regular Expressions**](https://en.wikipedia.org/wiki/Regular_expression) to influence the comments to create... Memes.

### Conditions
In [responses.json](responses.json) defines all of the possible comments to look for and defines arrays of possible responses to said comments. The bot will look for a key phrase using a regular expression and will pick a random response upon finding one.

The bot will also keep track of what comments it has sent and will perform additional checks to common replies such as `"Good bot"` or `"Bad bot"`.

### Commands
The bot will respond to the following commands:

- `!dewit`
- `!spin`
- `!youngling`
- `!sand`

*Note: To summon the bot, your comment only needs to contain one of these strings. You do not need to put the bot's username in the comment.*

### Example
Here is an example regular expression:

```
(did you|have you) ever heard? the (.*) of (.*)\?$
```

To satisfy this condition, a comment will look like this:

>Did you ever hear the ... of ...?

*Note: Almost all of the regular expressions end with `$`, this denotes that the comment must **end with** the phrase. It just ensures that the bot is responding in the right context.*

## Contributing
- Check the project issues for any jobs that need help.
- Feel free to fork the project and make a pull request with some nice new features. We can never have too many comment responses.
- Submit an issue if you have an idea for a comment response and are not sure how to implement it or if you have any other issue with the bot.

## Testing
If you are submitting a pull request, please run the tests first (`npm test`) and ensure that they are all successful. If you are adding a major new feature, please write tests as well.

## License
[MIT](LICENSE)


text:
using System.Windows.Input;
using Sketching.Tool;
using Xamarin.Forms;

namespace Sketching.Views
{
	public partial class SketchToolbarItem : ContentView
	{
		public static readonly BindableProperty SelectionColorProperty = BindableProperty.Create(nameof(SelectionColor), typeof(Color), typeof(SketchToolbarItem), Color.Orange);
		public Color SelectionColor
		{
			get { return (Color)GetValue(SelectionColorProperty); }
			set { SetValue(SelectionColorProperty, value); }
		}

		public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create(nameof(IsSelected), typeof(bool), typeof(SketchToolbarItem), false, propertyChanged: IsSelectedPropertyChanged);
		public bool IsSelected
		{
			get { return (bool)GetValue(IsSelectedProperty); }
			set { SetValue(IsSelectedProperty, value); }
		}

		private static void IsSelectedPropertyChanged(BindableObject bindable, object oldValue, object newValue)
		{
			if ((bool)newValue)
			{
				((SketchToolbarItem)bindable).toolLine.BackgroundColor = ((SketchToolbarItem)bindable).SelectionColor;
			}
			else
			{
				((SketchToolbarItem)bindable).toolLine.BackgroundColor = Color.Transparent;
			}
		}

		public ITool Tool { get; set; }

		public SketchToolbarItem(ImageSource imageSource, ITool tool, ICommand tappedCommand)
		{
			InitializeComponent();

			toolImage.Source = imageSource;
			toolImage.GestureRecognizers.Add(new TapGestureRecognizer
			{
				Command = tappedCommand,
				CommandParameter = tool
			});

			Tool = tool;
		}
	}
}


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee180f11250">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court District of Kansas</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2011-11-02</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2011-01-07</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_10-cv-03245</identifier>
<identifier type="local">P0b002ee180f11250</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2011-11-02</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2011-11-02</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ksd-5_10-cv-03245</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-5_10-cv-03245</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>5:10-cv-03245</caseNumber>
 <caseOffice>Topeka</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>555</natureSuitCode>
 <natureSuit>Prisoner - Prison Condition</natureSuit>
 <party firstName="C." fullName="C. Chester" lastName="Chester" role="Defendant"></party>
 <party firstName="Mario" fullName="Mario Jara" lastName="Jara" role="Plaintiff"></party>
 <party firstName="(fnu)" fullName="(fnu) Mason" lastName="Mason" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Defendant"></party>
</extension>
<titleInfo>
 <title>Jara v. United States of America et al</title>
 <partNumber>5:10-cv-03245</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_10-cv-03245/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">5:10-cv-03245;10-3245</identifier>
<name type="corporate">
 <namePart>United States District Court District of Kansas</namePart>
 <namePart>10th Circuit</namePart>
 <namePart>Topeka</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>C. Chester</displayForm>
 <namePart type="family">Chester</namePart>
 <namePart type="given">C.</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>Mario Jara</displayForm>
 <namePart type="family">Jara</namePart>
 <namePart type="given">Mario</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>(fnu) Mason</displayForm>
 <namePart type="family">Mason</namePart>
 <namePart type="given">(fnu)</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>United States of America</displayForm>
 <namePart type="family">United States of America</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-5_10-cv-03245</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>5:10-cv-03245</caseNumber>
 <caseOffice>Topeka</caseOffice>
 <caseType>civil</caseType>
 <natureSuitCode>555</natureSuitCode>
 <natureSuit>Prisoner - Prison Condition</natureSuit>
 <party firstName="C." fullName="C. Chester" lastName="Chester" role="Defendant"></party>
 <party firstName="Mario" fullName="Mario Jara" lastName="Jara" role="Plaintiff"></party>
 <party firstName="(fnu)" fullName="(fnu) Mason" lastName="Mason" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Defendant"></party>
 <state>Kansas</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-5_10-cv-03245-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_10-cv-03245/USCOURTS-ksd-5_10-cv-03245-0/mods.xml">
 <titleInfo>
  <title>Jara v. United States of America et al</title>
  <subTitle>ORDER ENTERED: Plaintiff is granted twenty (20) days in which to submit his complaint upon forms provided by the court, to satisfy the filing fee of $350.00, and to show cause why this action should not be dismissed for failure to state a federal constitutional claim and treated as a strike. Signed by Senior District Judge Sam A. Crow on 1/7/2011. (Mailed to pro se party Mario Jara by regular mail.) (smnd)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2011-01-07</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ksd-5_10-cv-03245-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee180f2a2d2</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_10-cv-03245/USCOURTS-ksd-5_10-cv-03245-0</identifier>
 <identifier type="former granule identifier">ksd-5_10-cv-03245_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-5_10-cv-03245/USCOURTS-ksd-5_10-cv-03245-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-5_10-cv-03245/pdf/USCOURTS-ksd-5_10-cv-03245-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:10-cv-03245; Jara v. United States of America et al; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-5_10-cv-03245-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2011-01-07</dateIssued>
  <docketText>ORDER ENTERED: Plaintiff is granted twenty (20) days in which to submit his complaint upon forms provided by the court, to satisfy the filing fee of $350.00, and to show cause why this action should not be dismissed for failure to state a federal constitutional claim and treated as a strike. Signed by Senior District Judge Sam A. Crow on 1/7/2011. (Mailed to pro se party Mario Jara by regular mail.) (smnd)</docketText>
</extension>
</relatedItem>
</mods>


text:
using namespace std;

namespace cnn {

using namespace expr;

ClassFactoredSoftmaxBuilder::ClassFactoredSoftmaxBuilder(unsigned rep_dim,
                             const std::string& cluster_file,
                             Dict* word_dict,
                             Model* model) {
  ReadClusterFile(cluster_file, word_dict);
  const unsigned num_clusters = cdict.size();
  p_r2c = model->add_parameters({num_clusters, rep_dim});
  p_cbias = model->add_parameters({num_clusters});
  p_rc2ws.resize(num_clusters);
  p_rcwbiases.resize(num_clusters);
  for (unsigned i = 0; i < num_clusters; ++i) {
    auto& words = cidx2words[i];  // vector of word ids
    const unsigned num_words_in_cluster = words.size();
    if (num_words_in_cluster > 1) {
      // for singleton clusters, we don't need these parameters, so
      // we don't create them
      p_rc2ws[i] = model->add_parameters({num_words_in_cluster, rep_dim});
      p_rcwbiases[i] = model->add_parameters({num_words_in_cluster});
    }
  }
}

void ClassFactoredSoftmaxBuilder::new_graph(ComputationGraph& cg) {
  pcg = &cg;
  const unsigned num_clusters = cdict.size();
  r2c = parameter(cg, p_r2c);
  cbias = parameter(cg, p_cbias);
  rc2ws.clear();
  rc2biases.clear();
  rc2ws.resize(num_clusters);
  rc2biases.resize(num_clusters);
}

Expression ClassFactoredSoftmaxBuilder::neg_log_softmax(const Expression& rep, unsigned wordidx) {
  // TODO assert that new_graph has been called
  int clusteridx = widx2cidx[wordidx];
  assert(clusteridx >= 0);  // if this fails, wordid is missing from clusters
  Expression cscores = affine_transform({cbias, r2c, rep});
  Expression cnlp = pickneglogsoftmax(cscores, clusteridx);
  if (singleton_cluster[clusteridx]) return cnlp;
  // if there is only one word in the cluster, just return -log p(class | rep)
  // otherwise predict word too
  unsigned wordrow = widx2cwidx[wordidx];
  Expression& cwbias = get_rc2wbias(clusteridx);
  Expression& r2cw = get_rc2w(clusteridx);
  Expression wscores = affine_transform({cwbias, r2cw, rep});
  Expression wnlp = pickneglogsoftmax(wscores, wordrow);
  return cnlp + wnlp;
}

unsigned ClassFactoredSoftmaxBuilder::sample(const expr::Expression& rep) {
  // TODO assert that new_graph has been called
  Expression cscores = affine_transform({cbias, r2c, rep});
  softmax(cscores);
  auto cdist = as_vector(pcg->incremental_forward());
  unsigned c = 0;
  double p = rand01();
  for (; c < cdist.size(); ++c) {
    p -= cdist[c];
    if (p < 0.0) { break; }
  }
  if (c == cdist.size()) --c;
  unsigned w = 0;
  if (!singleton_cluster[c]) {
    Expression& cwbias = get_rc2wbias(c);
    Expression& r2cw = get_rc2w(c);
    Expression wscores = affine_transform({cwbias, r2cw, rep});
    softmax(wscores);
    auto wdist = as_vector(pcg->incremental_forward());
    p = rand01();
    for (; w < wdist.size(); ++w) {
      p -= wdist[w];
      if (p < 0.0) { break; }
    }
    if (w == wdist.size()) --w;
  }
  return cidx2words[c][w];
}

inline bool is_ws(char x) { return (x == ' ' || x == '\t'); }
inline bool not_ws(char x) { return (x != ' ' && x != '\t'); }

void ClassFactoredSoftmaxBuilder::ReadClusterFile(const std::string& cluster_file, Dict* word_dict) {
  cerr << "Reading clusters from " << cluster_file << " ...\n";
  ifstream in(cluster_file);
  assert(in);
  int wc = 0;
  string line;
  while(getline(in, line)) {
    ++wc;
    const unsigned len = line.size();
    unsigned startc = 0;
    while (is_ws(line[startc]) && startc < len) { ++startc; }
    unsigned endc = startc;
    while (not_ws(line[endc]) && endc < len) { ++endc; }
    unsigned startw = endc;
    while (is_ws(line[startw]) && startw < len) { ++startw; }
    unsigned endw = startw;
    while (not_ws(line[endw]) && endw < len) { ++endw; }
    assert(endc > startc);
    assert(startw > endc);
    assert(endw > startw);
    unsigned c = cdict.Convert(line.substr(startc, endc - startc));
    unsigned word = word_dict->Convert(line.substr(startw, endw - startw));
    if (word >= widx2cidx.size()) {
      widx2cidx.resize(word + 1, -1);
      widx2cwidx.resize(word + 1);
    }
    widx2cidx[word] = c;
    if (c >= cidx2words.size()) cidx2words.resize(c + 1);
    auto& clusterwords = cidx2words[c];
    widx2cwidx[word] = clusterwords.size();
    clusterwords.push_back(word);
  }
  singleton_cluster.resize(cidx2words.size());
  int scs = 0;
  for (unsigned i = 0; i < cidx2words.size(); ++i) {
    bool sc = cidx2words[i].size() <= 1;
    if (sc) scs++;
    singleton_cluster[i] = sc;
  }
  cerr << "Read " << wc << " words in " << cdict.size() << " clusters (" << scs << " singleton clusters)\n";
}

} // namespace cnn


text:
About me project for Code 201

For functions, Maelle was the driver and Britney the navigator.
We didn't get lost, yay.


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <parameters>
        <parameter key="impact_program.example.class">Impact\ProgramBundle\Example</parameter>
    </parameters>

    <services>
        <service id="impact_program.example" class="%impact_program.example.class%">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->
</container>


text:
var EventTarget = function() {
    this._listener = {};
};

EventTarget.prototype = {
    constructor: this,
    addEvent: function(type, fn) {
        if (typeof type === "string" && typeof fn === "function") {
            if (typeof this._listener[type] === "undefined") {
                this._listener[type] = [fn];
            } else {
                this._listener[type].push(fn);
            }
        }
        return this;
    },
    addEvents: function(obj) {
        obj = typeof obj === "object"? obj : {};
        var type;
        for (type in obj) {
            if ( type && typeof obj[type] === "function") {
                this.addEvent(type, obj[type]);
            }
        }
        return this;
    },
    fireEvent: function(type) {
        if (type && this._listener[type]) {
            var events = {
                type: type,
                target: this
            };

            for (var length = this._listener[type].length, start=0; start<length; start+=1) {
                this._listener[type][start].call(this, events);
            }
        }
        return this;
    },
    fireEvents: function(array) {
        if (array instanceof Array) {
            for (var i=0, length = array.length; i<length; i+=1) {
                this.fireEvent(array[i]);
            }
        }
        return this;
    },
    removeEvent: function(type, key) {
        var listeners = this._listener[type];
        if (listeners instanceof Array) {
            if (typeof key === "function") {
                for (var i=0, length=listeners.length; i<length; i+=1){
                    if (listeners[i] === key){
                        listeners.splice(i, 1);
                        break;
                    }
                }
            } else if (key instanceof Array) {
                for (var lis=0, lenkey = key.length; lis<lenkey; lis+=1) {
                    this.removeEvent(type, key[lenkey]);
                }
            } else {
                delete this._listener[type];
            }
        }
        return this;
    },
    removeEvents: function(params) {
        if (params instanceof Array) {
            for (var i=0, length = params.length; i<length; i+=1) {
                this.removeEvent(params[i]);
            }
        } else if (typeof params === "object") {
            for (var type in params) {
                this.removeEvent(type, params[type]);
            }
        }
        return this;
    }
};


text:
package org.openhealthtools.openxds.webapp.control;

import gov.nist.registry.common2.exception.MetadataException;
import gov.nist.registry.common2.exception.MetadataValidationException;
import gov.nist.registry.common2.registry.Metadata;
import gov.nist.registry.common2.registry.MetadataSupport;
import gov.nist.registry.common2.registry.Validator;
import gov.nist.registry.common2.xml.XmlFormatter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;

/**
 * This class creates actual view of all the pages to display.
 * @author Anil Kumar
 */
public class Xdsview {
	private Metadata m;
	private HttpUtils oc;
	HashMap<String, String> symbolic_ids = new HashMap<String, String>(); // uuid -> symbolic

	public Xdsview(Metadata m, HttpUtils oc) {
		this.oc = oc;
		this.m = m;
	}

	public Xdsview(HttpUtils oc)  {
		this.oc = oc;
		this.m = new Metadata();
	}

	public HttpUtils h() { return oc; }

	void out(String s) {
		//System.out.println(s);
		oc.o(s);
	}

	String symbolic(String id, String type) {
		String symbolic = symbolic_ids.get(id);
		if (symbolic == null) {
			int i = 1;
			while (true) {
				String new_symbolic = type + Integer.toString(i);
				if (symbolic_ids.containsValue(new_symbolic)) {
					i++;
					continue;
				}
				symbolic_ids.put(id, new_symbolic);
				return new_symbolic;
			}
		}
		return symbolic;
	}

	String symbolic(String id) {
		String symbolic = symbolic_ids.get(id);
		if (symbolic != null)
			return symbolic;
		try {
			String type = m.type(id);
			if (type != null) {
				if (type.equals("ExtrinsicObject") )
					type = "Doc";
				else if (type.equals("RegistryPackage")) {
					if (m.isSubmissionSet(id))
						type = "SS";
					else if (m.isFolder(id))
						type = "Fol";
				}
				else if (type.equals("Association"))
					type = "Assoc";
				else if (type.equals("ObjectRef"))
					return "Ref";
				return symbolic(id, type);
			}
		} catch (Exception e) {

		}
		return id;
	}

	static String build_link(String href, String text) {
		return "" + text + "";
	}

	static String build_link(String href, String target, String text) {
		return "" + text + "";
	}

	String build_ssac_link(String id) {
		return build_link("/openxds-web/query1.action?verb=ssac&id=" + id,"left", symbolic(id));
	}

	String build_sscontents_link(String id) {
		return build_link("/openxds-web/query1.action?verb=ssac&id=" + id, "left","SSandcontents");
	}

	String build_details_link(String id, String cntl) {
		if (cntl == null)
			return build_link("/openxds-web/innerquery.action?verb=details&id=" + id,"content", symbolic(id));
		else
			return build_link("/openxds-web/innerquery.action?verb=details&id=" + id + "&cntl=" + cntl,"content", symbolic(id));
	}

	String build_related_link(String id) {
		return build_link("/openxds-web/query1.action?verb=related&id=" + id, "left","related");
	}

	String build_display_doc_link(String cntl, String id) {
		return build_link("/openxds-web/query1.action?action=display_doc&cntl=" + cntl + "&id=" + id, "_new", "display");
	}

	String build_ss_link(String id) {
		return build_link("/openxds-web/query1.action?verb=ss&id=" + id,"left", "ss");
	}

	String build_assoc_link(String id, String type, String cntl) {
		if (cntl == null)
			return build_link("/openxds-web/innerquery.action?verb=xml&id=" + id,"content", type);
		else
			return build_link("/openxds-web/innerquery.action?verb=xml&id=" + id + "&cntl=" + cntl,"content", type);
	}

	String build_xml_link(String id, String cntl) {
		if (cntl == null)
			return build_link("/openxds-web/innerquery.action?verb=xml&id=" + id, "content","xml");
		else
			return build_link("/openxds-web/innerquery.action?verb=xml&id=" + id + "&cntl=" + cntl,"content", "xml");
	}

	String build_headers_link(String id, String cntl) {
		if (cntl == null)
			return build_link("/openxds-web/innerquery.action?verb=display_headers&id=" + id, "headers");
		else
			return build_link("/openxds-web/innerquery.action?verb=display_headers&id=" + id + "&cntl=" + cntl, "headers");
	}

	String build_query_results_xml_link(String index) {
		return build_link("/openxds-web/innerquery.action?verb=queryresponsexml&cntl=" + index,"content", "RawResult");
	}

	String build_query_request_xml_link(String index) {
		return build_link("/openxds-web/innerquery.action?verb=queryrequestxml&cntl=" + index,"content", "RawRequest");
	}

	static String build_next_page_link(String index) {
		return build_link("/openxds-web/query1.action?action=nextpage&cntl=" + index,"left", "next");
	}

	public void displayOutline(QueryControl q_cntl, int index)
	throws MetadataException, MetadataValidationException {
		QueryContents qc = q_cntl.getAllQueryContents().get(index);
		qc.displayStructure(q_cntl, index, oc, this, null);
	}

	void scan() {
		OMElement ss = m.getSubmissionSet();
		if (ss != null)
			symbolic(m.getId(ss), "SS");

		for (String id : m.getExtrinsicObjectIds())
			symbolic(id, "Doc");

		for (String id : m.getSubmissionSetIds())
			symbolic(id, "SS");

		for (String id : m.getFolderIds())
			symbolic(id, "Fol");

		for (OMElement ele : m.getAssociations()) {
			String id = m.getId(ele);
			symbolic(id, "Assoc");
		}
	}

	String xml_anchor(String id) {
		return " (" + "XML" + ")";
	}

	String display_anchor(String id) {
		String sym = symbolic(id);
		return "" + sym + "";
	}

	void doc_code_row(String id, String uuid, String label) throws MetadataException {
		List<OMElement> classifications = m.getClassifications(id);
		for (OMElement class_ele : classifications) {
			String class_uuid = class_ele.getAttributeValue(MetadataSupport.classificationscheme_qname);
			if (class_uuid != null && class_uuid.equals(uuid)) {
				row11111(null,
						label,
						class_ele.getAttributeValue(MetadataSupport.noderepresentation_qname),
						m.getNameValue(class_ele),
						m.getSlotValue(class_ele, "codingScheme", 0));
			}
		}
	}

	public void run() throws MetadataException {
		scan();

		start();
		for (OMElement ele: m.getAssociations()) {
			String a_id = m.getId(ele);
			String src_id = m.getSourceObject(ele);
			String tar_id = m.getTargetObject(ele);
			row (display_anchor(src_id),
					strip_namespace(m.getAssocType(ele)) + xml_anchor(a_id),
					display_anchor(tar_id));
		}
		end();

		if (m.getAssociations().size() != 0)
			out("
");

		for (String id : m.getSubmissionSetIds()) {
			displaySS(m, id);
		}

		for (String id: m.getExtrinsicObjectIds()) {
			displayDoc(m, id);
		}

		for (String id: m.getFolderIds()) {
			displayFolder(m, id);
		}

		Validator v = new Validator(m);
		// two element - testname, test status
		List<List> al = v.getPatterns();
		for (List<String> elements : al) {
			row (elements.get(0), elements.get(1), elements.get(2));
		}
	}

	private void displayFolder(Metadata m, String id) throws MetadataException {
		OMElement fol = m.getObjectById(id);
		out("
");
		start();
		row(null, "is", "Folder");
		row(null, "Name", m.getNameValue(id));
		row(null, "Description", m.getDescriptionValue(id));
		row113(null, "status", m.getStatus(fol));
		row113(null, "home", m.getHome(fol));
		row113(null, "patient ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSFolder_patientid_uuid));
		row113(null, "unique ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSFolder_uniqueid_uuid));
		row113(null, "update time", m.getSlotValue(fol, "lastUpdateTime", 0));
		doc_code_row(id, "urn:uuid:1ba97051-7806-41a8-a48b-8fce7af683c5", "codeList");
		end();
	}

	public void displayRegistryObject(String id) throws MetadataException {
		displayRegistryObject(m, id);
	}

	public void displayRegistryObject(Metadata m, String id) throws MetadataException {
		if (m.isDocument(id)) {
			displayDoc(m, id);
		} else if (m.isSubmissionSet(id)) {
			displaySS(m, id);
		} else if (m.isFolder(id)) {
			this.displayFolder(m, id);
		} else {
			System.out.println("id " + id + "  is not a document or submission set");
		}
	}

	public void displayDoc(Metadata m, String id) throws MetadataException {
		OMElement eo = m.getObjectById(id);
		if (eo == null) {
			System.out.println("displayDoc: unknown id " + id);
			return;
		}
		start();
		row(null, "is", "ExtrinsicObject");
		row(null, "id", id);
		row113(null, "name", m.getNameValue(id));
		row113(null, "desc", m.getDescriptionValue(id));
		row113(null, "status", m.getStatus(eo));
		row113(null, "home", m.getHome(eo));
		row113(null, "URI", m.getSlotValue(eo, "URI", 0));
		row113(null, "repositoryUniqueId", m.getSlotValue(eo, "repositoryUniqueId", 0));
		row11111(null, "size/mime_type", m.getSlotValue(eo, "size", 0), eo.getAttributeValue(MetadataSupport.mime_type_qname),"");
		row113(null, "hash", m.getSlotValue(eo, "hash", 0));
		row113(null, "patient ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSDocumentEntry_patientid_uuid));
		row113(null, "unique ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSDocumentEntry_uniqueid_uuid));
		row11111(null, "creation/service time", m.getSlotValue(eo, "creationTime", 0), m.getSlotValue(eo, "serviceStartTime", 0), m.getSlotValue(eo, "serviceStopTime", 0));
		doc_code_row(id, "urn:uuid:41a5887f-8865-4c09-adf7-e362475b143a", "classCode");
		doc_code_row(id, "urn:uuid:f4f85eac-e6cb-4883-b524-f2705394840f", "confCode");
		doc_code_row(id, "urn:uuid:2c6b8cb7-8b2a-4051-b291-b1ae6a575ef4", "eventCode");
		doc_code_row(id, "urn:uuid:a09d5840-386c-46f2-b5ad-9c3699a4309d", "formatCode");
		doc_code_row(id, "urn:uuid:f33fb8ac-18af-42cc-ae0e-ed0b0bdb91e1", "hcftCode");
		doc_code_row(id, "urn:uuid:cccf5598-8b07-4b77-a05e-ae952c785ead", "practiceSettingCode");
		end();
	}

	public void displaySS(Metadata m, String id) throws MetadataException {
		OMElement ss = m.getObjectById(id);
		if (ss == null) {
			System.out.println("displaySS: unknown id " + id);
			return;
		}
		out("
");

		start();
		row(null, "is", "SubmissionSet");
		row(null, "id", id);
		row113(null, "name", m.getNameValue(id));
		row113(null, "desc", m.getDescriptionValue(id));
		row113(null, "status", m.getStatus(ss));
		row113(null, "home", m.getHome(ss));
		row113(null, "patient ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSSubmissionSet_patientid_uuid));
		row113(null, "unique ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSSubmissionSet_uniqueid_uuid));
		row113(null, "source ID", m.getExternalIdentifierValue(id, MetadataSupport.XDSSubmissionSet_sourceid_uuid));
		row113(null, "submisssion time", m.getSlotValue(id, "submissionTime", 0));
		List<String> ctypes = m.getClassificationsValues(id, "urn:uuid:aa543740-bdda-424e-8c96-df4873be8500");
		for (String ctype : ctypes) {
			row113(null, "content type", ctype);
		}
		List<OMElement> authors = m.getClassifications(id, "urn:uuid:a7058bb9-b4e4-4307-ba5b-e3f0ab85e12d");
		for (OMElement author : authors) {
			String author_name = m.getSlotValue(author, "authorPerson", 0);
			row113(null, "author", author_name);
			for (int i=0; i<10; i++) {
				String author_role = m.getSlotValue(author, "authorRole", i);
				if (author_role != null && !author_role.equals(""))
					row1112(null, null, "role", author_role);
			}
			for (int i=0; i<10; i++) {
				String author_role = m.getSlotValue(author, "authorSpecialty", i);
				if (author_role != null && !author_role.equals(""))
					row1112(null, null, "specialty", author_role);
			}
			for (int i=0; i<10; i++) {
				String author_role = m.getSlotValue(author, "authorInstitution", i);
				if (author_role != null && !author_role.equals(""))
					row1112(null, null, "institution", author_role);
			}
		}
		end();
	}

	String strip_namespace(String name) {
		String[] parts = name.split(":");
		if (parts.length == 0) return name;
		return parts[parts.length - 1];
	}

	void displayXml(String id) throws MetadataException {
		displayXml(m, id);
	}

	void displayXml(Metadata m, String id) throws MetadataException {
		OMElement ele = m.getObjectById(id);
		if (ele == null) throw new MetadataException("displayXml(): id " + id + " is not a known object");
		out(XmlFormatter.htmlize(ele.toString(), false));
	}

	void xml() throws MetadataException {

		for (String ss_id : m.getSubmissionSetIds()) {
			OMElement ss = m.getObjectById(ss_id);
			out("
" + symbolic(ss_id) + "
");
			out("
");
			out(XmlFormatter.htmlize(ss.toString(), false));
			out("
");
		}

		for (String id: m.getExtrinsicObjectIds()) {
			OMElement eo = m.getObjectById(id);
			out("
" + symbolic(id) + "
");
			out("
");
			out(XmlFormatter.htmlize(eo.toString(), false));
			out("
");
		}

		for (String id: m.getFolderIds()) {
			OMElement eo = m.getObjectById(id);
			out("
" + symbolic(id) + "
");
			out("
");
			out(XmlFormatter.htmlize(eo.toString(), false));
			out("
");
		}

		for (OMElement ele: m.getAssociations()) {
			String id = ele.getAttributeValue(new QName("id"));
			out("
" + symbolic(id) + "
");
			out("
");
			out(XmlFormatter.htmlize(ele.toString(), false));
			out("
");
		}

	}

	public void header() {
		System.out.println(
				"\n" +
				"\n" +
				"\n"
		);
	}

	public void footer() {
		System.out.println(
				"\n" +
				"\n"
		);
	}

	public void start() {
		out("
");
	}

	public void end() {
		out("
");
	}

	public void row(String l, String m, String r) {
		if (l == null) l = "";
		if (m == null) m = "";
		if (r == null) r = "";
		out("
");
		out("" + l + "	");
		out("" + m + "	");
		out("" + r + "	");
		out("
");
	}

	public void row122(String l, String m, String r) {
		if (l == null) l = "";
		if (m == null) m = "";
		if (r == null) r = "";
		out("
");
		out("" + l + "	");
		out("" + m + "	");
		out("" + r + "	");
		out("
");
	}

	public void row1112(String l, String m, String mm, String r) {
		if (l == null) l = "";
		if (m == null) m = "";
		if (mm == null) mm = "";
		if (r == null) r = "";
		out("
");
		out("" + l + "	");
		out("" + m + "	");
		out("" + mm + "	");
		out("" + r + "	");
		out("
");
	}

	public void row11111(String l, String m, String mm, String r, String rr) {
		if (l == null) l = "";
		if (m == null) m = "";
		if (mm == null) mm = "";
		if (r == null) r = "";
		if (rr == null) rr = "";
		out("
");
		out("" + l + "	");
		out("" + m + "	");
		out("" + mm + "	");
		out("" + r + "	");
		out("" + rr + "	");
		out("
");
	}

	public void row113(String l, String m, String r) {
		if (l == null) l = "";
		if (m == null) m = "";
		if (r == null) r = "";
		out("
");
		out("" + l + "	");
		out("" + m + "	");
		out("" + r + "	");
		out("
");
	}

	public void row(String only) {
		out( "
" + only + "
");
	}

	public Metadata getMetadata() { return m; }

	public HttpUtils getOc() {
		return oc;
	}

	public void setOc(HttpUtils oc) {
		this.oc = oc;
	}

//	static public void main(String[] args) {
//	if (args.length == 0) {
//	System.err.println("filename arg required");
//	System.exit(-1);
//	}
//	Xdsview xv = new Xdsview(new File(args[0]));
//	xv.header();
//	xv.start();
//	try {
//	xv.run();
//	}
//	catch (Exception e) {
//	System.err.println(e.getMessage());
//	}
//	xv.end();
//	try {
//	xv.xml();
//	}
//	catch (Exception e) {
//	System.err.println(e.getMessage());
//	}
//	xv.footer();
//	}

}


text:
if node['kernel']['release'] and node['kernel']['release'].include?("xen")
  default['drbd']['packages'] = ["kmod-drbd83", "drbd83", "kmod-drbd83-xen"]
else
  default['drbd']['packages'] = ["kmod-drbd83", "drbd83"]
end

node['drbd']['packages'].each do |pkg|
  default['drbd'][pkg]['version'] = nil
end

default['drbd']['remote_host'] = nil
default['drbd']['disk']['start'] = "/dev/"
default_unless['drbd']['fs_type'] = "ext3"
default['drbd']['dev'] = "/dev/drbd0"
default['drbd']['master'] = false
default['drbd']['port'] = 7789
default['drbd']['syncrate'] = "36M"
default['drbd']['resource'] = "data"
default['drbd']['disk']['location'] = "/dev/local/#{node['drbd']['resource']}"
default['drbd']['wait_til_synced'] = true

default['drbd']['config_file'] = "/etc/drbd.conf"

default['drbd']['stop_file'] = "/etc/drbd_stop_file"
default['drbd']['synced']['stop_file'] = "/etc/drbd_synced_stop_file"
default['drbd']['initialized']['stop_file'] = "/etc/drbd_initialized_stop_file"

default['drbd']['primary']['fqdn'] = nil
default['drbd']['server']['hostname'] = nil
default['drbd']['server']['ipaddress'] = nil
default['drbd']['partner']['hostname'] = nil
default['drbd']['partner']['ipaddress'] = nil

default['drbd']['command_timeout'] = 36000

default['drbd']['protocol'] = 'C'
default['drbd']['disk']['on_io_error_action'] = 'detach'
default['drbd']['disk']['disk-flushes'] = false
default['drbd']['disk']['md-flushes'] = false
default['drbd']['disk']['no-disk-barrier'] = false

default['drbd']['net']['enabled'] = false
default['drbd']['net']['sndbuf-size'] = '1M'
default['drbd']['net']['max-buffers'] = 8000
default['drbd']['net']['max-epoch-size'] = 8000

default['iptables']['enabled'] = true


text:
"""Cement core extensions module."""

import sys
from ..core import exc, interface, handler
from ..utils.misc import minimal_logger

LOG = minimal_logger(__name__)

def extension_validator(klass, obj):
    """
    Validates an handler implementation against the IExtension interface.

    """
    members = [
        '_setup',
        'load_extension',
        'load_extensions',
        'get_loaded_extensions',
    ]
    interface.validate(IExtension, obj, members)

class IExtension(interface.Interface):

    """
    This class defines the Extension Handler Interface.  Classes that
    implement this handler must provide the methods and attributes defined
    below.

    Implementations do *not* subclass from interfaces.

    Usage:

    .. code-block:: python

        from cement.core import extension

        class MyExtensionHandler(object):
            class Meta:
                interface = extension.IExtension
                label = 'my_extension_handler'
            ...

    """

    # pylint: disable=W0232, C0111, R0903
    class IMeta:

        """Interface meta-data."""

        label = 'extension'
        """The string identifier of the interface."""

        validator = extension_validator
        """The interface validator function."""

    # Must be provided by the implementation
    Meta = interface.Attribute('Handler Meta-data class')

    def _setup(app_obj):
        """
        The _setup function is called during application initialization and
        must 'setup' the handler object making it ready for the framework
        or the application to make further calls to it.

        :param app_obj: The application object.
        :returns: None

        """

    def load_extension(self, ext_module):
        """
        Load an extension whose module is 'ext_module'.  For example,
        'cement.ext.ext_configobj'.

        :param ext_module: The name of the extension to load.
        :type ext_module: ``str``

        """

    def load_extensions(self, ext_list):
        """
        Load all extensions from ext_list.

        :param ext_list: A list of extension modules to load.  For example:
            ``['cement.ext.ext_configobj', 'cement.ext.ext_logging']``

        :type ext_list: ``list``

        """

class CementExtensionHandler(handler.CementBaseHandler):

    class Meta:

        """
        Handler meta-data (can be passed as keyword arguments to the parent
        class).
        """

        interface = IExtension
        """The interface that this class implements."""

        label = 'cement'
        """The string identifier of the handler."""

    def __init__(self, **kw):
        """
        This is an implementation of the IExtentionHandler interface.  It
        handles loading framework extensions.

        """
        super(CementExtensionHandler, self).__init__(**kw)
        self.app = None
        self._loaded_extensions = []

    def get_loaded_extensions(self):
        """Returns list of loaded extensions."""
        return self._loaded_extensions

    def load_extension(self, ext_module):
        """
        Given an extension module name, load or in other-words 'import' the
        extension.

        :param ext_module: The extension module name.  For example:
            'cement.ext.ext_logging'.
        :type ext_module: ``str``
        :raises: cement.core.exc.FrameworkError

        """
        # If its not a full module path then preppend our default path
        if ext_module.find('.') == -1:
            ext_module = 'cement.ext.ext_%s' % ext_module

        if ext_module in self._loaded_extensions:
            LOG.debug("framework extension '%s' already loaded" % ext_module)
            return

        LOG.debug("loading the '%s' framework extension" % ext_module)
        try:
            if ext_module not in sys.modules:
                __import__(ext_module, globals(), locals(), [], 0)

            if hasattr(sys.modules[ext_module], 'load'):
                sys.modules[ext_module].load(self.app)

            if ext_module not in self._loaded_extensions:
                self._loaded_extensions.append(ext_module)

        except ImportError as e:
            raise exc.FrameworkError(e.args[0])

    def load_extensions(self, ext_list):
        """
        Given a list of extension modules, iterate over the list and pass
        individually to self.load_extension().

        :param ext_list: A list of extension modules.
        :type ext_list: ``list``

        """
        for ext in ext_list:
            self.load_extension(ext)


text:
<?php

namespace Webiny\Component\EventManager;

use Webiny\Component\StdLib\SingletonTrait;
use Webiny\Component\StdLib\StdLibTrait;

/**
 * EventProcessor is a class that takes EventListeners and Event object and processes the event.
 * @package         Webiny\Component\EventManager
 */
class EventProcessor
{
    use StdLibTrait, SingletonTrait;

    /**
     * Process given event
     *
     * @param array|ArrayObject $eventListeners EventListeners that are subscribed to this event
     * @param Event             $event Event data object
     *
     * @param null|string       $resultType Type of event result to enforce (can be any class or interface name)
     * @param null|int          $limit Number of results to return
     *
     * @return array
     */
    public function process($eventListeners, Event $event, $resultType = null, $limit = null)
    {

        $eventListeners = $this->orderByPriority($eventListeners);

        $results = [];

        /* @var $eventListener EventListener */
        foreach ($eventListeners as $eventListener) {

            $handler = $eventListener->getHandler();
            if ($this->isNull($handler)) {
                continue;
            }

            $method = $eventListener->getMethod();

            if ($this->isCallable($handler)) {
                /** @var $handler \Closure */
                $result = $handler($event);
            } else {
                $result = call_user_func_array([
                    $handler,
                    $method
                ], [$event]);
            }

            if ($this->isNull($resultType) || (!$this->isNull($resultType) && $this->isInstanceOf($result, $resultType))) {
                $results[] = $result;

                if ($limit === 1 && count($results) === 1) {
                    return $results[0];
                }

                if (count($results) === $limit) {
                    return $results;
                }
            }

            if ($event->isPropagationStopped()) {
                break;
            }
        }

        return $results;
    }

    /**
     * @param $eventListeners
     *
     * @return mixed
     */
    private function orderByPriority($eventListeners)
    {
        /**
         * @param int $a
         * @param int $b
         *
         * @return int
         */
        $comparisonFunction = function ($a, $b) {
            if ($a->getPriority() == $b->getPriority()) {
                // This will keep the order of same priority listeners in the order of subscribing
                return 1;
            }

            return ($a->getPriority() > $b->getPriority()) ? -1 : 1;
        };

        return $this->arr($eventListeners)->sortUsingFunction($comparisonFunction)->val();
    }
}


text:
function [post, a] = gmmpost(mix, x)
%GMMPOST Computes the class posterior probabilities of a Gaussian mixture model.
%
%	Description
%	This function computes the posteriors POST (i.e. the probability of
%	each component conditioned on the data P(J|X)) for a Gaussian mixture
%	model.   The data structure MIX defines the mixture model, while the
%	matrix X contains the data vectors.  Each row of X represents a
%	single vector.
%
%	See also
%	GMM, GMMACTIV, GMMPROB
%

%	Copyright (c) Ian T Nabney (1996-2001)

% Check that inputs are consistent
errstring = consist(mix, 'gmm', x);
if ~isempty(errstring)
  error(errstring);
end

ndata = size(x, 1);

a = gmmactiv(mix, x);

post = (ones(ndata, 1)*mix.priors).*a;
s = sum(post, 2);
if any(s==0)
   warning('Some zero posterior probabilities')
   % Set any zeros to one before dividing
   zero_rows = find(s==0);
   s = s + (s==0);
   post(zero_rows, :) = 1/mix.ncentres;
end
post = post./(s*ones(1, mix.ncentres));

end


text:
#pragma once
#include "kernel/expr.h"

namespace lean {
/**
    \brief Create a choice expression for the given expressions.
    The elaborator decides which one should be used based on the type of the arguments.

    \remark if num_fs == 1, then return fs[0]

    \pre num_fs >= 1
*/
expr mk_choice(unsigned num_es, expr const * es);
/** \brief Return true iff \c e is an expression created using \c mk_choice. */
bool is_choice(expr const & e);
/**
   \brief Return the number of alternatives in a choice expression.
   We have that <tt>get_num_choices(mk_choice(n, es)) == n</tt> whenever <tt>n >= 2</tt>.

   \pre is_choice(e)
*/
unsigned get_num_choices(expr const & e);
/**
   \brief Return the (i+1)-th alternative of a choice expression.

   \pre is_choice(e)
   \pre i < get_num_choices(e)
*/
expr const & get_choice(expr const & e, unsigned i);

/**
   \brief Collect "choices" occurring in \c e.
   For example, if \c e contains [choice (f a) (g a)] where f and g are constants,
   the result contains the list [f, g]. This function is only used for producing nicer
   error messages.
*/
list<list<name>> collect_choice_symbols(expr const & e);
/** \brief Format the result produced by collect_choice_symbols. */
format pp_choice_symbols(expr const & e);

void initialize_choice();
void finalize_choice();
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Model extends Api_Model {

	public function __construct()
	{
		parent::__construct();
	}

	public function admin_login($params='')
	{
		$response = $this->post(BASE_API_URL.'account/account/admin_login' , $params);
		return $response;

	}

}

/* End of file Admin_model.php */
/* Location: ./application/models/Admin_model.php */
?>


text:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
  private static long test(List<Predicate<String>> predicates, List<String> strings) {
      long count = 0;
      for (Predicate<String> pred : predicates) {
          if (pred != null) {
              for (String string : strings) {
                  if (pred.test(string)) {
                      count++;
                  }
              }
          }
      }
      return count;
  }

  public static void main(String[] args) {
    System.out.println(test(
      Arrays.asList(String::isEmpty, s -> s.length() > 3),
      Arrays.asList("", "a", "abcd", "xyz")
    ));
  }
}


text:
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

def index(request):
    return render(request, 'squares/index.html')


text:
"""v3/mail/send response body builder"""
from .personalization import Personalization
from .header import Header

class Mail(object):
    """Creates the response body for v3/mail/send"""
    def __init__(
            self, from_email=None, subject=None, to_email=None, content=None):
        self.from_email = None
        self.subject = None
        self.template_id = None
        self.send_at = None
        self.batch_id = None
        self.asm = None
        self.ip_pool_name = None
        self.mail_settings = None
        self.tracking_settings = None
        self.reply_to = None
        self._personalizations = None
        self._contents = None
        self._attachments = None
        self._sections = None
        self._headers = None
        self._categories = None
        self._custom_args = None

        # Minimum required to send an email
        if from_email and subject and to_email and content:
            self.from_email = from_email
            self.subject = subject
            personalization = Personalization()
            personalization.add_to(to_email)
            self.add_personalization(personalization)
            self.add_content(content)

    def __str__(self):
        return str(self.get())

    def get(self):
        """
        :return: response body dict
        """
        mail = {
            'from': self._get_or_none(self.from_email),
            'subject': self.subject,
            'personalizations': [p.get() for p in self.personalizations or []],
            'content': [c.get() for c in self.contents or []],
            'attachments': [a.get() for a in self.attachments or []],
            'template_id': self.template_id,
            'sections': self._flatten_dictionaries(self.sections),
            'headers': self._flatten_dictionaries(self.headers),
            'categories': [c.get() for c in self.categories or []],
            'custom_args': self._flatten_dictionaries(self.custom_args),
            'send_at': self.send_at,
            'batch_id': self.batch_id,
            'asm': self._get_or_none(self.asm),
            'ip_pool_name': self.ip_pool_name,
            'mail_settings': self._get_or_none(self.mail_settings),
            'tracking_settings': self._get_or_none(self.tracking_settings),
            'reply_to': self._get_or_none(self.reply_to),
        }

        return dict((key, value) for key, value in mail.items()
                    if value is not None and value != [] and value != {})

    def _get_or_none(self, from_obj):
        return from_obj.get() if from_obj is not None else None

    def _flatten_dictionaries(self, dicts):
        list_of_dicts = [d.get() for d in dicts or []]
        return dict((k, v) for d in list_of_dicts for k, v in d.items())

    @property
    def personalizations(self):
        return self._personalizations

    def add_personalization(self, personalizations):
        self._personalizations = self._ensure_append(
            personalizations, self._personalizations)

    @property
    def contents(self):
        return self._contents

    def add_content(self, content):
        self._contents = self._ensure_append(content, self._contents)

    @property
    def attachments(self):
        return self._attachments

    def add_attachment(self, attachment):
        self._attachments = self._ensure_append(attachment, self._attachments)

    @property
    def sections(self):
        return self._sections

    def add_section(self, section):
        self._sections = self._ensure_append(section, self._sections)

    @property
    def headers(self):
        return self._headers

    def add_header(self, header):
        if isinstance(header, dict):
            (k, v) = list(header.items())[0]
            self._headers = self._ensure_append(Header(k, v), self._headers)
        else:
            self._headers = self._ensure_append(header, self._headers)

    @property
    def categories(self):
        return self._categories

    def add_category(self, category):
        self._categories = self._ensure_append(category, self._categories)

    @property
    def custom_args(self):
        return self._custom_args

    def add_custom_arg(self, custom_arg):
        self._custom_args = self._ensure_append(custom_arg, self._custom_args)

    def _ensure_append(self, new_items, append_to):
        append_to = append_to or []
        append_to.append(new_items)
        return append_to


text:
font-family: url(@@FONT@@);
font: bold 35px;
color: white;


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_item_selector">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="12dp">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="12dp"
            android:layout_marginTop="12dp"
            android:background="@drawable/round_icon_path"
            android:padding="@dimen/project_icon_edge_width"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_default_image" />

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/icon"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@id/icon"
            android:lines="1"
            android:text="Medium Text"
            android:textColor="@color/font_1"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/comment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/icon"
            android:layout_alignLeft="@+id/name"
            android:layout_marginBottom="5dp"
            android:lines="1"
            android:text="cc"
            android:textColor="@color/font_3"
            android:textSize="15sp" />

    </RelativeLayout>
</FrameLayout>


text:
package org.elasticsearch.xpack.security.authc.pki;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.ValidationException;
import org.elasticsearch.client.security.AuthenticateResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.RefreshPolicy;
import org.elasticsearch.client.security.AuthenticateResponse.RealmInfo;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.support.expressiondsl.fields.FieldRoleMapperExpression;
import org.elasticsearch.client.security.DelegatePkiAuthenticationRequest;
import org.elasticsearch.client.security.DelegatePkiAuthenticationResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.InvalidateTokenResponse;
import org.elasticsearch.client.security.user.User;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.SecurityIntegTestCase;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.security.action.realm.ClearRealmCacheRequestBuilder;
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
import org.junit.Before;
import org.elasticsearch.test.SecuritySettingsSource;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Arrays;

import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.emptyCollectionOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.startsWith;

public class PkiAuthDelegationIntegTests extends SecurityIntegTestCase {

    @Override
    public Settings nodeSettings(int nodeOrdinal) {
        return Settings.builder()
                .put(super.nodeSettings(nodeOrdinal))
                .put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true)
                // pki1 does not allow delegation
                .put("xpack.security.authc.realms.pki.pki1.order", "1")
                .putList("xpack.security.authc.realms.pki.pki1.certificate_authorities",
                    getDataPath("/org/elasticsearch/xpack/security/action/pki_delegation/testRootCA.crt").toString())
                .put("xpack.security.authc.realms.pki.pki1.files.role_mapping", getDataPath("role_mapping.yml"))
                // pki2 allows delegation but has a non-matching username pattern
                .put("xpack.security.authc.realms.pki.pki2.order", "2")
                .putList("xpack.security.authc.realms.pki.pki2.certificate_authorities",
                    getDataPath("/org/elasticsearch/xpack/security/action/pki_delegation/testRootCA.crt").toString())
                .put("xpack.security.authc.realms.pki.pki2.username_pattern", "CN=MISMATCH(.*?)(?:,|$)")
                .put("xpack.security.authc.realms.pki.pki2.delegation.enabled", true)
                .put("xpack.security.authc.realms.pki.pki2.files.role_mapping", getDataPath("role_mapping.yml"))
                // pki3 allows delegation and the username pattern (default) matches
                .put("xpack.security.authc.realms.pki.pki3.order", "3")
                .putList("xpack.security.authc.realms.pki.pki3.certificate_authorities",
                    getDataPath("/org/elasticsearch/xpack/security/action/pki_delegation/testRootCA.crt").toString())
                .put("xpack.security.authc.realms.pki.pki3.delegation.enabled", true)
                .put("xpack.security.authc.realms.pki.pki3.files.role_mapping", getDataPath("role_mapping.yml"))
                .build();
    }

    @Override
    protected String configUsers() {
        final String usersPasswdHashed = new String(Hasher.resolve(
            randomFrom("pbkdf2", "pbkdf2_1000", "bcrypt", "bcrypt9")).hash(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING));
        return super.configUsers() +
            "user_manage:" + usersPasswdHashed + "\n" +
            "user_manage_security:" + usersPasswdHashed + "\n" +
            "user_delegate_pki:" + usersPasswdHashed + "\n" +
            "user_all:" + usersPasswdHashed + "\n" +
            "kibana_system:" + usersPasswdHashed + "\n";
    }

    @Override
    protected String configRoles() {
        return super.configRoles() + "\n" +
                "role_manage:\n" +
                "  cluster: [ manage ]\n" +
                "\n" +
                "role_manage_security:\n" +
                "  cluster: [ manage_security ]\n" +
                "\n" +
                "role_delegate_pki:\n" +
                "  cluster: [ delegate_pki ]\n" +
                "\n" +
                "role_all:\n" +
                "  cluster: [ all ]\n";
    }

    @Override
    protected String configUsersRoles() {
        return super.configUsersRoles() + "\n" +
                "role_manage:user_manage\n" +
                "role_manage_security:user_manage_security\n" +
                "role_delegate_pki:user_delegate_pki\n" +
                "role_all:user_all\n" +
                "kibana_system:kibana_system\n";
    }

    @Override
    protected boolean transportSSLEnabled() {
        return true;
    }

    @Override
    protected boolean addMockHttpTransport() {
        return false; // enable http
    }

    @Before
    void clearRealmCache() {
        new ClearRealmCacheRequestBuilder(client()).get();
    }

    public void testDelegateThenAuthenticate() throws Exception {
        final X509Certificate clientCertificate = readCertForPkiDelegation("testClient.crt");
        final X509Certificate intermediateCA = readCertForPkiDelegation("testIntermediateCA.crt");
        final X509Certificate rootCA = readCertForPkiDelegation("testRootCA.crt");
        DelegatePkiAuthenticationRequest delegatePkiRequest;
        // trust root is optional
        if (randomBoolean()) {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA));
        } else {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA, rootCA));
        }

        try (RestHighLevelClient restClient = new TestRestHighLevelClient()) {
            for (String delegateeUsername : Arrays.asList("user_all", "user_delegate_pki", "kibana_system")) {
                // delegate
                RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
                optionsBuilder.addHeader("Authorization",
                        basicAuthHeaderValue(delegateeUsername, SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING));
                DelegatePkiAuthenticationResponse delegatePkiResponse = restClient.security().delegatePkiAuthentication(delegatePkiRequest,
                        optionsBuilder.build());
                String token = delegatePkiResponse.getAccessToken();
                assertThat(token, is(notNullValue()));
                // authenticate
                optionsBuilder = RequestOptions.DEFAULT.toBuilder();
                optionsBuilder.addHeader("Authorization", "Bearer " + token);
                AuthenticateResponse resp = restClient.security().authenticate(optionsBuilder.build());
                User user = resp.getUser();
                assertThat(user, is(notNullValue()));
                assertThat(user.getUsername(), is("Elasticsearch Test Client"));
                RealmInfo authnRealm = resp.getAuthenticationRealm();
                assertThat(authnRealm, is(notNullValue()));
                assertThat(authnRealm.getName(), is("pki3"));
                assertThat(authnRealm.getType(), is("pki"));
            }
        }
    }

    public void testTokenInvalidate() throws Exception {
        final X509Certificate clientCertificate = readCertForPkiDelegation("testClient.crt");
        final X509Certificate intermediateCA = readCertForPkiDelegation("testIntermediateCA.crt");
        final X509Certificate rootCA = readCertForPkiDelegation("testRootCA.crt");
        DelegatePkiAuthenticationRequest delegatePkiRequest;
        // trust root is optional
        if (randomBoolean()) {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA));
        } else {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA, rootCA));
        }

        try (RestHighLevelClient restClient = new TestRestHighLevelClient()) {
            String delegateeUsername = randomFrom("user_all", "user_delegate_pki", "kibana_system");
            // delegate
            RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
            optionsBuilder.addHeader("Authorization",
                    basicAuthHeaderValue(delegateeUsername, SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING));
            DelegatePkiAuthenticationResponse delegatePkiResponse = restClient.security().delegatePkiAuthentication(delegatePkiRequest,
                    optionsBuilder.build());
            String token = delegatePkiResponse.getAccessToken();
            assertThat(token, is(notNullValue()));
            // authenticate
            optionsBuilder = RequestOptions.DEFAULT.toBuilder();
            optionsBuilder.addHeader("Authorization", "Bearer " + token);
            AuthenticateResponse resp = restClient.security().authenticate(optionsBuilder.build());
            User user = resp.getUser();
            assertThat(user, is(notNullValue()));
            assertThat(user.getUsername(), is("Elasticsearch Test Client"));
            assertThat(user.getMetadata().get("pki_dn"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_dn"), is("O=org, OU=Elasticsearch, CN=Elasticsearch Test Client"));
            assertThat(user.getMetadata().get("pki_delegated_by_user"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_delegated_by_user"), is(delegateeUsername));
            assertThat(user.getMetadata().get("pki_delegated_by_realm"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_delegated_by_realm"), is("file"));
            // no roles because no role mappings
            assertThat(user.getRoles(), is(emptyCollectionOf(String.class)));
            RealmInfo authnRealm = resp.getAuthenticationRealm();
            assertThat(authnRealm, is(notNullValue()));
            assertThat(authnRealm.getName(), is("pki3"));
            assertThat(authnRealm.getType(), is("pki"));
            // invalidate
            InvalidateTokenRequest invalidateRequest = new InvalidateTokenRequest(token, null, null, null);
            optionsBuilder = RequestOptions.DEFAULT.toBuilder();
            optionsBuilder.addHeader("Authorization",
                    basicAuthHeaderValue(delegateeUsername, SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING));
            InvalidateTokenResponse invalidateResponse = restClient.security().invalidateToken(invalidateRequest, optionsBuilder.build());
            assertThat(invalidateResponse.getInvalidatedTokens(), is(1));
            assertThat(invalidateResponse.getErrorsCount(), is(0));
            // failed authenticate
            ElasticsearchStatusException e1 = expectThrows(ElasticsearchStatusException.class, () -> restClient.security()
                    .authenticate(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", "Bearer " + token).build()));
            assertThat(e1.getMessage(), is("Elasticsearch exception [type=security_exception, reason=token expired]"));
        }
    }

    public void testDelegateUnauthorized() throws Exception {
        final X509Certificate clientCertificate = readCertForPkiDelegation("testClient.crt");
        final X509Certificate intermediateCA = readCertForPkiDelegation("testIntermediateCA.crt");
        final X509Certificate rootCA = readCertForPkiDelegation("testRootCA.crt");
        DelegatePkiAuthenticationRequest delegatePkiRequest;
        // trust root is optional
        if (randomBoolean()) {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA));
        } else {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA, rootCA));
        }
        try (RestHighLevelClient restClient = new TestRestHighLevelClient()) {
            for (String delegateeUsername : Arrays.asList("user_manage", "user_manage_security")) {
                RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
                optionsBuilder.addHeader("Authorization",
                        basicAuthHeaderValue(delegateeUsername, SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING));
                ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> {
                    restClient.security().delegatePkiAuthentication(delegatePkiRequest, optionsBuilder.build());
                });
                assertThat(e.getMessage(), startsWith("Elasticsearch exception [type=security_exception, reason=action"
                        + " [cluster:admin/xpack/security/delegate_pki] is unauthorized for user"));
            }
        }
    }

    public void testDelegatePkiWithRoleMapping() throws Exception {
        X509Certificate clientCertificate = readCertForPkiDelegation("testClient.crt");
        X509Certificate intermediateCA = readCertForPkiDelegation("testIntermediateCA.crt");
        X509Certificate rootCA = readCertForPkiDelegation("testRootCA.crt");
        DelegatePkiAuthenticationRequest delegatePkiRequest;
        // trust root is optional
        if (randomBoolean()) {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA));
        } else {
            delegatePkiRequest = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate, intermediateCA, rootCA));
        }
        final RequestOptions testUserOptions = RequestOptions.DEFAULT.toBuilder()
                .addHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
                        new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())))
                .build();
        try (RestHighLevelClient restClient = new TestRestHighLevelClient()) {
            // put role mappings for delegated PKI
            PutRoleMappingRequest request = new PutRoleMappingRequest("role_by_delegated_user", true,
                    Collections.singletonList("role_by_delegated_user"), Collections.emptyList(),
                    new FieldRoleMapperExpression("metadata.pki_delegated_by_user", "test_user"), null, RefreshPolicy.IMMEDIATE);
            restClient.security().putRoleMapping(request, testUserOptions);
            request = new PutRoleMappingRequest("role_by_delegated_realm", true, Collections.singletonList("role_by_delegated_realm"),
                    Collections.emptyList(), new FieldRoleMapperExpression("metadata.pki_delegated_by_realm", "file"), null,
                    RefreshPolicy.IMMEDIATE);
            restClient.security().putRoleMapping(request, testUserOptions);
            // delegate
            DelegatePkiAuthenticationResponse delegatePkiResponse = restClient.security().delegatePkiAuthentication(delegatePkiRequest,
                    testUserOptions);
            // authenticate
            AuthenticateResponse resp = restClient.security().authenticate(RequestOptions.DEFAULT.toBuilder()
                    .addHeader("Authorization", "Bearer " + delegatePkiResponse.getAccessToken()).build());
            User user = resp.getUser();
            assertThat(user, is(notNullValue()));
            assertThat(user.getUsername(), is("Elasticsearch Test Client"));
            assertThat(user.getMetadata().get("pki_dn"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_dn"), is("O=org, OU=Elasticsearch, CN=Elasticsearch Test Client"));
            assertThat(user.getMetadata().get("pki_delegated_by_user"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_delegated_by_user"), is("test_user"));
            assertThat(user.getMetadata().get("pki_delegated_by_realm"), is(notNullValue()));
            assertThat(user.getMetadata().get("pki_delegated_by_realm"), is("file"));
            // assert roles
            assertThat(user.getRoles(), containsInAnyOrder("role_by_delegated_user", "role_by_delegated_realm"));
            RealmInfo authnRealm = resp.getAuthenticationRealm();
            assertThat(authnRealm, is(notNullValue()));
            assertThat(authnRealm.getName(), is("pki3"));
            assertThat(authnRealm.getType(), is("pki"));
            // delete role mappings for delegated PKI
            restClient.security().deleteRoleMapping(new DeleteRoleMappingRequest("role_by_delegated_user", RefreshPolicy.IMMEDIATE),
                  testUserOptions);
            restClient.security().deleteRoleMapping(new DeleteRoleMappingRequest("role_by_delegated_realm", RefreshPolicy.IMMEDIATE),
                  testUserOptions);
        }
    }

    public void testIncorrectCertChain() throws Exception {
        X509Certificate clientCertificate = readCertForPkiDelegation("testClient.crt");
        X509Certificate intermediateCA = readCertForPkiDelegation("testIntermediateCA.crt");
        X509Certificate bogusCertificate = readCertForPkiDelegation("bogus.crt");
        RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
        optionsBuilder.addHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
                new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
        try (RestHighLevelClient restClient = new TestRestHighLevelClient()) {
            // incomplete cert chain
            DelegatePkiAuthenticationRequest delegatePkiRequest1 = new DelegatePkiAuthenticationRequest(Arrays.asList(clientCertificate));
            ElasticsearchStatusException e1 = expectThrows(ElasticsearchStatusException.class,
                    () -> restClient.security().delegatePkiAuthentication(delegatePkiRequest1, optionsBuilder.build()));
            assertThat(e1.getMessage(), is("Elasticsearch exception [type=security_exception, reason=unable to authenticate user"
                    + " [O=org, OU=Elasticsearch, CN=Elasticsearch Test Client] for action [cluster:admin/xpack/security/delegate_pki]]"));
            // swapped order
            DelegatePkiAuthenticationRequest delegatePkiRequest2 = new DelegatePkiAuthenticationRequest(
                    Arrays.asList(intermediateCA, clientCertificate));
            ValidationException e2 = expectThrows(ValidationException.class,
                    () -> restClient.security().delegatePkiAuthentication(delegatePkiRequest2, optionsBuilder.build()));
            assertThat(e2.getMessage(), is("Validation Failed: 1: certificates chain must be an ordered chain;"));
            // bogus certificate
            DelegatePkiAuthenticationRequest delegatePkiRequest3 = new DelegatePkiAuthenticationRequest(Arrays.asList(bogusCertificate));
            ElasticsearchStatusException e3 = expectThrows(ElasticsearchStatusException.class,
                    () -> restClient.security().delegatePkiAuthentication(delegatePkiRequest3, optionsBuilder.build()));
            assertThat(e3.getMessage(), startsWith("Elasticsearch exception [type=security_exception, reason=unable to authenticate user"));
        }
    }

    private X509Certificate readCertForPkiDelegation(String certName) throws Exception {
        Path path = getDataPath("/org/elasticsearch/xpack/security/action/pki_delegation/" + certName);
        try (InputStream in = Files.newInputStream(path)) {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            return (X509Certificate) factory.generateCertificate(in);
        }
    }

}