text:
<?php

namespace Laradic\Console;

use Illuminate\Console\Command as BaseCommand;
use Laradic\Console\Helpers\ColorHelper;
use Laradic\Console\Helpers\ModesHelper;
use Laradic\Console\Helpers\TreeHelper;
use Laradic\Support\Vendor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * The abstract Command class. Other commands can extend this class to benefit from a larger toolset
 *
 * @package     Laradic\Console
 * @author      Robin Radic
 * @license     MIT
 * @copyright   2011-2015, Robin Radic
 * @link        http://radic.mit-license.org
 *
 */
abstract class Command extends BaseCommand
{
    /**
     * @var bool
     */
    protected $enabled = true;

    /**
     * @var bool
     */
    protected $allowSudo = false;

    /**
     * @var bool
     */
    protected $requireSudo = false;

    /**
     * @var \Laradic\Console\Color
     */
    protected $colors;

    /**
     * If enabled, the command will run on production environment
     * @var bool
     */
    protected $env = [];

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

    /**
     * Get the Laravel application instance.
     *
     * @return \Illuminate\Contracts\Foundation\Application
     */
    public function getLaravel()
    {
        return $this->laravel;
    }

    /**
     * @param $styles
     * @param $text
     *
     * @return string
     * @throws \JakubOnderka\PhpConsoleColor\InvalidStyleException
     * @internal param array|string $style
     */
    public function colorize($styles, $text)
    {
        return $this->style($styles, $text);
    }

    /**
     * style
     *
     * @param $styles
     * @param $str
     *
     * @return string
     * @throws \JakubOnderka\PhpConsoleColor\InvalidStyleException
     */
    protected function style($styles, $str)
    {
        return $this->color()->apply($styles, $str);
    }

    /** @return TreeHelper */
    protected function tree()
    {
        return $this->getHelper('tree');
    }

    /** @return ColorHelper */
    protected function color()
    {
        return $this->getHelper('color');
    }

    /** @return ModesHelper */
    public function modes()
    {
        return $this->getHelper('modes');
    }

    /**
     * hasRootAccess
     *
     * @return bool
     */
    public function hasRootAccess()
    {
        $path = '/root/.' . md5('_radic-cli-perm-test' . time());
        $root = (@file_put_contents($path, '1') === false ? false : true);
        if ($root !== false) {
            $this->getLaravel()->make('files')->delete($path);
        }

        return $root !== false;
    }

    /**
     * execute
     *
     * @param \Symfony\Component\Console\Input\InputInterface   $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @return mixed
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->allowSudo and !$this->requireSudo and $this->hasRootAccess()) {
            $this->error('Cannot execute this command with root privileges');
            exit;
        }

        if ($this->requireSudo and !$this->hasRootAccess()) {
            $this->error('This command requires root privileges');
            exit;
        }

        $this->fireEvent('firing', [$this]);
        $return = null;
        if (method_exists($this, 'handle')) {
            $return = $this->handle();
        }
        if (method_exists($this, 'fire')) {
            $return = $this->fire();
        }
        $this->fireEvent('fired', [$this]);

        return $return;
    }

    /**
     * @param mixed
     */
    public function dump($dump)
    {
        if (class_exists('Kint')) {
            \Kint::dump(func_get_args());
        } elseif (class_exists('Symfony\\Component\\VarDumper\\VarDumper')) {
            \Symfony\Component\VarDumper\VarDumper::dump(func_get_args());
        } else {
            var_dump(func_get_args());
        }
    }

    /**
     * arrayTable
     *
     * @param       $arr
     * @param array $header
     */
    protected function arrayTable($arr, array $header = [ 'Key', 'Value' ])
    {
        $rows = [ ];
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $val = print_r(array_slice($val, 0, 5), true);
            }
            $rows[] = [ (string)$key, (string)$val ];
        }
        $this->table($header, $rows);
    }

    /**
     * Write a string as error output.
     *
     * @param  string $string
     *
     * @return string
     */
    public function error($string, $verbosity = null)
    {
        $this->output->writeln("<error>$string</error>");

        return $string;
    }

    /**
     * @inheritDoc
     * @return string
     */
    public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null)
    {
        return parent::choice($question, $choices, $default, $attempts, $multiple);
    }

    /**
     * title method
     *
     * @param $text
     *
     * @return mixed
     */
    public function title($text)
    {
        $this->output->title($text);

        return $text;
    }

    /**
     * listing method
     *
     * @param array $items
     *
     * @return array
     */
    public function listing(array $items = [ ])
    {
        $this->output->listing($items);

        return $items;
    }

    /**
     * section method
     *
     * @param $text
     *
     * @return mixed
     */
    public function section($text)
    {
        $this->output->section($text);

        return $text;
    }

    /**
     * note method
     *
     * @param $text
     *
     * @return mixed
     */
    public function note($text)
    {
        $this->output->note($text);

        return $text;
    }

    /**
     * writeln method
     *
     * @param $text
     *
     * @return mixed
     */
    public function writeln($text)
    {
        $this->output->writeln($text);

        return $text;
    }

    /**
     * write method
     *
     * @param $text
     *
     * @return mixed
     */
    public function write($text)
    {
        $this->output->write($text);

        return $text;
    }

    /**
     * success method
     *
     * @param $text
     *
     * @return mixed
     */
    public function success($text)
    {
        $this->output->success($text);

        return $text;
    }

    /**
     * warning method
     *
     * @param $text
     *
     * @return mixed
     */
    public function warning($text)
    {
        $this->output->warning($text);

        return $text;
    }

    /**
     * caution method
     *
     * @param $text
     *
     * @return mixed
     */
    public function caution($text)
    {
        $this->output->caution($text);

        return $text;
    }

    public function isEnabled()
    {
        return $this->enabled; // TODO: Change the autogenerated stub
    }

    /**
     * Set the enabled value
     *
     * @param boolean $enabled
     *
     * @return Command
     */
    public function enable()
    {
        $this->enabled = true;

        return $this;
    }

    public function disable()
    {
        $this->enabled = true;

        return $this;
    }

    /**
     * getApplication method
     *
     * @return Artisan
     */
    public function getApplication()
    {
        return parent::getApplication(); // TODO: Change the autogenerated stub
    }

    public function hasOption($name)
    {
        return $this->input->hasOption($name);
    }

    public function hasArgument($name)
    {
        return $this->input->hasArgument($name);
    }

    protected function fireEvent($name, array $payload = [ ])
    {
        $events  = $this->getLaravel()->make('events');
        $command = $this->getName();
        $events->fire("command.{$name}: {$command}", array_replace_recursive([ $this ], $payload));
    }

    public function askArgument($key, $question = null, $default = null)
    {
        $arg = $this->argument($key);
        if ( $arg === null )
        {
            $question = $question ?: "{$key}?";
            $arg      = $this->ask($question, $default);
        }
        return $arg;
    }

    public function askSecretArgument($key, $question = null, $default = null)
    {
        $arg = $this->argument($key);
        if ( $arg === null )
        {
            $question = $question ?: "{$key}?";
            $arg      = $this->secret($question, $default);
        }
        return $arg;
    }

    public function askChoiceArgument($key, array $choices, $question = null, $default = null, $multi = false)
    {
        $arg = $this->argument($key);
        if ( null === $arg )
        {
            $question = $question ?: "$key?";
            $arg = parent::choice($question, $choices, $default, null, $multi);
        }
        if(false === in_array($arg, $choices, true)){
            throw new Exception("Given $key is not in " . implode(', ', $choices));
        }
        return $arg;
    }
}


text:
<?php

/**
 * Service definition for Replicapool (v1beta2).
 *
 *

 * [Deprecated. Please use Instance Group Manager in Compute API] Provides
 * groups of homogenous Compute Engine instances.

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class Google_Service_Replicapool extends Google_Service
{
  /** View and manage your data across Google Cloud Platform services. */
  const CLOUD_PLATFORM =
      "https://www.googleapis.com/auth/cloud-platform";
  /** View your data across Google Cloud Platform services. */
  const CLOUD_PLATFORM_READ_ONLY =
      "https://www.googleapis.com/auth/cloud-platform.read-only";
  /** View and manage your Google Compute Engine resources. */
  const COMPUTE =
      "https://www.googleapis.com/auth/compute";
  /** View your Google Compute Engine resources. */
  const COMPUTE_READONLY =
      "https://www.googleapis.com/auth/compute.readonly";

  public $instanceGroupManagers;
  public $zoneOperations;

  /**
   * Constructs the internal representation of the Replicapool service.
   *
   * @param Google_Client $client
   */
  public function __construct(Google_Client $client)
  {
    parent::__construct($client);
    $this->rootUrl = 'https://www.googleapis.com/';
    $this->servicePath = 'replicapool/v1beta2/projects/';
    $this->version = 'v1beta2';
    $this->serviceName = 'replicapool';

    $this->instanceGroupManagers = new Google_Service_Replicapool_Resource_InstanceGroupManagers(
        $this,
        $this->serviceName,
        'instanceGroupManagers',
        array(
          'methods' => array(
            'abandonInstances' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/abandonInstances',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'delete' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}',
              'httpMethod' => 'DELETE',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'deleteInstances' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/deleteInstances',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'get' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}',
              'httpMethod' => 'GET',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'insert' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'size' => array(
                  'location' => 'query',
                  'type' => 'integer',
                  'required' => true,
                ),
              ),
            ),'list' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers',
              'httpMethod' => 'GET',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'filter' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'maxResults' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
                'pageToken' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
              ),
            ),'recreateInstances' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/recreateInstances',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'resize' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/resize',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'size' => array(
                  'location' => 'query',
                  'type' => 'integer',
                  'required' => true,
                ),
              ),
            ),'setInstanceTemplate' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setInstanceTemplate',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'setTargetPools' => array(
              'path' => '{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setTargetPools',
              'httpMethod' => 'POST',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'instanceGroupManager' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),
          )
        )
    );
    $this->zoneOperations = new Google_Service_Replicapool_Resource_ZoneOperations(
        $this,
        $this->serviceName,
        'zoneOperations',
        array(
          'methods' => array(
            'get' => array(
              'path' => '{project}/zones/{zone}/operations/{operation}',
              'httpMethod' => 'GET',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'operation' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
              ),
            ),'list' => array(
              'path' => '{project}/zones/{zone}/operations',
              'httpMethod' => 'GET',
              'parameters' => array(
                'project' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'zone' => array(
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ),
                'filter' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
                'maxResults' => array(
                  'location' => 'query',
                  'type' => 'integer',
                ),
                'pageToken' => array(
                  'location' => 'query',
                  'type' => 'string',
                ),
              ),
            ),
          )
        )
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace AppUIBasics.ControlPages
{
    [ContentProperty(Name="Example")]
    public sealed partial class ControlExample : UserControl
    {
        public static readonly DependencyProperty HeaderTextProperty = DependencyProperty.Register("HeaderText", typeof(string), typeof(ControlExample), new PropertyMetadata(null));
        public string HeaderText
        {
            get { return (string)GetValue(HeaderTextProperty); }
            set { SetValue(HeaderTextProperty, value); }
        }

        public static readonly DependencyProperty ExampleProperty = DependencyProperty.Register("Example", typeof(object), typeof(ControlExample), new PropertyMetadata(null));
        public object Example
        {
            get { return GetValue(ExampleProperty); }
            set { SetValue(ExampleProperty, value); }
        }

        public static readonly DependencyProperty XamlProperty = DependencyProperty.Register("Xaml", typeof(object), typeof(ControlExample), new PropertyMetadata(null));
        public object Xaml
        {
            get { return GetValue(XamlProperty); }
            set
            {
                if (value != null)
                    XamlBorder.Visibility = Visibility.Visible;
                SetValue(XamlProperty, value);
            }
        }

        public static readonly DependencyProperty ExampleHeightProperty = DependencyProperty.Register("ExampleHeight", typeof(GridLength), typeof(ControlExample), new PropertyMetadata(new GridLength(1, GridUnitType.Star)));
        public GridLength ExampleHeight
        {
            get { return (GridLength)GetValue(ExampleHeightProperty); }
            set { SetValue(ExampleHeightProperty, value); }
        }

        public new static readonly DependencyProperty HorizontalContentAlignmentProperty = DependencyProperty.Register("HorizontalContentAlignment", typeof(HorizontalAlignment), typeof(ControlExample), new PropertyMetadata(HorizontalAlignment.Left));
        public new HorizontalAlignment HorizontalContentAlignment
        {
            get { return (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty); }
            set { SetValue(HorizontalContentAlignmentProperty, value); }
        }

        public ControlExample()
        {
            this.InitializeComponent();

            if (Xaml == null)
            {
                XamlBorder.Visibility = Visibility.Collapsed;
            }
        }
    }
}


text:
package org.apache.avro.io;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.io.parsing.JsonGrammarGenerator;
import org.apache.avro.io.parsing.Parser;
import org.apache.avro.io.parsing.Symbol;
import org.apache.avro.util.Utf8;
import org.codehaus.jackson.Base64Variant;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonLocation;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonStreamContext;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.ObjectCodec;

/** A {@link Decoder} for Avro's JSON data encoding.
 *

 * Construct using {@link DecoderFactory}.
 *

 * JsonDecoder is not thread-safe.
 * */
public class JsonDecoder extends ParsingDecoder
  implements Parser.ActionHandler {
  private JsonParser in;
  private static JsonFactory jsonFactory = new JsonFactory();
  Stack<ReorderBuffer> reorderBuffers = new Stack<ReorderBuffer>();
  ReorderBuffer currentReorderBuffer;

  private static class ReorderBuffer {
    public Map<String, List<JsonElement>> savedFields = new HashMap<String, List<JsonElement>>();
    public JsonParser origParser = null;
  }

  static final String CHARSET = "ISO-8859-1";

  private JsonDecoder(Symbol root, InputStream in) throws IOException {
    super(root);
    configure(in);
  }

  private JsonDecoder(Symbol root, String in) throws IOException {
    super(root);
    configure(in);
  }

  JsonDecoder(Schema schema, InputStream in) throws IOException {
    this(getSymbol(schema), in);
  }

  JsonDecoder(Schema schema, String in) throws IOException {
    this(getSymbol(schema), in);
  }

  private static Symbol getSymbol(Schema schema) {
    if (null == schema) {
      throw new NullPointerException("Schema cannot be null!");
    }
    return new JsonGrammarGenerator().generate(schema);
  }

  /**
   * Reconfigures this JsonDecoder to use the InputStream provided.
   *

   * If the InputStream provided is null, a NullPointerException is thrown.
   *

   * Otherwise, this JsonDecoder will reset its state and then
   * reconfigure its input.
   * @param in
   *   The IntputStream to read from. Cannot be null.
   * @throws IOException
   * @return this JsonDecoder
   */
  public JsonDecoder configure(InputStream in) throws IOException {
    if (null == in) {
      throw new NullPointerException("InputStream to read from cannot be null!");
    }
    parser.reset();
    this.in = jsonFactory.createJsonParser(in);
    this.in.nextToken();
    return this;
  }

  /**
   * Reconfigures this JsonDecoder to use the String provided for input.
   *

   * If the String provided is null, a NullPointerException is thrown.
   *

   * Otherwise, this JsonDecoder will reset its state and then
   * reconfigure its input.
   * @param in
   *   The String to read from. Cannot be null.
   * @throws IOException
   * @return this JsonDecoder
   */
  public JsonDecoder configure(String in) throws IOException {
    if (null == in) {
      throw new NullPointerException("String to read from cannot be null!");
    }
    parser.reset();
    this.in = new JsonFactory().createJsonParser(in);
    this.in.nextToken();
    return this;
  }

  private void advance(Symbol symbol) throws IOException {
    this.parser.processTrailingImplicitActions();
    if (in.getCurrentToken() == null && this.parser.depth() == 1)
      throw new EOFException();
    parser.advance(symbol);
  }

  @Override
  public void readNull() throws IOException {
    advance(Symbol.NULL);
    if (in.getCurrentToken() == JsonToken.VALUE_NULL) {
      in.nextToken();
    } else {
      throw error("null");
    }
  }

  @Override
  public boolean readBoolean() throws IOException {
    advance(Symbol.BOOLEAN);
    JsonToken t = in.getCurrentToken();
    if (t == JsonToken.VALUE_TRUE || t == JsonToken.VALUE_FALSE) {
      in.nextToken();
      return t == JsonToken.VALUE_TRUE;
    } else {
      throw error("boolean");
    }
  }

  @Override
  public int readInt() throws IOException {
    advance(Symbol.INT);
    if (in.getCurrentToken().isNumeric()) {
      int result = in.getIntValue();
      in.nextToken();
      return result;
    } else {
      throw error("int");
    }
  }

  @Override
  public long readLong() throws IOException {
    advance(Symbol.LONG);
    if (in.getCurrentToken().isNumeric()) {
      long result = in.getLongValue();
      in.nextToken();
      return result;
    } else {
      throw error("long");
    }
  }

  @Override
  public float readFloat() throws IOException {
    advance(Symbol.FLOAT);
    if (in.getCurrentToken().isNumeric()) {
      float result = in.getFloatValue();
      in.nextToken();
      return result;
    } else {
      throw error("float");
    }
  }

  @Override
  public double readDouble() throws IOException {
    advance(Symbol.DOUBLE);
    if (in.getCurrentToken().isNumeric()) {
      double result = in.getDoubleValue();
      in.nextToken();
      return result;
    } else {
      throw error("double");
    }
  }

  @Override
  public Utf8 readString(Utf8 old) throws IOException {
    return new Utf8(readString());
  }

  @Override
  public String readString() throws IOException {
    advance(Symbol.STRING);
    if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) {
      parser.advance(Symbol.MAP_KEY_MARKER);
      if (in.getCurrentToken() != JsonToken.FIELD_NAME) {
        throw error("map-key");
      }
    } else {
      if (in.getCurrentToken() != JsonToken.VALUE_STRING) {
        throw error("string");
      }
    }
    String result = in.getText();
    in.nextToken();
    return result;
  }

  @Override
  public void skipString() throws IOException {
    advance(Symbol.STRING);
    if (parser.topSymbol() == Symbol.MAP_KEY_MARKER) {
      parser.advance(Symbol.MAP_KEY_MARKER);
      if (in.getCurrentToken() != JsonToken.FIELD_NAME) {
        throw error("map-key");
      }
    } else {
      if (in.getCurrentToken() != JsonToken.VALUE_STRING) {
        throw error("string");
      }
    }
    in.nextToken();
  }

  @Override
  public ByteBuffer readBytes(ByteBuffer old) throws IOException {
    advance(Symbol.BYTES);
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
      byte[] result = readByteArray();
      in.nextToken();
      return ByteBuffer.wrap(result);
    } else {
      throw error("bytes");
    }
  }

  private byte[] readByteArray() throws IOException {
    byte[] result = in.getText().getBytes(CHARSET);
    return result;
  }

  @Override
  public void skipBytes() throws IOException {
    advance(Symbol.BYTES);
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
      in.nextToken();
    } else {
      throw error("bytes");
    }
  }

  private void checkFixed(int size) throws IOException {
    advance(Symbol.FIXED);
    Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol();
    if (size != top.size) {
      throw new AvroTypeException(
        "Incorrect length for fixed binary: expected " +
        top.size + " but received " + size + " bytes.");
    }
  }

  @Override
  public void readFixed(byte[] bytes, int start, int len) throws IOException {
    checkFixed(len);
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
      byte[] result = readByteArray();
      in.nextToken();
      if (result.length != len) {
        throw new AvroTypeException("Expected fixed length " + len
            + ", but got" + result.length);
      }
      System.arraycopy(result, 0, bytes, start, len);
    } else {
      throw error("fixed");
    }
  }

  @Override
  public void skipFixed(int length) throws IOException {
    checkFixed(length);
    doSkipFixed(length);
  }

  private void doSkipFixed(int length) throws IOException {
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
      byte[] result = readByteArray();
      in.nextToken();
      if (result.length != length) {
        throw new AvroTypeException("Expected fixed length " + length
            + ", but got" + result.length);
      }
    } else {
      throw error("fixed");
    }
  }

  @Override
  protected void skipFixed() throws IOException {
    advance(Symbol.FIXED);
    Symbol.IntCheckAction top = (Symbol.IntCheckAction) parser.popSymbol();
    doSkipFixed(top.size);
  }

  @Override
  public int readEnum() throws IOException {
    advance(Symbol.ENUM);
    Symbol.EnumLabelsAction top = (Symbol.EnumLabelsAction) parser.popSymbol();
    if (in.getCurrentToken() == JsonToken.VALUE_STRING) {
      in.getText();
      int n = top.findLabel(in.getText());
      if (n >= 0) {
        in.nextToken();
        return n;
      }
      throw new AvroTypeException("Unknown symbol in enum " + in.getText());
    } else {
      throw error("fixed");
    }
  }

  @Override
  public long readArrayStart() throws IOException {
    advance(Symbol.ARRAY_START);
    if (in.getCurrentToken() == JsonToken.START_ARRAY) {
      in.nextToken();
      return doArrayNext();
    } else {
      throw error("array-start");
    }
  }

  @Override
  public long arrayNext() throws IOException {
    advance(Symbol.ITEM_END);
    return doArrayNext();
  }

  private long doArrayNext() throws IOException {
    if (in.getCurrentToken() == JsonToken.END_ARRAY) {
      parser.advance(Symbol.ARRAY_END);
      in.nextToken();
      return 0;
    } else {
      return 1;
    }
  }

  @Override
  public long skipArray() throws IOException {
    advance(Symbol.ARRAY_START);
    if (in.getCurrentToken() == JsonToken.START_ARRAY) {
      in.skipChildren();
      in.nextToken();
      advance(Symbol.ARRAY_END);
    } else {
      throw error("array-start");
    }
    return 0;
  }

  @Override
  public long readMapStart() throws IOException {
    advance(Symbol.MAP_START);
    if (in.getCurrentToken() == JsonToken.START_OBJECT) {
      in.nextToken();
      return doMapNext();
    } else {
      throw error("map-start");
    }
  }

  @Override
  public long mapNext() throws IOException {
    advance(Symbol.ITEM_END);
    return doMapNext();
  }

  private long doMapNext() throws IOException {
    if (in.getCurrentToken() == JsonToken.END_OBJECT) {
      in.nextToken();
      advance(Symbol.MAP_END);
      return 0;
    } else {
      return 1;
    }
  }

  @Override
  public long skipMap() throws IOException {
    advance(Symbol.MAP_START);
    if (in.getCurrentToken() == JsonToken.START_OBJECT) {
      in.skipChildren();
      in.nextToken();
      advance(Symbol.MAP_END);
    } else {
      throw error("map-start");
    }
    return 0;
  }

  @Override
  public int readIndex() throws IOException {
    advance(Symbol.UNION);
    Symbol.Alternative a = (Symbol.Alternative) parser.popSymbol();

    String label;
    if (in.getCurrentToken() == JsonToken.VALUE_NULL) {
      label = "null";
    } else if (in.getCurrentToken() == JsonToken.START_OBJECT &&
               in.nextToken() == JsonToken.FIELD_NAME) {
      label = in.getText();
      in.nextToken();
      parser.pushSymbol(Symbol.UNION_END);
    } else {
      throw error("start-union");
    }
    int n = a.findLabel(label);
    if (n < 0)
      throw new AvroTypeException("Unknown union branch " + label);
    parser.pushSymbol(a.getSymbol(n));
    return n;
  }

  @Override
  public Symbol doAction(Symbol input, Symbol top) throws IOException {
    if (top instanceof Symbol.FieldAdjustAction) {
        Symbol.FieldAdjustAction fa = (Symbol.FieldAdjustAction) top;
        String name = fa.fname;
      if (currentReorderBuffer != null) {
        List<JsonElement> node = currentReorderBuffer.savedFields.get(name);
        if (node != null) {
          currentReorderBuffer.savedFields.remove(name);
          currentReorderBuffer.origParser = in;
          in = makeParser(node);
          return null;
        }
      }
      if (in.getCurrentToken() == JsonToken.FIELD_NAME) {
        do {
          String fn = in.getText();
          in.nextToken();
          if (name.equals(fn)) {
            return null;
          } else {
            if (currentReorderBuffer == null) {
              currentReorderBuffer = new ReorderBuffer();
            }
            currentReorderBuffer.savedFields.put(fn, getVaueAsTree(in));
          }
        } while (in.getCurrentToken() == JsonToken.FIELD_NAME);
        throw new AvroTypeException("Expected field name not found: " + fa.fname);
      }
    } else if (top == Symbol.FIELD_END) {
      if (currentReorderBuffer != null && currentReorderBuffer.origParser != null) {
        in = currentReorderBuffer.origParser;
        currentReorderBuffer.origParser = null;
      }
    } else if (top == Symbol.RECORD_START) {
      if (in.getCurrentToken() == JsonToken.START_OBJECT) {
        in.nextToken();
        reorderBuffers.push(currentReorderBuffer);
        currentReorderBuffer = null;
      } else {
        throw error("record-start");
      }
    } else if (top == Symbol.RECORD_END || top == Symbol.UNION_END) {
      if (in.getCurrentToken() == JsonToken.END_OBJECT) {
        in.nextToken();
        if (top == Symbol.RECORD_END) {
          if (currentReorderBuffer != null && !currentReorderBuffer.savedFields.isEmpty()) {
            throw error("Unknown fields: " + currentReorderBuffer.savedFields.keySet());
          }
          currentReorderBuffer = reorderBuffers.pop();
        }
      } else {
        throw error(top == Symbol.RECORD_END ? "record-end" : "union-end");
      }
    } else {
      throw new AvroTypeException("Unknown action symbol " + top);
    }
    return null;
  }

  private static class JsonElement {
    public final JsonToken token;
    public final String value;
    public JsonElement(JsonToken t, String value) {
      this.token = t;
      this.value = value;
    }

    public JsonElement(JsonToken t) {
      this(t, null);
    }
  }

  private static List<JsonElement> getVaueAsTree(JsonParser in) throws IOException {
    int level = 0;
    List<JsonElement> result = new ArrayList<JsonElement>();
    do {
      JsonToken t = in.getCurrentToken();
      switch (t) {
      case START_OBJECT:
      case START_ARRAY:
        level++;
        result.add(new JsonElement(t));
        break;
      case END_OBJECT:
      case END_ARRAY:
        level--;
        result.add(new JsonElement(t));
        break;
      case FIELD_NAME:
      case VALUE_STRING:
      case VALUE_NUMBER_INT:
      case VALUE_NUMBER_FLOAT:
      case VALUE_TRUE:
      case VALUE_FALSE:
      case VALUE_NULL:
        result.add(new JsonElement(t, in.getText()));
        break;
      }
      in.nextToken();
    } while (level != 0);
    result.add(new JsonElement(null));
    return result;
  }

  private JsonParser makeParser(final List<JsonElement> elements) throws IOException {
    return new JsonParser() {
      int pos = 0;

      @Override
      public ObjectCodec getCodec() {
        throw new UnsupportedOperationException();
      }

      @Override
      public void setCodec(ObjectCodec c) {
        throw new UnsupportedOperationException();
      }

      @Override
      public void close() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public JsonToken nextToken() throws IOException {
        pos++;
        return elements.get(pos).token;
      }

      @Override
      public JsonParser skipChildren() throws IOException {
        int level = 0;
        do {
          switch(elements.get(pos++).token) {
          case START_ARRAY:
          case START_OBJECT:
            level++;
            break;
          case END_ARRAY:
          case END_OBJECT:
            level--;
            break;
          }
        } while (level > 0);
        return this;
      }

      @Override
      public boolean isClosed() {
        throw new UnsupportedOperationException();
      }

      @Override
      public String getCurrentName() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public JsonStreamContext getParsingContext() {
        throw new UnsupportedOperationException();
      }

      @Override
      public JsonLocation getTokenLocation() {
        throw new UnsupportedOperationException();
      }

      @Override
      public JsonLocation getCurrentLocation() {
        throw new UnsupportedOperationException();
      }

      @Override
      public String getText() throws IOException {
        return elements.get(pos).value;
      }

      @Override
      public char[] getTextCharacters() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public int getTextLength() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public int getTextOffset() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public Number getNumberValue() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public NumberType getNumberType() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public int getIntValue() throws IOException {
        return Integer.parseInt(getText());
      }

      @Override
      public long getLongValue() throws IOException {
        return Long.parseLong(getText());
      }

      @Override
      public BigInteger getBigIntegerValue() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public float getFloatValue() throws IOException {
        return Float.parseFloat(getText());
      }

      @Override
      public double getDoubleValue() throws IOException {
        return Double.parseDouble(getText());
      }

      @Override
      public BigDecimal getDecimalValue() throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public byte[] getBinaryValue(Base64Variant b64variant)
        throws IOException {
        throw new UnsupportedOperationException();
      }

      @Override
      public JsonToken getCurrentToken() {
        return elements.get(pos).token;
      }
    };
  }

  private AvroTypeException error(String type) {
    return new AvroTypeException("Expected " + type +
        ". Got " + in.getCurrentToken());
  }

}


text:
/**
 * @requires phabricator-notification
 *           javelin-stratcom
 *           javelin-behavior
 * @provides javelin-behavior-phabricator-notification-example
 */

JX.behavior('phabricator-notification-example', function(config) {

  var sequence = 0;

  JX.Stratcom.listen(
    'click',
    'notification-example',
    function(e) {
      e.kill();

      var notification = new JX.Notification();
      switch (sequence % 4) {
        case 0:
          var update = function() {
            notification.setContent('It is ' + new Date().toString());
          };

          update();
          setInterval(update, 1000);

          break;
        case 1:
          notification
            .setContent('Permanent alert notification (until clicked).')
            .setDuration(0)
            .alterClassName('jx-notification-alert', true);
          break;
        case 2:
          notification
            .setContent('This notification reacts when you click it.');

          notification.listen(
            'activate',
            function() {
              if (!confirm("Close notification?")) {
                JX.Stratcom.context().kill();
              }
            });
          break;
        case 3:
          notification
            .setDuration(2000)
            .setContent('This notification will close after 2 seconds ' +
                        'unless you keep clicking it!');

          notification.listen(
            'activate',
            function() {
              notification.setDuration(2000);
              JX.Stratcom.context().kill();
            });
          break;
      }

      notification.show();
      sequence++;
    });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"

       default-init-method="initialize"
       default-destroy-method="destroy">

    <!-- Based off of system/flows/authn/external-authn-beans.xml -->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"
          p:placeholderPrefix="%{" p:placeholderSuffix="}" />

    <bean class="net.shibboleth.ext.spring.config.IdentifiableBeanPostProcessor" />
    <bean class="net.shibboleth.idp.profile.impl.ProfileActionBeanPostProcessor" />

    <!-- Default strategy function to obtain the external path. -->
    <bean id="shibboleth.authn.Cas.externalAuthnPathStrategy"
          class="com.google.common.base.Functions" factory-method="constant"
          c:_0-ref="shibboleth.authn.Cas.externalAuthnPath" />

    <bean id="ValidateExternalAuthentication"
          class="net.shibboleth.idp.authn.impl.ValidateExternalAuthentication" scope="prototype"
          p:matchExpression="#{getObject('shibboleth.authn.Cas.matchExpression')}"
          p:addDefaultPrincipals="#{getObject('shibboleth.authn.Cas.addDefaultPrincipals') ?: true}"
          p:classifiedMessages-ref="shibboleth.authn.Cas.ClassifiedMessageMap"
          p:resultCachingPredicate="#{getObject('shibboleth.authn.Cas.resultCachingPredicate')}" />

    <bean id="PopulateSubjectCanonicalizationContext"
          class="net.shibboleth.idp.authn.impl.PopulateSubjectCanonicalizationContext" scope="prototype"
          p:availableFlows-ref="shibboleth.PostLoginSubjectCanonicalizationFlows" />

    <!-- Based off of conf/auth/external-authn-config.xml-->

    <bean id="shibboleth.authn.Cas.externalAuthnPath" class="java.lang.String"
          c:_0="contextRelative:Authn/ExtCas" />

    <util:map id="shibboleth.authn.Cas.ClassifiedMessageMap">
        <entry key="AuthenticationException">
            <list>
                <value>AuthenticationException</value>
            </list>
        </entry>
        <entry key="InvalidAuthenticationContext">
            <list>
                <value>InvalidAuthenticationContext</value>
            </list>
        </entry>
        <entry key="NoPassive">
            <list>
                <value>NoPassive</value>
            </list>
        </entry>
        <entry key="NoCredentials">
            <list>
                <value>InvalidTicket</value>
            </list>
        </entry>
    </util:map>

</beans>


text:
package org.onosproject.net.packet.impl;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.Device;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flowobjective.DefaultForwardingObjective;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.Objective;
import org.onosproject.net.flowobjective.ObjectiveContext;
import org.onosproject.net.flowobjective.ObjectiveError;
import org.onosproject.net.packet.DefaultPacketRequest;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketEvent;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketProcessorEntry;
import org.onosproject.net.packet.PacketProvider;
import org.onosproject.net.packet.PacketProviderRegistry;
import org.onosproject.net.packet.PacketProviderService;
import org.onosproject.net.packet.PacketRequest;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.packet.PacketStore;
import org.onosproject.net.packet.PacketStoreDelegate;
import org.onosproject.net.provider.AbstractProviderRegistry;
import org.onosproject.net.provider.AbstractProviderService;
import org.slf4j.Logger;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.security.AppGuard.checkPermission;
import static org.onosproject.security.AppPermission.Type.*;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Provides a basic implementation of the packet SB & NB APIs.
 */
@Component(immediate = true)
@Service
public class PacketManager
        extends AbstractProviderRegistry<PacketProvider, PacketProviderService>
        implements PacketService, PacketProviderRegistry {

    private final Logger log = getLogger(getClass());

    private static final String TABLE_TYPE_MSG =
            "Table Type cannot be null. For requesting packets without " +
                    "table hints, use other methods in the packetService API";

    private final PacketStoreDelegate delegate = new InternalStoreDelegate();

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    private CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    private DeviceService deviceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    private FlowRuleService flowService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    private PacketStore store;

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    private FlowObjectiveService objectiveService;

    private ExecutorService eventHandlingExecutor;

    private final DeviceListener deviceListener = new InternalDeviceListener();

    private final List<ProcessorEntry> processors = Lists.newCopyOnWriteArrayList();

    private ApplicationId appId;

    @Activate
    public void activate() {
        eventHandlingExecutor = Executors.newSingleThreadExecutor(
                groupedThreads("onos/net/packet", "event-handler"));
        appId = coreService.getAppId(CoreService.CORE_APP_NAME);
        store.setDelegate(delegate);
        deviceService.addListener(deviceListener);
        store.existingRequests().forEach(this::pushToAllDevices);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        store.unsetDelegate(delegate);
        deviceService.removeListener(deviceListener);
        eventHandlingExecutor.shutdown();
        log.info("Stopped");
    }

    @Override
    public void addProcessor(PacketProcessor processor, int priority) {
        checkPermission(PACKET_EVENT);
        checkNotNull(processor, "Processor cannot be null");
        ProcessorEntry entry = new ProcessorEntry(processor, priority);

        // Insert the new processor according to its priority.
        int i = 0;
        for (; i < processors.size(); i++) {
            if (priority < processors.get(i).priority()) {
                break;
            }
        }
        processors.add(i, entry);
    }

    @Override
    public void removeProcessor(PacketProcessor processor) {
        checkPermission(PACKET_EVENT);
        checkNotNull(processor, "Processor cannot be null");

        // Remove the processor entry.
        for (int i = 0; i < processors.size(); i++) {
            if (processors.get(i).processor() == processor) {
                processors.remove(i);
                break;
            }
        }
    }

    @Override
    public List<PacketProcessorEntry> getProcessors() {
        return ImmutableList.copyOf(processors);
    }

    @Override
    public void requestPackets(TrafficSelector selector, PacketPriority priority,
                               ApplicationId appId) {
        checkPermission(PACKET_READ);
        checkNotNull(selector, "Selector cannot be null");
        checkNotNull(appId, "Application ID cannot be null");

        PacketRequest request = new DefaultPacketRequest(selector, priority, appId);
        if (store.requestPackets(request)) {
            pushToAllDevices(request);
        }
    }

    @Override
    public void cancelPackets(TrafficSelector selector, PacketPriority priority,
                              ApplicationId appId) {
        checkPermission(PACKET_READ);
        checkNotNull(selector, "Selector cannot be null");
        checkNotNull(appId, "Application ID cannot be null");

        PacketRequest request = new DefaultPacketRequest(selector, priority, appId);
        if (store.cancelPackets(request)) {
            removeFromAllDevices(request);
        }
    }

    @Override
    public List<PacketRequest> getRequests() {
        return store.existingRequests();
    }

    /**
     * Pushes all rules to the specified device.
     *
     * @param device device on which to install packet request flows
     */
    private void pushRulesToDevice(Device device) {
        log.debug("Pushing packet requests to device {}", device.id());
        for (PacketRequest request : store.existingRequests()) {
            pushRule(device, request);
        }
    }

    /**
     * Pushes a packet request flow rule to all devices.
     *
     * @param request the packet request
     */
    private void pushToAllDevices(PacketRequest request) {
        log.debug("Pushing packet request {} to all devices", request);
        for (Device device : deviceService.getDevices()) {
            pushRule(device, request);
        }
    }

    /**
     * Removes packet request flow rule from all devices.
     *
     * @param request the packet request
     */
    private void removeFromAllDevices(PacketRequest request) {
        deviceService.getAvailableDevices().forEach(d -> removeRule(d, request));
    }

    /**
     * Pushes packet intercept flow rules to the device.
     *
     * @param device  the device to push the rules to
     * @param request the packet request
     */
    private void pushRule(Device device, PacketRequest request) {
        if (!device.type().equals(Device.Type.SWITCH)) {
            return;
        }

        ForwardingObjective forwarding = createBuilder(request)
                .add(new ObjectiveContext() {
                    @Override
                    public void onError(Objective objective, ObjectiveError error) {
                        log.warn("Failed to install packet request {} to {}: {}",
                                 request, device.id(), error);
                    }
                });

        objectiveService.forward(device.id(), forwarding);
    }

    /**
     * Removes packet intercept flow rules from the device.
     *
     * @param device  the device to remove the rules deom
     * @param request the packet request
     */
    private void removeRule(Device device, PacketRequest request) {
        if (!device.type().equals(Device.Type.SWITCH)) {
            return;
        }
        ForwardingObjective forwarding = createBuilder(request)
                .remove(new ObjectiveContext() {
                    @Override
                    public void onError(Objective objective, ObjectiveError error) {
                        log.warn("Failed to withdraw packet request {} from {}: {}",
                                 request, device.id(), error);
                    }
                });
        objectiveService.forward(device.id(), forwarding);
    }

    private DefaultForwardingObjective.Builder createBuilder(PacketRequest request) {
        return DefaultForwardingObjective.builder()
                .withPriority(request.priority().priorityValue())
                .withSelector(request.selector())
                .fromApp(appId)
                .withFlag(ForwardingObjective.Flag.VERSATILE)
                .withTreatment(DefaultTrafficTreatment.builder().punt().build())
                .makePermanent();
    }

    @Override
    public void emit(OutboundPacket packet) {
        checkPermission(PACKET_WRITE);
        checkNotNull(packet, "Packet cannot be null");
        store.emit(packet);
    }

    private void localEmit(OutboundPacket packet) {
        Device device = deviceService.getDevice(packet.sendThrough());
        if (device == null) {
            return;
        }
        PacketProvider packetProvider = getProvider(device.providerId());
        if (packetProvider != null) {
            packetProvider.emit(packet);
        }
    }

    @Override
    protected PacketProviderService createProviderService(PacketProvider provider) {
        return new InternalPacketProviderService(provider);
    }

    /**
     * Personalized packet provider service issued to the supplied provider.
     */
    private class InternalPacketProviderService
            extends AbstractProviderService<PacketProvider>
            implements PacketProviderService {

        protected InternalPacketProviderService(PacketProvider provider) {
            super(provider);
        }

        @Override
        public void processPacket(PacketContext context) {
            // TODO filter packets sent to processors based on registrations
            for (ProcessorEntry entry : processors) {
                long start = System.nanoTime();
                entry.processor().process(context);
                entry.addNanos(System.nanoTime() - start);
            }
        }

    }

    /**
     * Internal callback from the packet store.
     */
    private class InternalStoreDelegate implements PacketStoreDelegate {
        @Override
        public void notify(PacketEvent event) {
            localEmit(event.subject());
        }
    }

    /**
     * Internal listener for device service events.
     */
    private class InternalDeviceListener implements DeviceListener {
        @Override
        public void event(DeviceEvent event) {
            eventHandlingExecutor.execute(() -> {
                try {
                    Device device = event.subject();
                    switch (event.type()) {
                        case DEVICE_ADDED:
                        case DEVICE_AVAILABILITY_CHANGED:
                            if (deviceService.isAvailable(event.subject().id())) {
                                pushRulesToDevice(device);
                            }
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    log.warn("Failed to process {}", event, e);
                }
            });
        }
    }

    /**
     * Entity for tracking stats for a packet processor.
     */
    private class ProcessorEntry implements PacketProcessorEntry {
        private final PacketProcessor processor;
        private final int priority;
        private long invocations = 0;
        private long nanos = 0;

        public ProcessorEntry(PacketProcessor processor, int priority) {
            this.processor = processor;
            this.priority = priority;
        }

        @Override
        public PacketProcessor processor() {
            return processor;
        }

        @Override
        public int priority() {
            return priority;
        }

        @Override
        public long invocations() {
            return invocations;
        }

        @Override
        public long totalNanos() {
            return nanos;
        }

        @Override
        public long averageNanos() {
            return invocations > 0 ? nanos / invocations : 0;
        }

        void addNanos(long nanos) {
            this.nanos += nanos;
            this.invocations++;
        }
    }
}


text:
.class Landroid/support/v4/view/ViewPager$4;
.super Ljava/lang/Object;
.source "ViewPager.java"

# interfaces
.implements Landroid/support/v4/view/OnApplyWindowInsetsListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v4/view/ViewPager;->initViewPager()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field private final mTempRect:Landroid/graphics/Rect;

.field final synthetic this$0:Landroid/support/v4/view/ViewPager;

# direct methods
.method constructor <init>(Landroid/support/v4/view/ViewPager;)V
    .registers 3
    .param p1, "this$0"    # Landroid/support/v4/view/ViewPager;

    .prologue
    .line 425
    iput-object p1, p0, Landroid/support/v4/view/ViewPager$4;->this$0:Landroid/support/v4/view/ViewPager;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 426
    new-instance v0, Landroid/graphics/Rect;

    invoke-direct {v0}, Landroid/graphics/Rect;-><init>()V

    iput-object v0, p0, Landroid/support/v4/view/ViewPager$4;->mTempRect:Landroid/graphics/Rect;

    return-void
.end method

# virtual methods
.method public onApplyWindowInsets(Landroid/view/View;Landroid/support/v4/view/WindowInsetsCompat;)Landroid/support/v4/view/WindowInsetsCompat;
    .registers 12
    .param p1, "v"    # Landroid/view/View;
    .param p2, "originalInsets"    # Landroid/support/v4/view/WindowInsetsCompat;

    .prologue
    .line 432
    .line 433
    invoke-static {p1, p2}, Landroid/support/v4/view/ViewCompat;->onApplyWindowInsets(Landroid/view/View;Landroid/support/v4/view/WindowInsetsCompat;)Landroid/support/v4/view/WindowInsetsCompat;

    move-result-object v0

    .line 434
    .local v0, "applied":Landroid/support/v4/view/WindowInsetsCompat;
    invoke-virtual {v0}, Landroid/support/v4/view/WindowInsetsCompat;->isConsumed()Z

    move-result v5

    if-eqz v5, :cond_b

    .line 468
    .end local v0    # "applied":Landroid/support/v4/view/WindowInsetsCompat;
    :goto_a
    return-object v0

    .line 446
    .restart local v0    # "applied":Landroid/support/v4/view/WindowInsetsCompat;
    :cond_b
    iget-object v4, p0, Landroid/support/v4/view/ViewPager$4;->mTempRect:Landroid/graphics/Rect;

    .line 447
    .local v4, "res":Landroid/graphics/Rect;
    invoke-virtual {v0}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetLeft()I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->left:I

    .line 448
    invoke-virtual {v0}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetTop()I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->top:I

    .line 449
    invoke-virtual {v0}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetRight()I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->right:I

    .line 450
    invoke-virtual {v0}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetBottom()I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->bottom:I

    .line 452
    const/4 v3, 0x0

    .local v3, "i":I
    iget-object v5, p0, Landroid/support/v4/view/ViewPager$4;->this$0:Landroid/support/v4/view/ViewPager;

    invoke-virtual {v5}, Landroid/support/v4/view/ViewPager;->getChildCount()I

    move-result v2

    .local v2, "count":I
    :goto_2c
    if-ge v3, v2, :cond_6b

    .line 453
    iget-object v5, p0, Landroid/support/v4/view/ViewPager$4;->this$0:Landroid/support/v4/view/ViewPager;

    .line 454
    invoke-virtual {v5, v3}, Landroid/support/v4/view/ViewPager;->getChildAt(I)Landroid/view/View;

    move-result-object v5

    invoke-static {v5, v0}, Landroid/support/v4/view/ViewCompat;->dispatchApplyWindowInsets(Landroid/view/View;Landroid/support/v4/view/WindowInsetsCompat;)Landroid/support/v4/view/WindowInsetsCompat;

    move-result-object v1

    .line 457
    .local v1, "childInsets":Landroid/support/v4/view/WindowInsetsCompat;
    invoke-virtual {v1}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetLeft()I

    move-result v5

    iget v6, v4, Landroid/graphics/Rect;->left:I

    invoke-static {v5, v6}, Ljava/lang/Math;->min(II)I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->left:I

    .line 459
    invoke-virtual {v1}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetTop()I

    move-result v5

    iget v6, v4, Landroid/graphics/Rect;->top:I

    invoke-static {v5, v6}, Ljava/lang/Math;->min(II)I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->top:I

    .line 461
    invoke-virtual {v1}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetRight()I

    move-result v5

    iget v6, v4, Landroid/graphics/Rect;->right:I

    invoke-static {v5, v6}, Ljava/lang/Math;->min(II)I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->right:I

    .line 463
    invoke-virtual {v1}, Landroid/support/v4/view/WindowInsetsCompat;->getSystemWindowInsetBottom()I

    move-result v5

    iget v6, v4, Landroid/graphics/Rect;->bottom:I

    invoke-static {v5, v6}, Ljava/lang/Math;->min(II)I

    move-result v5

    iput v5, v4, Landroid/graphics/Rect;->bottom:I

    .line 452
    add-int/lit8 v3, v3, 0x1

    goto :goto_2c

    .line 468
    .end local v1    # "childInsets":Landroid/support/v4/view/WindowInsetsCompat;
    :cond_6b
    iget v5, v4, Landroid/graphics/Rect;->left:I

    iget v6, v4, Landroid/graphics/Rect;->top:I

    iget v7, v4, Landroid/graphics/Rect;->right:I

    iget v8, v4, Landroid/graphics/Rect;->bottom:I

    invoke-virtual {v0, v5, v6, v7, v8}, Landroid/support/v4/view/WindowInsetsCompat;->replaceSystemWindowInsets(IIII)Landroid/support/v4/view/WindowInsetsCompat;

    move-result-object v0

    goto :goto_a
.end method


text:
<?php

/* TestBlogBundle:Blog:modifier.html.twig */
class __TwigTemplate_6870533230981e1c98021f201428505522234affb0465fbe7f57a2d7e657dbf4 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("TestBlogBundle::layout.html.twig");

        $this->blocks = array(
            'testBlogBody' => array($this, 'block_testBlogBody'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "TestBlogBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_testBlogBody($context, array $blocks = array())
    {
        // line 3
        echo "\t
Modifier un article

\t
\t";
        // line 5
        $this->env->loadTemplate("TestBlogBundle:Blog:formulaire.html.twig")->display($context);
        // line 6
        echo "\t
\t

\t\tAttention!! Cet article sera directement modifié sur la page d'accueil après validation de ce formulaire\t
\t

\t
\t

\t\tenv, $this->env->getExtension('routing')->getPath("testblog_voir", array("id" => $this->getAttribute((isset($context["article"]) ? $context["article"] : $this->getContext($context, "article")), "id"))), "html", null, true);
        echo "\" class='btn'>
\t\t\t
\t\t\tRetour à l'article
\t\t
\t

\t
";
    }

    public function getTemplateName()
    {
        return "TestBlogBundle:Blog:modifier.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  45 => 12,  37 => 6,  35 => 5,  31 => 3,  28 => 2,);
    }
}


text:
.. EN-Revision: none
.. _zend.service.amazon.s3:

Zend\Service_Amazon\S3
======================

.. _zend.service.amazon.s3.introduction:

Einführung
----------

Amazon S3 bietet ein einfaches Webservice Interface das verwendet werden kann um beliebige Mengen an Daten,
jederzeit und von überall her aus dem Web, zu Speichern und erhalten. Es gibt Entwicklern den Zugriff auf die
gleiche, hoch skalierbare, verfügbare, schnelle und kostengünstige Datenspeicher Infrastruktur die Amazon
verwendet um sein eigenes globales Netzwerk an Websites zu betreiben. Der Service zielt darauf ab den Nutzen der
Skalierbarkeit zu erhöhen und diese Vorteile an Entwickler weiterzugeben.

.. _zend.service.amazon.s3.registering:

Registrierung mit Amazon S3
---------------------------

Bevor man mit ``Zend\Service_Amazon\S3`` beginnen kann, muß man einen Account registrieren. Sehen Sie bitte auf
die Amazon Website `S3 FAQ`_ für weitere Informationen.

Nach der Registrierung erhält man einen Anwendungsschlüssel und einen geheimen Schlüssel. Man benötigt beide um
auf den S3 Service zugreifen zu können.

.. _zend.service.amazon.s3.apiDocumentation:

API Dokumentation
-----------------

Die Klasse ``Zend\Service_Amazon\S3`` bietet einen *PHP* Wrapper zum Amazon S3 REST Interface. Schauen Sie bitte in
die `Amazon S3 Dokumentation`_ für eine detailierte Beschreibung des Services. Man muß mit dem grundsätzlichen
Konzept vertraut sein um dieses Service nutzen zu können.

.. _zend.service.amazon.s3.features:

Features
--------

``Zend\Service_Amazon\S3`` bietet die folgenden Funktionalitäten:

   - Einen einzelnen Punkt für die Konfiguration der eigenen amazon.s3 Zugangsdaten der über dem kompletten
     amazon.s3 Namespace verwendet werden kann.

   - Ein Proxy Objekt das bequemer zu verwenden ist als ein *HTTP* Client alleine, da er hauptsächlich die
     Notwendigkeit eliminiert manuell eine *HTTP* POST Anfrage über den REST Service zu erstellen.

   - Ein Antwort-Wrapper der jede Antwort erhebt und eine Exception wirft wenn ein Fehler aufgetreten ist, was die
     Notwendigkeit eliminiert den Erfolg vieler Kommandos wiederholt zu prüfen.

   - Zusätzliche bequeme Methoden für einige der üblicheren Operationen.

.. _zend.service.amazon.s3.storing-your-first:

Beginnen wir
------------

Sobald man sich mit Amazon S3 registriert hat, ist man bereit sein erstes Objekt auf S3 zu speichern. Die Objekte
werden auf S3 in Containern gespeichert, die "Buckets" genannt werden. Der Name der Buckets ist auf S3 eindeutig,
und jeder Benutzer kann nicht mehr als 100 Buckets simultan besitzen. Jeder Bucket kann eine unlimitierte Anzahl an
Objekten enthalten, die durch den Namen identifiziert werden.

Das folgende Beispiel demonstriert die Erstellung eines Buckets, und das Speichern und Empfangen von Daten.

.. _zend.service.amazon.s3.storing-your-first.example:

.. rubric:: Beispiel der Verwendung von Zend\Service_Amazon\S3

.. code-block:: php
   :linenos:

   require_once 'Zend/Service/Amazon/S3.php';

   $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

   $s3->createBucket("my-own-bucket");

   $s3->putObject("my-own-bucket/myobject", "somedata");

   echo $s3->getObject("my-own-bucket/myobject");

Da der ``Zend\Service_Amazon\S3`` Service eine Authentifizierung benötigt, sollte man seine Zugangsdaten (AWS
Schlüssel und Geheimschlüssel) an den Konstruktor übergeben. Wenn man nur einen Account verwendet, kann man
Standard-Zugangsdaten für das Service setzen:

.. code-block:: php
   :linenos:

   require_once 'Zend/Service/Amazon/S3.php';

   Zend\Service_Amazon\S3::setKeys($my_aws_key, $my_aws_secret_key);
   $s3 = new Zend\Service_Amazon\S3();

.. _zend.service.amazon.s3.buckets:

Bucket Operationen
------------------

Alle Objekte im S3 System werden in Buckets gespeichert. Buckets müssen erstellt werden bevor Speicheroperationen
durchgeführt werden. Der Name des Buckets ist im System eindeutig, so das man den Bucket nicht so benennen kann
wie den Bucket einer anderen Person.

Namen von Buckets können Kleinbuchstaben, Ziffern, Punkte (.), Unterstriche (\_), und Bindestriche (-) enthalten.
Es sind keine anderen Symbole erlaubt. Bucketnamen sollten mit einem Buchstaben oder einer Ziffer beginnen, und 3
bis 255 Zeichen lang sein. Namen die wie eine IP Adresse aussehen (z.B. "192.168.16.255") sind nicht erlaubt.

- ``createBucket()`` erstellt einen neuen Bucket.

- ``cleanBucket()`` entfernt alle Objekte die in einem Bucket enthalten sind.

- ``removeBucket()`` entfernt den Bucket vom System. Der Bucket sollte leer sein damit er entfernt werden kann.

  .. _zend.service.amazon.s3.buckets.remove.example:

  .. rubric:: Beispiel für das Entfernen eines Buckets in Zend\Service_Amazon\S3

  .. code-block:: php
     :linenos:

     require_once 'Zend/Service/Amazon/S3.php';

     $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

     $s3->cleanBucket("my-own-bucket");
     $s3->removeBucket("my-own-bucket");

- ``getBuckets()`` gibt eine Liste der Namen aller Buckets zurück die einem Benutzer gehören.

  .. _zend.service.amazon.s3.buckets.list.example:

  .. rubric:: Beispiel für das Auflisten der Buckets in Zend\Service_Amazon\S3

  .. code-block:: php
     :linenos:

     require_once 'Zend/Service/Amazon/S3.php';

     $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

     $list = $s3->getBuckets();
     foreach ($list as $bucket) {
       echo "Ich habe das Bucket $bucket\n";
     }

- ``isBucketAvailable()`` prüft ob das Bucket existiert und gibt ``TRUE`` zurück wenn das der Fall ist.

.. _zend.service.amazon.s3.objects:

Operationen am Objekt
---------------------

Das Objekte ist die grundsätzliche Speichereinheit in S3. Objekte speichern nicht strukturierte Daten, welche jede
Größe, bis zu 4 Gigabyte, haben können. Es gibt kein Limit in der Anzahl der Objekte die auf dem System
gespeichert werden können.

Objekte werden in Buckets abgelegt. Sie werden durch den Namen identifiziert, der jeder UTF-8 String sein kann. Es
ist üblich hierarchische Namen zu verwenden (wie z.B. *Pictures/Myself/CodingInPHP.jpg* um Objektnamen zu
organisieren. Objektnamen wird der Bucketname vorangestellt wenn Objektfunktionen verwendet werden, so dass das
Objekt "mydata" im Bucket "my-own-bucket" den Namen *my-own-bucket/mydata* haben würde.

Objekte können ersetzt (durch Überschreiben neuer Daten mit dem gleichen Schlüssel) oder gelöscht werden, aber
nicht geändert, angefügt, usw. Objekte werden immer als Ganzes gespeichert.

Standardmäßig sind alle Objekte privat und es kann nur durch Ihren Besitzer auf Sie zugegriffen werden. Trotzdem
ist es möglich Objekte mit öffentlichem Zugriff zu spezifizieren, wodurch man auf Sie mit der folgenden *URL*
zugreifen kann: *http://s3.amazonaws.com/[bucket-name]/[object-name]*.

- ``putObject($object, $data, $meta)`` erstellt ein Objekt mit dem Namen ``$object`` (Sollte den Bucketnamen als
  Präfix enthalten!) das ``$data`` als seinen Inhalt besitzt.

  Der optionale ``$meta`` Parameter ist das Array von Metadaten, welches aktuell die folgenden Schlüssel enthalten
  kann:

  **S3_CONTENT_TYPE_HEADER**
     *MIME* Content Type der Daten. Wenn nicht angegeben, wird der Typ anhand der Dateiextension des Objektnamens
     geschätzt.

  **S3_ACL_HEADER**
     Der Zugriff auf das Element. Folgende Zugriffskonstanten können verwendet werden:

        **S3_ACL_PRIVATE**
           Nur der Besitzer hat auf das Element Zugriff.

        **S3_ACL_PUBLIC_READ**
           Jeder kann das Objekt lesen, aber nur der Besitzer kann schreiben. Diese Eigenschaft kann verwendet
           werden um öffentlich zugängliche Inhalte zu speichern.

        **S3_ACL_PUBLIC_WRITE**
           Jeder kann das Objekt schreiben oder lesen. Diese Eigenschaft sollte sehr spärlich verwendet werden.

        **S3_ACL_AUTH_READ**
           Nur der Besitzer hat Schreibzugriff auf das Element, und andere authentifizierte S3 Benutzer haben
           Leserechte. Das ist nützlich um Daten zwischen S3 Accounts zu teilen ohne Sie der Öffentlichkeit
           zugänglich zu machen.

     Standardmäßig sind alle diese Elemente privat.

     .. _zend.service.amazon.s3.objects.public.example:

     .. rubric:: Beispiel für ein öffentliches Objekt in Zend\Service_Amazon\S3

     .. code-block:: php
        :linenos:

        require_once 'Zend/Service/Amazon/S3.php';

        $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

        $s3->putObject("my-own-bucket/Pictures/Me.png", file_get_contents("me.png"),
            array(Zend\Service_Amazon\S3::S3_ACL_HEADER =>
                  Zend\Service_Amazon\S3::S3_ACL_PUBLIC_READ));
        // oder:
        $s3->putFile("me.png", "my-own-bucket/Pictures/Me.png",
            array(Zend\Service_Amazon\S3::S3_ACL_HEADER =>
                  Zend\Service_Amazon\S3::S3_ACL_PUBLIC_READ));
        echo "Go to http://s3.amazonaws.com/my-own-bucket/Pictures/Me.png to see me!\n";

- ``getObject($object)`` empfängt Objektdaten vom Speicher anhand des Namens.

- ``removeObject($object)`` entfernt das Objekt vom Speicher.

- ``getInfo($object)`` empfängt die Metadaten des Objekts. Diese Funktion gibt ein Array mit Metadaten zurück.
  Einige der nützlichen Schlüssel sind:

     **type**
        Der *MIME* Typ des Elements.

     **size**
        Die Größe der Objektdaten.

     **mtime**
        UNIX-artiger Zeitstempel der letzten Änderung für das Objekt.

     **etag**
        Das ETag der Daten, welches ein MD5 Hash der Daten ist, eingeklammert von Hochkomma (").

  Die Funktion gibt ``FALSE`` zurück wenn der Schlüssel keinem der existierenden Objekte entspricht.

- ``getObjectsByBucket($bucket)`` gibt eine Liste der Objektschlüssel zurüc, die im Bucket enthalten sind.

  .. _zend.service.amazon.s3.objects.list.example:

  .. rubric:: Beispiel für die Auflistung eines Zend\Service_Amazon\S3 Objekts

  .. code-block:: php
     :linenos:

     require_once 'Zend/Service/Amazon/S3.php';

     $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

     $list = $s3->getObjectsByBucket("my-own-bucket");
     foreach ($list as $name) {
       echo "Ich habe $name Schlüssel:\n";
       $data = $s3->getObject("my-own-bucket/$name");
       echo "with data: $data\n";
     }

- ``isObjectAvailable($object)`` prüft ob das Objekt mit dem angegebenen Namen existiert.

- ``putFile($path, $object, $meta)`` fügt den Inhalt der Datei unter ``$path`` in das Objekt mit dem Namen
  ``$object`` ein.

  Das optionale Argument ``$meta`` ist das gleiche wie für *putObject*. Wenn der Content-Typ nicht angegeben wird,
  wird er anhand des Dateinamens vermutet.

.. _zend.service.amazon.s3.streaming:

Daten Streamen
--------------

Es ist möglich Objekte zu Holen und Setzen wobei keine Stream Daten verwendet werden die im Speicher sind, sondern
Dateien oder *PHP* Streams. Das ist Speziell dann nützlich wenn Dateien sehr groß sind um nicht über
Speichergrenzen zu kommen.

Um ein Objekt mit Streaming zu Empfangen muss die Methode ``getObjectStream($object, $filename)`` verwendet werden.
Diese Methode gibt einen ``Zend\Http_Response\Stream`` zurück, welcher wie im Kapitel :ref:`HTTP Client Daten
Streaming <zend.http.client.streaming>` verwendet werden kann.

      .. _zend.service.amazon.s3.streaming.example1:

      .. rubric:: Beispiel für das Streamen von Daten mit Zend\Service_Amazon\S3

      .. code-block:: php
         :linenos:

         $response = $amazon->getObjectStream("mybycket/zftest");
         // Datei kopieren
         copy($response->getStreamName(), "my/downloads/file");
         // Hinauf Streamen
         $fp = fopen("my/downloads/file2", "w");
         stream_copy_to_stream($response->getStream(), $fp);

Der zweite Parameter für ``getObjectStream()`` ist optional und spezifiziert die Zieldatei in welche die dAten
geschrieben werden. Wenn er nicht spezifiziert ist, wird eine temporäre Datei verwendet. Diese wird gelöscht
nachdem das Antwort-Objekt gelöscht wurde.

Um ein Objekt mit Streaming zu Senden kann ``putFileStream()`` verwendet werden. Es hat die gleiche Signatur wie
``putFile()`` verwendet aber Streaming und liest die Datei nicht in den Speicher ein.

Man kann auch eine Stream Ressource an die ``putObject()`` Methode als Daten Parameter übergeben. In diesem Fall
werden die Daten vom Stream gelesen wenn die Anfrage an den Server gesendet wird.

.. _zend.service.amazon.s3.streams:

Stream wrapper
--------------

Zusätzlich zum oben beschriebenen Interface unterstützt ``Zend\Service_Amazon\S3`` das Arbeiten als Stream
Wrapper. Hierfür muß das Client-Objekt als Stream Wrapper registriert werden:

.. _zend.service.amazon.s3.streams.example:

.. rubric:: Beispiel für Streams mit Zend\Service_Amazon\S3

.. code-block:: php
   :linenos:

   require_once 'Zend/Service/Amazon/S3.php';

   $s3 = new Zend\Service_Amazon\S3($my_aws_key, $my_aws_secret_key);

   $s3->registerStreamWrapper("s3");

   mkdir("s3://my-own-bucket");
   file_put_contents("s3://my-own-bucket/testdata", "mydata");

   echo file_get_contents("s3://my-own-bucket/testdata");

Die Verzeichnis-Operationen (*mkdir*, *rmdir*, *opendir*, usw.) werden an Buckets ausgeführt und deshalb sollten
deren Argumente in der Form *s3://bucketname* angegeben werden. Dateioperationen werden an Objekten ausgeführt.
Objekt Erstellung, Lesen, Schreiben, Löschen, Stat und Anzeigen von Verzeichnissen wird unterstützt.

.. _`S3 FAQ`: http://aws.amazon.com/s3/faqs/
.. _`Amazon S3 Dokumentation`: http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=48


text:
This code is the code used for the "Domain Separation Networks" paper
by Bousmalis K., Trigeorgis G., et al. which was presented at NIPS 2016. The
paper can be found here: https://arxiv.org/abs/1608.06019.

## Contact
This code was open-sourced by [Konstantinos Bousmalis](https://github.com/bousmalis) (konstantinos@google.com).

## Installation
You will need to have the following installed on your machine before trying out the DSN code.

*  Tensorflow: https://www.tensorflow.org/install/
*  Bazel: https://bazel.build/

## Important Note
Although we are making the code available, you are only able to use the MNIST
provider for now. We will soon provide a script to download and convert MNIST-M
as well. Check back here in a few weeks or wait for a relevant announcement from
[@bousmalis](https://twitter.com/bousmalis).

## Running the code for adapting MNIST to MNIST-M
In order to run the MNIST to MNIST-M experiments with DANNs and/or DANNs with
domain separation (DSNs) you will need to set the directory you used to download
MNIST and MNIST-M:

```
$ export DSN_DATA_DIR=/your/dir
```

Add models and models/slim to your `$PYTHONPATH`:

```
$ export PYTHONPATH=$PYTHONPATH:$PWD:$PWD/slim
```

Then you need to build the binaries with Bazel:

```
$ bazel build -c opt domain_adaptation/domain_separation/...
```

You can then train with the following command:

```
$ ./bazel-bin/domain_adaptation/domain_separation/dsn_train  \
      --similarity_loss=dann_loss  \
      --basic_tower=dann_mnist  \
      --source_dataset=mnist  \
      --target_dataset=mnist_m  \
      --learning_rate=0.0117249  \
      --gamma_weight=0.251175  \
      --weight_decay=1e-6  \
      --layers_to_regularize=fc3  \
      --nouse_separation  \
      --master=""  \
      --dataset_dir=${DSN_DATA_DIR}  \
      -v --use_logging
```

Evaluation can be invoked with the following command:

```
$ ./bazel-bin/domain_adaptation/domain_separation/dsn_eval  \
    -v --dataset mnist_m --split test --num_examples=9001  \
    --dataset_dir=${DSN_DATA_DIR}
```


text:
namespace vespalib::crypto::openssl_impl {

class PrivateKeyImpl : public PrivateKey {
    EvpPkeyPtr _pkey;
    Type _type;
public:
    PrivateKeyImpl(EvpPkeyPtr pkey, Type type) noexcept
        : _pkey(std::move(pkey)),
          _type(type)
    {}
    ~PrivateKeyImpl() override = default;

    ::EVP_PKEY* native_key() noexcept { return _pkey.get(); }
    const ::EVP_PKEY* native_key() const noexcept { return _pkey.get(); }

    Type type() const noexcept override { return _type; }
    vespalib::string private_to_pem() const override;

    static std::shared_ptr<PrivateKeyImpl> generate_openssl_p256_ec_key();
};

class X509CertificateImpl : public X509Certificate {
    X509Ptr _cert;
public:
    explicit X509CertificateImpl(X509Ptr cert) noexcept : _cert(std::move(cert)) {}
    ~X509CertificateImpl() = default;

    ::X509* native_cert() noexcept { return _cert.get(); }
    const ::X509* native_cert() const noexcept { return _cert.get(); }

    vespalib::string to_pem() const override;

    // Generates an X509 certificate using a SHA-256 digest
    static std::shared_ptr<X509CertificateImpl> generate_openssl_x509_from(Params params);
};

}