text:
<?php
namespace packages\base;

use packages\base\frontend\{theme, events\throwDynamicData};
use packages\base\view\events\{beforeLoad, afterLoad, afterOutput};

class View {

	/**
	 * Find a view by it's name or parents name.
	 *
	 * @param string $viewName [parent] Full Qualified Class Name.
	 * @throws packages\base\NoViewException if cannot find any view by this name or parent name.
	 * @return packages\base\view
	 */
	public static function byName(string $viewName): view {
		$location = frontend\theme::locate($viewName);
		if (!$location) {
			throw new NoViewException($viewName);
		}
		$sources = frontend\theme::byName($location['source']->getName());
		foreach ($sources as $source) {
			$source->registerTranslates(translator::getCodeLang());
		}
		$view = new $location['name']();
		$view->setSource($location['source']);
		return $view;
	}

	/** @var string[] */
	protected $title = [];

	/** @var string */
	protected $description = "";

	/** @var string|\packages\base\IO\file|null */
	protected $file;

	/** @var \packages\base\frontend\Source */
	protected $source;

	/** @var array */
	protected $css = [];

	/** @var array */
	protected $js = [];

	/** @var mixed */
	protected $data = [];

	/** @var \packages\base\view\error[] */
	protected $errors = [];

	/** @var \packages\base\frontend\events\throwDynamicData */
	protected $dynamicData;

	/**
	 * Construct the view and assets by Its frontend source.
	 *
	 * @param \packages\base\frontend\Source $source
	 */
	public function __construct() {
		$this->dynamicData = new throwDynamicData();
		$this->dynamicData->setView($this);
	}

	/**
	 * Setter for view title
	 *
	 * @param string|string[] $title
	 * @return void
	 */
	public function setTitle($title): void {
		if (!is_array($title)) {
			$title = [$title];
		}
		$this->title = $title;
	}

	/**
	 * Getter title
	 *
	 * @param string|null $glue
	 * @return string|array if glue wasn't empty it will keep titles togheter and return string, in otherwise return array of title parts.
	 */
	public function getTitle(?string $glue = ' | ') {
		return $glue ? implode($glue, $this->title) : $this->title;
	}

	/**
	 * Setter for description of view
	 *
	 * @param string $description
	 * @return void
	 */
	public function setDescription(string $description): void {
		$this->description = $description;
	}

	/**
	 * Getter for description of view
	 *
	 * @return string
	 */
	public function getDescription(): string {
		return $this->description;
	}

	public function getCSSAssets(): array {
		return $this->css;
	}
	public function getJSAssets(): array {
		return $this->js;
	}

	/**
	 * Add an inline of css block.
	 *
	 * @param string $code
	 * @param string $name
	 * @return void
	 */
	public function addCSS(string $code, string $name = ""): void {
		$this->css[] = array(
			'name' => $name,
			'type' => 'inline',
			'code' => $code
		);
	}

	/**
	 * Add a link to css file.
	 *
	 * @param string $file Should be public URL.
	 * @param string $name It will set to file URL if it was empty (or not set).
	 * @param bool $preload default: false
	 * @return void
	 */
	public function addCSSFile(string $file, string $name = "", $preload = false): void {
		if($name == ""){
			$name = $file;
		}
		$this->css[] = array(
			'name' => $name,
			'type' => 'file',
			'file' => $file,
			'preload' => $preload
		);
	}

	/**
	 * Find first css asset by given name.
	 *
	 * @param string $name
	 * @return void
	 */
	public function removeCSS(string $name): void {
		foreach ($this->css as $key => $css) {
			if ($css['name'] == $name) {
				unset($this->css[$key]);
				return;
			}
		}
	}

	/**
	 * Add an inline of Javascript block.
	 *
	 * @param string $code
	 * @param string $name
	 * @return void
	 */
	public function addJS(string $code, string $name = ""): void {
		$this->js[] = array(
			'name' => $name,
			'type' => 'inline',
			'code' => $code
		);
	}

	/**
	 * Add a link to Javascript file.
	 *
	 * @param string $file Should be public URL.
	 * @param string $name It will set to file URL if it was empty (or not set).
	 * @return void
	 */
	public function addJSFile(string $file, string $name = ""): void {
		if($name == ""){
			$name = $file;
		}
		$this->js[] = array(
			'name' => $name,
			'type' => 'file',
			'file' => $file
		);
	}

	/**
	 * Find first Javascript asset by given name.
	 *
	 * @param string $name
	 * @return void
	 */
	public function removeJS(string $name): void {
		foreach ($this->js as $key=> $js) {
			if ($js['name'] == $name) {
				unset($this->js[$key]);
				return;
			}
		}
	}

	/**
	 * Clear all CSS and Javascript assets from view.
	 *
	 * @return void
	 */
	public function clearAssets(): void {
		$this->js = [];
		$this->css = [];
	}

	/**
	 * Clear all Javascript assets from view.
	 *
	 * @return void
	 */
	public function clearJSAssets(): void {
		$this->js = [];
	}

	/**
	 * Clear all CSS assets from view.
	 *
	 * @return void
	 */
	public function clearCSSAssets(): void {
		$this->css = [];
	}

	/**
	 * Getter for dynamic data.
	 *
	 * @return \packages\base\frontend\events\throwDynamicData
	 */
	public function dynamicData(): throwDynamicData {
		if(!$this->dynamicData){
			$this->dynamicData = new throwDynamicData();
			$this->dynamicData->setView($this);
		}
		return $this->dynamicData;
	}

	/**
	 * Set html file.
	 *
	 * @param \packages\base\IO\file $file
	 * @return void
	 */
	public function setFile(IO\file $file): void {
		$this->file = $file;
	}

	/**
	 * Get html file.
	 *
	 * @return \packages\base\IO\file|null
	 */
	public function getFile(): ?IO\file {
		if (is_string($this->file)) {
			$this->file = $this->source->getHome()->file($this->file);
		}
		return $this->file;
	}

	/**
	 * Attach a data to view.
	 *
	 * @param mixed $data
	 * @param string|null $key
	 * @return void
	 */
	public function setData($data, ?string $key = null): void {
		if ($key) {
			$this->data[$key] = $data;
		} else {
			$this->data = $data;
		}
	}

	/**
	 * Get data attached to data.
	 *
	 * @param string|null $key
	 * @return mixed|false return null if cannot found the key.
	 */
	public function getData(?string $key = null) {
		if ($key) {
			return(isset($this->data[$key]) ? $this->data[$key] : null);
		} else {
			return $this->data;
		}
	}

	/**
	 * Add a error to view.
	 *
	 * @param \packages\base\view\error $error
	 * @return void
	 */
	public function addError(view\error $error): void {
		$this->errors[] = $error;
	}

	/**
	 * Return the first error.
	 *
	 * @return \packages\base\view\error|null
	 */
	public function getError() {
		return ($this->errors ? $this->errors[0] : null);
	}

	/**
	 * Getter for all errors.
	 *
	 * @return \packages\base\view\error[]
	 */
	public function getErrors(): array {
		return $this->errors;
	}

	/**
	 * Getter for source of view.
	 *
	 * @return \packages\base\frontend\Source
	 */
	public function getSource(){
		return $this->source;
	}

	/**
	 * Setter for source
	 *
	 * @param \packages\base\frontend\Source $source
	 * @return void
	 */
	public function setSource(frontend\Source $source): void {
		$this->source = $source;
		frontend\theme::setPrimarySource($source);
		$sources = frontend\theme::byName($source->getName());
		foreach ($sources as $source) {
			foreach ($source->getAssets(['css', 'js']) as $asset) {
				if ($asset['type'] == 'css') {
					if (isset($asset['file'])) {
						$this->addCSSFile(theme::url($asset['file']), $asset['name'] ?? '', $asset['preload'] ?? false);
					} elseif (isset($asset['inline'])){
						$this->addCSS($asset['inline'], $asset['name'] ?? '');
					}
				} elseif ($asset['type'] == 'js') {
					if (isset($asset['file'])) {
						$this->addJSFile(theme::url($asset['file']), $asset['name'] ?? '');
					} elseif (isset($asset['inline'])) {
						$this->addJS($asset['inline'], $asset['name'] ?? '');
					}
				}
			}
		}
	}

	/**
	 * Ouput the html file.
	 *
	 * @return void
	 */
	public function output() {
		$this->loadHTMLFile();
		if (!$this->file) {
			return;
		}

		frontend\theme::loadViews();
		(new beforeLoad($this))->trigger();
		$this->dynamicData()->trigger();
		if (method_exists($this, '__beforeLoad')){
			$this->__beforeLoad();
		}
		(new afterLoad($this))->trigger();
		$this->dynamicData()->addAssets();

		require_once($this->file->getPath());

		(new afterOutput($this))->trigger();
	}

	/**
	 * Genrate html tags to load CSS assets by browser.
	 *
	 * @return void
	 */
	protected function loadCSS(): void {
		foreach ($this->css as $css){
			if ($css['type'] == 'file') {
				if ($css['preload']) {
					echo("<link rel=\"preload\" type=\"text/css\" href=\"{$css['file']}\" as=\"style\" onload=\"this.onload=null;this.rel='stylesheet'\">\n");
					echo("<noscript><link rel=\"stylesheet\" type=\"text/css\" href=\"{$css['file']}\"></noscript>\n");
				} else {
					echo("<link rel=\"stylesheet\" type=\"text/css\" href=\"{$css['file']}\" />\n");
				}
			}
		}
		foreach ($this->css as $css) {
			if ($css['type'] == 'inline'){
				echo("<style>\n{$css['code']}\n</style>\n");
			}
		}
	}

	/**
	 * Genrate html tags to load Javascript assets by browser.
	 *
	 * @return void
	 */
	protected function loadJS(): void {
		foreach ($this->js as $js) {
			if ($js['type'] == 'inline') {
				echo("<script>\n{$js['code']}\n</script>\n");
			}
		}
		foreach ($this->js as $js) {
			if ($js['type'] == 'file') {
				echo("<script async src=\"{$js['file']}\"></script>\n");
			}
		}
	}

	/**
	 * Locate html file and put in $file property based on this priority:
	 *  1. $file property of extended class.
	 *  2. theme.json file.
	 *  3. same path of view file in frontend source in it's html directory.
	 *
	 * @throws IO\NotFoundException if located file doesn't exist
	 * @return void
	 */
	protected function loadHTMLFile(): void {
		if (!$this->source) {
			return;
		}
		if ($this->file) {
			if (!is_string($this->file)) {
				return;
			}
			$this->file = $this->source->getFile($this->file);
		} else {
			$this->file = $this->source->getHTMLFile(get_class($this));
			if ($this->file) {
				return;
			}
			$reflection = new \ReflectionClass(get_class($this));
			$thisFile = $reflection->getFileName();
			$sourceHome = $this->source->getHome()->getRealPath();
			$file = substr($thisFile, strlen($sourceHome) + 1);
			$file = $this->source->getFile("html" . substr($file, strpos($file, "/")));
			$this->file = $file;
		}
		if ($this->file and !$this->file->exists()) {
			throw new IO\NotFoundException($this->file);
		}
	}
}


text:
<?php

namespace AppBundle\Form\Report;

use AppBundle\Entity\Report\MoneyShortCategory;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as FormTypes;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MoneyShortCategoryType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                 ->add('typeId', FormTypes\HiddenType::class)
                 ->add('present', FormTypes\CheckboxType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
             'data_class' => MoneyShortCategory::class,
             'validation_groups' => ['TODO'],
             'translation_domain' => 'report-money-short',
        ]);
    }

    public function getBlockPrefix()
    {
        return 'category';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class WPWAF_Model_Topic {

    public $post_type;
    public $topic_category_taxonomy;
    public $topic_tag_taxonomy;
    public $error_message;

    public function __construct() {
        global $wpwaf;

        $this->post_type                = 'wpwaf_topic';
        $this->topic_category_taxonomy  = 'wpwaf_topic_category';
        $this->topic_tag_taxonomy       = 'wpwaf_topic_tag';

        $this->error_message = '';
        add_action( 'init', array( $this, 'create_topics_post_type' ) );
        add_action( 'init', array( $this, 'create_topics_custom_taxonomies' ) );
        add_action( 'add_meta_boxes', array( $this, 'add_topics_meta_boxes' ) );
        add_action( 'save_post', array( $this, 'save_topic_meta_data' ) );
        add_filter( 'post_updated_messages', array( $this, 'generate_topic_messages' ) );
        add_action( 'admin_notices', array( $this, 'topic_admin_notices' ) );
        add_action( 'p2p_init', array( $this, 'join_topics_to_forums' ) );
    }

    public function create_topics_post_type() {
        global $wpwaf;

        $params = array();

        $params['post_type'] = $this->post_type;
        $params['singular_post_name'] = __('Topic','wpwaf');
        $params['plural_post_name'] = __('Topics','wpwaf');
        $params['description'] = __('Topics','wpwaf');
        $params['supported_fields'] = array('title', 'editor');
        $params['capabilities'] = array(
            'edit_post'              => 'edit_wpwaf_topic',
            'read_post'              => 'read_wpwaf_topic',
            'delete_post'            => 'delete_wpwaf_topic',
            'create_posts'           => 'create_wpwaf_topics',
            'edit_posts'             => 'edit_wpwaf_topics',
            'edit_others_posts'      => 'edit_others_wpwaf_topics',
            'publish_posts'          => 'publish_wpwaf_topics',
            'read_private_posts'     => 'read',
            'read'                   => 'read',
            'delete_posts'           => 'delete_wpwaf_topics',
            'delete_private_posts'   => 'delete_private_wpwaf_topics',
            'delete_published_posts' => 'delete_published_wpwaf_topics',
            'delete_others_posts'    => 'delete_others_wpwaf_topics',
            'edit_private_posts'     => 'edit_private_wpwaf_topics',
            'edit_published_posts'   => 'edit_published_wpwaf_topics'
            );

        $wpwaf->model_manager->create_post_type($params);
    }

    public function create_topics_custom_taxonomies() {
        global $wpwaf;

        $params = array();

        $params['category_taxonomy']    = $this->topic_category_taxonomy;
        $params['post_type']            = $this->post_type;

        $params['singular_name']        = __('Topic Category','wpwaf');
        $params['plural_name']          = __('Topic Category','wpwaf');
        $params['hierarchical']         = true;
        $wpwaf->model_manager->create_custom_taxonomies($params);

        $params['category_taxonomy']    = $this->topic_tag_taxonomy;
        $params['post_type']            = $this->post_type;

        $params['singular_name']        = __('Topic Tag','wpwaf');
        $params['plural_name']          = __('Topic Tag','wpwaf');
        $params['capabilities']         = array(
                                                    'manage_terms'      => 'manage_wpwaf_topic_tag',
                                                    'edit_terms'        => 'edit_wpwaf_topic_tag',
                                                    'delete_terms'      => 'delete_wpwaf_topic_tag',
                                                    'assign_terms'      => 'assign_wpwaf_topic_tag'
                                            );
        $params['hierarchical'] = false;

        $wpwaf->model_manager->create_custom_taxonomies($params);

    }

    public function add_topics_meta_boxes() {
        add_meta_box( 'wpwaf-topics-meta', __('Topic Details','wpwaf'), array( $this, 'display_topics_meta_boxes' ), $this->post_type );
    }

    public function display_topics_meta_boxes() {
        global $wpwaf,$post,$template_data,$wpwa_template_loader;

        $data = array();
        $topic = $post;
        $template_data['topic_post_type']      = $this->post_type;
        $template_data['topic_meta_nonce']     = wp_create_nonce('wpwaf-topic-meta');
        $template_data['topic_sticky_status']  = get_post_meta( $topic->ID, '_wpwaf_topic_sticky_status', true );
        $template_data['topic_docs']           = (array) json_decode(get_post_meta( $topic->ID, '_wpwaf_topic_docs', true ));

        ob_start();
        $wpwa_template_loader->get_template_part( 'topic','meta');
        $display = ob_get_clean();
        echo $display;
    }

    public function save_topic_meta_data() {
        global $post,$wpwaf;

        // Verify the nonce value for secure form submission
        if ( isset($_POST['topic_meta_nonce']) && !wp_verify_nonce($_POST['topic_meta_nonce'], 'wpwaf-topic-meta' ) ) {
             return;
        }

        // Check for the autosaving feature of WordPress
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
            return;
        }

        if ( isset($_POST['post_type']) && $this->post_type == $_POST['post_type'] && current_user_can( 'edit_wpwaf_topics', $post->ID ) ) {

            $sticky_status  = isset( $_POST['wpwaf_sticky_status'] ) ? sanitize_text_field( trim($_POST['wpwaf_sticky_status']) ) : '';

            if ( $sticky_status == '0' )  {
                $this->error_message .= __('Sticky status cannot be empty.
', 'wpwaf' );
            }

            if ( !empty( $this->error_message ) ) {

                remove_action( 'save_post', array( $this, 'save_topic_meta_data' ) );

                $post->post_status = 'draft';
                $post->post_title = isset($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : '';
                $post->post_content = isset($_POST['post_content']) ? ($_POST['post_content']) : '';
                wp_update_post( $post );

                add_action( 'save_post', array( $this, 'save_topic_meta_data' ) );

                $this->error_message = __('Topic creation failed.
', 'wpwaf' ) . $this->error_message;
                set_transient( $this->post_type."_error_message_$post->ID", $this->error_message, 60 * 10 );

            } else {

                update_post_meta( $post->ID, '_wpwaf_topic_sticky_status', $sticky_status );

                $topic_docs = isset ($_POST['h_wpwaf_files']) ? $_POST['h_wpwaf_files'] : "";
                $topic_docs = json_encode($topic_docs);
                update_post_meta($post->ID, "_wpwaf_topic_docs", $topic_docs);
            }
        } else {
            return;
        }
    }

    public function generate_topic_messages( $messages ) {
        global $wpwaf;

        $params = array();
        $params['post_type'] = $this->post_type;
        $params['singular_name'] = __('Topic','wpwaf');
        $params['plural_name'] = __('Topics','wpwaf');

        $messages = $wpwaf->model_manager->generate_messages($messages,$params);
        return $messages;

    }

    public function topic_admin_notices(){
        global $post;
        $this->temp_error_message = get_transient( $this->post_type."_error_message_$post->ID" );
        delete_transient( $this->post_type."_error_message_$post->ID" );

        if (!( $this->temp_error_message)){
            return;
        }

        $message = '

';
        $message .= $this->temp_error_message;
        $message .= '

';

        echo $message;
        remove_action( 'admin_notices', array($this,'topic_admin_notices') );
    }

    public function join_topics_to_forums() {
        global $wpwaf;
        p2p_register_connection_type( array(
                'name'  => 'topics_to_forums',
                'from'  => $this->post_type,
                'to'    => $wpwaf->forum->post_type
                ) );
    }

}

?>


text:
package com.twitter.io

import com.twitter.util.StdBenchAnnotations
import java.nio.ByteBuffer
import org.openjdk.jmh.annotations.{Benchmark, Param, Scope, State}

// run via:
// ./sbt 'project util-benchmark' 'jmh:run BufConcatBenchmark'
@State(Scope.Benchmark)
class BufConcatBenchmark extends StdBenchAnnotations {

  @Param(Array("1", "5", "10", "20", "40"))
  var concats: Int = _

  val bytes = Array[Byte](1, 2, 3, 4)

  val byteArrayBuf = Buf.ByteArray.Owned(bytes)
  val byteBufferBuf = Buf.ByteBuffer.Owned(ByteBuffer.wrap(bytes))
  val compositeBuf = byteArrayBuf.slice(0, bytes.length / 2)
    .concat(byteArrayBuf.slice(bytes.length / 2, bytes.length))

  private[this] def concatN(n: Int, buf: Buf): Buf = {
    var acc = buf
    var i = 0
    while (i < n) {
      i += 1
      acc = acc.concat(buf)
    }

    acc
  }

  @Benchmark
  def concatByteBufferBuf(): Buf =
    concatN(concats, byteBufferBuf)

  @Benchmark
  def concatByteArrayBuf(): Buf =
    concatN(concats, byteArrayBuf)

  @Benchmark
  def concatCompositeBuf(): Buf =
    concatN(concats, compositeBuf)
}


text:
'use strict';

// mime files data
var db = require('mime-db');

// Merge objects
//
function assign(obj /*from1, from2, from3, ...*/) {
  var sources = Array.prototype.slice.call(arguments, 1);

  sources.forEach(function (source) {
    Object.keys(source).forEach(function (key) {
      obj[key] = source[key];
    });
  });

  return obj;
}

// leaves only extension from the given string
//   normalize('foo/bar.js')  // -> '.js'
//   normalize('bar.js')      // -> '.js'
//   normalize('.js')         // -> '.js'
//   normalize('js')          // -> '.js'
function normalize(path) {
  // edge case: '/txt' & '\txt' are not resolveable
  if (/[\\/][^\\/.]+$/.test(path)) { return ''; }

  return '.' + path.replace(/.*[\.\/\\]/, '').toLowerCase();
}

// Remove charset/types/spaces, convenent for external data check
// " tExt/htMl ; charset=UTF-8 ; type=foo " -> "text/html"
function clearMime(mimeType) {
  if (!mimeType || (String(mimeType) !== mimeType)) { return ''; }
  return mimeType.split(';')[0].trim().toLowerCase();
}

/**
 * class Mimoza
 **/

/**
 *  new Mimoza([options])
 *
 *  Initiates new instance of Mimoza.
 *
 *  ##### Options
 *
 *  - **defaultType** _(String):_ Default mime type used as last-resort
 *    for [[Mimoza#getMimeType]]. By default: `undefined`.
 *  - **preloaded** _(Boolean):_ Init instance with default mime rules
 **/
var Mimoza = module.exports = function Mimoza(options) {
  options = options || {};

  // Map of `extension -> mimeType` pairs.
  Object.defineProperty(this, 'types',          { value: Object.create(null) });

  // Map of `mimeType -> extensions` pairs.
  Object.defineProperty(this, 'extensions',     { value: Object.create(null) });

  // Used as last-resort for [[Mimoza#getMimeType]].
  Object.defineProperty(this, 'defaultType',    { value: options.defaultType });

  if (options.preloaded) {
    Object.keys(db).forEach(function (mime) {
      var val = db[mime];

      if (val.extensions) {
        this.register(mime, val.extensions);
      }
    }, this);
  }
};

/**
 *  Mimoza#clone() -> Object
 *
 *  Creates copy of current Mimoza instanse
 **/
Mimoza.prototype.clone = function clone() {
  var m = new Mimoza({ defaultType: this.defaultType });

  assign(m.types, this.types);
  assign(m.extensions, this.extensions);

  return m;
};

/**
 *  Mimoza#register(mimeType, extensions[, overrideDefault = false]) -> Void
 *  - mimeType (String):
 *  - extensions (String|Array):
 *  - overrideDefault (Boolean):
 *
 *  Register given `extensions` as representatives of `mimeType` and register
 *  first element of `extensions` as default extension for the `mimeType`.
 *
 *
 *  ##### Example
 *
 *  ```javascript
 *  mime.register('audio/ogg', ['oga', 'ogg', 'spx']);
 *
 *  mime.getMimeType('.oga');       // -> 'audio/ogg'
 *  mime.getMimeType('.ogg');       // -> 'audio/ogg'
 *  mime.getExtension('audio/ogg'); // -> '.oga'
 *  ```
 *
 *  ##### Overriding default extension
 *
 *  `mimeType -> extension` is set only once, if you wnt to override it,
 *  pass `overrideDefault` flag as true. See example below:
 *
 *  ```javascript
 *  mime.register('audio/ogg', ['oga']);
 *  mime.getExtension('audio/ogg');
 *  // -> '.oga'
 *
 *  mime.register('audio/ogg', ['spx']);
 *  mime.getExtension('audio/ogg');
 *  // -> '.oga'
 *
 *  mime.register('audio/ogg', ['ogg'], true);
 *  mime.getExtension('audio/ogg');
 *  // -> '.ogg'
 *  ```
 **/
Mimoza.prototype.register = function register(mimeType, extensions, overrideDefault) {
  extensions = Array.isArray(extensions) ? extensions : [ extensions ];

  // pollute `extension -> mimeType` map
  extensions.forEach(function (ext) {
    this.types[normalize(ext)] = mimeType;
  }, this);

  // use case insensitive mime types for extention resolve
  if (overrideDefault || typeof this.extensions[mimeType.toLowerCase()] === 'undefined') {
    this.extensions[mimeType.toLowerCase()] = normalize(extensions[0]);
  }
};

/**
 *  Mimoza#getMimeType(path[, fallback]) -> String
 *
 *  Lookup a mime type based on extension
 **/
Mimoza.prototype.getMimeType = function getMimeType(path, fallback) {
  return this.types[normalize(path)] || fallback || this.defaultType;
};

/**
 *  Mimoza#getExtension(mimeType) -> String
 *
 *  Return file extension associated with a mime type.
 **/
Mimoza.prototype.getExtension = function getExtension(mimeType) {
  return this.extensions[clearMime(mimeType)];
};

// Returns whenever an asset is text or not
var TEXT_MIME_RE = new RegExp([
  '^text/',
  '/json$',
  '/javascript$'
].join('|'));

/**
 *  Mimoza#isText(mimeType) -> Boolean
 *
 *  Check if mime type provides text content. Can be used to add encoding.
 **/
Mimoza.prototype.isText = function isText(mimeType) {
  return TEXT_MIME_RE.test(clearMime(mimeType));
};

////////////////////////////////////////////////////////////////////////////////
//
// Public methods to work with module without creating new instance, if default
// configs are ok for you.
//

// builtin instance of mimoza
var builtin = new Mimoza({ preloaded: true });

/**
 *  Mimoza.getMimeType(path, fallback) -> String
 *
 *  Proxy to [[Mimoza#getMimeType]] of internal, built-in instance of [[Mimoza]]
 *  filled with some default types.
 **/
Mimoza.getMimeType = function _getMimeType(path, fallback) {
  return builtin.getMimeType(path, fallback);
};

/**
 *  Mimoza.getExtension(mimeType) -> String
 *
 *  Proxy to [[Mimoza#getExtension]] of internal, built-in instance of [[Mimoza]]
 *  filled with some default types.
 **/
Mimoza.getExtension = function _getExtension(mimeType) {
  return builtin.getExtension(mimeType);
};

/**
 *  Mimoza.isText(mimeType) -> Boolean
 *
 *  Proxy to [[Mimoza#isText]] of internal, built-in instance
 *  of [[Mimoza]].
 **/
Mimoza.isText = function _isText(mimeType) {
  return builtin.isText(mimeType);
};


text:
package org.roaringbitmap.bsi;

import java.io.Serializable;

/**
 * A generic class for pairs.
 * Copied from org.apache.hadoop.hbase.util.Pair
 *
 * @param <T1>
 * @param <T2>
 */
public class Pair<T1, T2> implements Serializable {
  private static final long serialVersionUID = -3986244606585552569L;

  protected T1 left = null;
  protected T2 right = null;

  /**
   * Default constructor.
   */
  public Pair() {
  }

  /**
   * Constructor
   *
   * @param a operand
   * @param b operand
   */
  public Pair(T1 a, T2 b) {
    this.left = a;
    this.right = b;
  }

  /**
   * Constructs a new pair, inferring the type via the passed arguments
   *
   * @param <T1> type for left
   * @param <T2> type for right
   * @param a  left element
   * @param b  right element
   * @return a new pair containing the passed arguments
   */
  public static <T1, T2> Pair<T1, T2> newPair(T1 a, T2 b) {
    return new Pair<T1, T2>(a, b);
  }

  private static boolean equals(Object x, Object y) {
    return (x == null && y == null) || (x != null && x.equals(y));
  }

  /**
   * Return the left element stored in the pair.
   *
   * @return T1
   */
  public T1 getLeft() {
    return left;
  }

  public T1 getKey() {
    return left;
  }

  /**
   * Replace the left element of the pair.
   *
   * @param a operand
   */
  public void setFirst(T1 a) {
    this.left = a;
  }

  /**
   * Return the right element stored in the pair.
   *
   * @return T2
   */
  public T2 getRight() {
    return right;
  }

  public T2 getValue() {
    return right;
  }

  /**
   * Replace the right element of the pair.
   *
   * @param b operand
   */
  public void setSecond(T2 b) {
    this.right = b;
  }

  @Override
  @SuppressWarnings("rawtypes")
  public boolean equals(Object other) {
    return other instanceof Pair && equals(left, ((Pair) other).left) && equals(right, ((Pair) other).right);
  }

  @Override
  public int hashCode() {
    if (left == null)
      return (right == null) ? 0 : right.hashCode() + 1;
    else if (right == null)
      return left.hashCode() + 2;
    else
      return left.hashCode() * 17 + right.hashCode();
  }

  @Override
  public String toString() {
    return "{" + getLeft() + "," + getRight() + "}";
  }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe GwtRpc::BaseExtensions::Boolean do
  describe ".gwt_deserialize" do
    it "0 should be false" do
      client = GwtRpc::Client.new
      reader = GwtRpc::Response::Reader.new(client, '[0,[],0,5]')
      GwtRpc::BaseExtensions::Boolean.gwt_deserialize(reader).should == false
    end
    it "1 should be true" do
      client = GwtRpc::Client.new
      reader = GwtRpc::Response::Reader.new(client, '[0,[],0,5]')
      GwtRpc::BaseExtensions::Boolean.gwt_deserialize(reader).should == false
    end
  end
end


text:
#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_SMART_PTR)
#include <boost/detail/lightweight_test.hpp>
#include <boost/smart_ptr/make_unique.hpp>

class type {
public:
    static unsigned instances;

    type() {
        if (instances == 5) {
            throw true;
        }
        ++instances;
    }

    ~type() {
        --instances;
    }

private:
    type(const type&);
    type& operator=(const type&);
};

unsigned type::instances = 0;

int main()
{
    BOOST_TEST(type::instances == 0);
    try {
        boost::make_unique<type[]>(6);
        BOOST_ERROR("make_unique did not throw");
    } catch (...) {
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    try {
        boost::make_unique<type[][2]>(3);
        BOOST_ERROR("make_unique did not throw");
    } catch (...) {
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    try {
        boost::make_unique_noinit<type[]>(6);
        BOOST_ERROR("make_unique_noinit did not throw");
    } catch (...) {
        BOOST_TEST(type::instances == 0);
    }
    BOOST_TEST(type::instances == 0);
    try {
        boost::make_unique_noinit<type[][2]>(3);
        BOOST_ERROR("make_unique_noinit did not throw");
    } catch (...) {
        BOOST_TEST(type::instances == 0);
    }
    return boost::report_errors();
}
#else
int main()
{
    return 0;
}
#endif


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DotNetty.Transport.Channels.Pool
{
    using System;
    using System.Collections.Concurrent;
    using System.Diagnostics.Contracts;
    using System.Threading.Tasks;
    using DotNetty.Common.Concurrency;
    using DotNetty.Common.Internal;
    using DotNetty.Common.Utilities;
    using DotNetty.Transport.Bootstrapping;

    /**
 * Simple {@link ChannelPool} implementation which will create new {@link Channel}s if someone tries to acquire
 * a {@link Channel} but none is in the pool atm. No limit on the maximal concurrent {@link Channel}s is enforced.
 *
 * This implementation uses LIFO order for {@link Channel}s in the {@link ChannelPool}.
 *
 */
    public class SimpleChannelPool : IChannelPool
    {
        public static readonly AttributeKey<SimpleChannelPool> PoolKey = AttributeKey<SimpleChannelPool>.NewInstance("channelPool");

        static readonly InvalidOperationException FullException = new InvalidOperationException("ChannelPool full");

        readonly IQueue<IChannel> store;

        /**
         * Creates a new instance using the {@link IChannelHealthChecker#ACTIVE}.
         *
         * @param bootstrap         the {@link Bootstrap} that is used for connections
         * @param handler           the {@link IChannelPoolHandler} that will be notified for the different pool actions
         */
        public SimpleChannelPool(Bootstrap bootstrap, IChannelPoolHandler handler)
            : this(bootstrap, handler, ChannelActiveHealthChecker.Instance)
        {
        }

        /**
         * Creates a new instance.
         *
         * @param bootstrap         the {@link Bootstrap} that is used for connections
         * @param handler           the {@link IChannelPoolHandler} that will be notified for the different pool actions
         * @param healthCheck       the {@link IChannelHealthChecker} that will be used to check if a {@link Channel} is
         *                          still healthy when obtain from the {@link ChannelPool}
         */
        public SimpleChannelPool(Bootstrap bootstrap, IChannelPoolHandler handler, IChannelHealthChecker healthChecker)
            : this(bootstrap, handler, healthChecker, true)
        {
        }

        /**
         * Creates a new instance.
         *
         * @param bootstrap          the {@link Bootstrap} that is used for connections
         * @param handler            the {@link IChannelPoolHandler} that will be notified for the different pool actions
         * @param healthCheck        the {@link IChannelHealthChecker} that will be used to check if a {@link Channel} is
         *                           still healthy when obtain from the {@link ChannelPool}
         * @param releaseHealthCheck will check channel health before offering back if this parameter set to {@code true};
         *                           otherwise, channel health is only checked at acquisition time
         */
        public SimpleChannelPool(Bootstrap bootstrap, IChannelPoolHandler handler, IChannelHealthChecker healthChecker, bool releaseHealthCheck)
            : this(bootstrap, handler, healthChecker, releaseHealthCheck, true)
        {
        }

        /**
         * Creates a new instance.
         *
         * @param bootstrap          the {@link Bootstrap} that is used for connections
         * @param handler            the {@link IChannelPoolHandler} that will be notified for the different pool actions
         * @param healthCheck        the {@link IChannelHealthChecker} that will be used to check if a {@link Channel} is
         *                           still healthy when obtain from the {@link ChannelPool}
         * @param releaseHealthCheck will check channel health before offering back if this parameter set to {@code true};
         *                           otherwise, channel health is only checked at acquisition time
         * @param lastRecentUsed    {@code true} {@link Channel} selection will be LIFO, if {@code false} FIFO.
         */
        public SimpleChannelPool(Bootstrap bootstrap, IChannelPoolHandler handler, IChannelHealthChecker healthChecker, bool releaseHealthCheck, bool lastRecentUsed)
        {
            Contract.Requires(handler != null);
            Contract.Requires(healthChecker != null);
            Contract.Requires(bootstrap != null);

            this.Handler = handler;
            this.HealthChecker = healthChecker;
            this.ReleaseHealthCheck = releaseHealthCheck;

            // Clone the original Bootstrap as we want to set our own handler
            this.Bootstrap = bootstrap.Clone();
            this.Bootstrap.Handler(new ActionChannelInitializer<IChannel>(this.OnChannelInitializing));
            this.store =
                lastRecentUsed
                    ? (IQueue<IChannel>)new CompatibleConcurrentStack<IChannel>()
                    : new CompatibleConcurrentQueue<IChannel>();
        }

        void OnChannelInitializing(IChannel channel)
        {
            Contract.Assert(channel.EventLoop.InEventLoop);
            this.Handler.ChannelCreated(channel);
        }

        /**
         * Returns the {@link Bootstrap} this pool will use to open new connections.
         *
         * @return the {@link Bootstrap} this pool will use to open new connections
         */
        internal Bootstrap Bootstrap { get; }

        /**
         * Returns the {@link IChannelPoolHandler} that will be notified for the different pool actions.
         *
         * @return the {@link IChannelPoolHandler} that will be notified for the different pool actions
         */
        internal IChannelPoolHandler Handler { get; }

        /**
         * Returns the {@link IChannelHealthChecker} that will be used to check if a {@link Channel} is healthy.
         *
         * @return the {@link IChannelHealthChecker} that will be used to check if a {@link Channel} is healthy
         */
        internal IChannelHealthChecker HealthChecker { get; }

        /**
         * Indicates whether this pool will check the health of channels before offering them back into the pool.
         *
         * @return {@code true} if this pool will check the health of channels before offering them back into the pool, or
         * {@code false} if channel health is only checked at acquisition time
         */
        internal bool ReleaseHealthCheck { get; }

        public virtual ValueTask<IChannel> AcquireAsync()
        {
            if (!this.TryPollChannel(out IChannel channel))
            {
                Bootstrap bs = this.Bootstrap.Clone();
                bs.Attribute(PoolKey, this);
                return new ValueTask<IChannel>(this.ConnectChannel(bs));
            }

            IEventLoop eventLoop = channel.EventLoop;
            if (eventLoop.InEventLoop)
            {
                return this.DoHealthCheck(channel);
            }
            else
            {
                var completionSource = new TaskCompletionSource<IChannel>();
                eventLoop.Execute(this.DoHealthCheck, channel, completionSource);
                return new ValueTask<IChannel>(completionSource.Task);
            }
        }

        async void DoHealthCheck(object channel, object state)
        {
            var promise = state as TaskCompletionSource<IChannel>;
            try
            {
                var result = await this.DoHealthCheck((IChannel)channel);
                promise.TrySetResult(result);
            }
            catch (Exception ex)
            {
                promise.TrySetException(ex);
            }
        }

        async ValueTask<IChannel> DoHealthCheck(IChannel channel)
        {
            Contract.Assert(channel.EventLoop.InEventLoop);
            try
            {
                if (await this.HealthChecker.IsHealthyAsync(channel))
                {
                    try
                    {
                        channel.GetAttribute(PoolKey).Set(this);
                        this.Handler.ChannelAcquired(channel);
                        return channel;
                    }
                    catch (Exception)
                    {
                        CloseChannel(channel);
                        throw;
                    }
                }
                else
                {
                    CloseChannel(channel);
                    return await this.AcquireAsync();
                }
            }
            catch
            {
                CloseChannel(channel);
                return await this.AcquireAsync();
            }
        }

        /**
         * Bootstrap a new {@link Channel}. The default implementation uses {@link Bootstrap#connect()}, sub-classes may
         * override this.
         * <p>
         * The {@link Bootstrap} that is passed in here is cloned via {@link Bootstrap#clone()}, so it is safe to modify.
         */
        protected virtual Task<IChannel> ConnectChannel(Bootstrap bs) => bs.ConnectAsync();

        public virtual async ValueTask<bool> ReleaseAsync(IChannel channel)
        {
            Contract.Requires(channel != null);
            try
            {
                IEventLoop loop = channel.EventLoop;
                if (loop.InEventLoop)
                {
                    return await this.DoReleaseChannel(channel);
                }
                else
                {
                    var promise = new TaskCompletionSource<bool>();
                    loop.Execute(this.DoReleaseChannel, channel, promise);
                    return await promise.Task;
                }
            }
            catch (Exception)
            {
                CloseChannel(channel);
                throw;
            }
        }

        async void DoReleaseChannel(object channel, object state)
        {
            var promise = state as TaskCompletionSource<bool>;
            try
            {
                var result = await this.DoReleaseChannel((IChannel)channel);
                promise.TrySetResult(result);
            }
            catch (Exception ex)
            {
                promise.TrySetException(ex);
            }
        }

        async ValueTask<bool> DoReleaseChannel(IChannel channel)
        {
            Contract.Assert(channel.EventLoop.InEventLoop);

            // Remove the POOL_KEY attribute from the Channel and check if it was acquired from this pool, if not fail.
            if (channel.GetAttribute(PoolKey).GetAndSet(null) != this)
            {
                CloseChannel(channel);
                // Better include a stacktrace here as this is an user error.
                throw new ArgumentException($"Channel {channel} was not acquired from this ChannelPool");
            }
            else
            {
                try
                {
                    if (this.ReleaseHealthCheck)
                    {
                        return await this.DoHealthCheckOnRelease(channel);
                    }
                    else
                    {
                        this.ReleaseAndOffer(channel);
                        return true;
                    }
                }
                catch
                {
                    CloseChannel(channel);
                    throw;
                }
            }
        }

        /**
         * Adds the channel back to the pool only if the channel is healthy.
         * @param channel the channel to put back to the pool
         * @param promise offer operation promise.
         * @param future the future that contains information fif channel is healthy or not.
         * @throws Exception in case when failed to notify handler about release operation.
         */
        async ValueTask<bool> DoHealthCheckOnRelease(IChannel channel)
        {
            if (await this.HealthChecker.IsHealthyAsync(channel))
            {
                //channel turns out to be healthy, offering and releasing it.
                this.ReleaseAndOffer(channel);
                return true;
            }
            else
            {
                //channel not healthy, just releasing it.
                this.Handler.ChannelReleased(channel);
                return false;
            }
        }

        void ReleaseAndOffer(IChannel channel)
        {
            if (this.TryOfferChannel(channel))
            {
                this.Handler.ChannelReleased(channel);
            }
            else
            {
                CloseChannel(channel);
                throw FullException;
            }
        }

        static void CloseChannel(IChannel channel)
        {
            channel.GetAttribute(PoolKey).GetAndSet(null);
            channel.CloseAsync();
        }

        /**
         * Poll a {@link Channel} out of the internal storage to reuse it. This will return {@code null} if no
         * {@link Channel} is ready to be reused.
         *
         * Sub-classes may override {@link #pollChannel()} and {@link #offerChannel(Channel)}. Be aware that
         * implementations of these methods needs to be thread-safe!
         */
        protected virtual bool TryPollChannel(out IChannel channel) => this.store.TryDequeue(out channel);

        /**
         * Offer a {@link Channel} back to the internal storage. This will return {@code true} if the {@link Channel}
         * could be added, {@code false} otherwise.
         *
         * Sub-classes may override {@link #pollChannel()} and {@link #offerChannel(Channel)}. Be aware that
         * implementations of these methods needs to be thread-safe!
         */
        protected virtual bool TryOfferChannel(IChannel channel) => this.store.TryEnqueue(channel);

        public virtual void Dispose()
        {
            while (this.TryPollChannel(out IChannel channel))
            {
                channel.CloseAsync();
            }
        }

        class CompatibleConcurrentStack<T> : ConcurrentStack<T>, IQueue<T>
        {
            public bool TryEnqueue(T item)
            {
                this.Push(item);
                return true;
            }

            public bool TryDequeue(out T item) => this.TryPop(out item);
        }
    }
}


text:
package debrepo.teamcity.service;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import debrepo.teamcity.archive.DebFileReaderFactory;
import debrepo.teamcity.entity.DebPackageEntity;
import debrepo.teamcity.entity.DebRepositoryBuildTypeConfig;
import debrepo.teamcity.entity.DebRepositoryBuildTypeConfig.Filter;
import debrepo.teamcity.entity.DebRepositoryConfiguration;
import debrepo.teamcity.entity.DebRepositoryConfigurationJaxImpl;
import debrepo.teamcity.entity.helper.PluginDataResolver;
import jetbrains.buildServer.serverSide.SBuild;
import jetbrains.buildServer.serverSide.SBuildType;
import jetbrains.buildServer.serverSide.ServerPaths;
import jetbrains.buildServer.serverSide.artifacts.BuildArtifact;
import jetbrains.buildServer.serverSide.artifacts.BuildArtifactHolder;
import jetbrains.buildServer.serverSide.artifacts.BuildArtifacts;
import jetbrains.buildServer.util.PluralUtil;

public class DebRepositoryBuildArtifactsPublisherImplTest {
	@Mock
	DebRepositoryManager debRepositoryManager;

	@Mock
	DebRepositoryConfigurationManager debRepositoryConfigManager;

	@Mock
	PluginDataResolver pluginDataResolver;

	@Mock
	ServerPaths serverPaths;

	@Mock
	SBuild build;

	@Mock
	SBuildType buildType;

	BuildArtifacts buildArtifacts;

	DebFileReaderFactory debFileReaderFactory;
	DebRepositoryConfiguration config;

	Set<DebRepositoryConfiguration> configs = new TreeSet<>();

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
		when(pluginDataResolver.getPluginTempFileDirectory()).thenReturn("target/temp");
		debFileReaderFactory = new DebFileReaderFactory(pluginDataResolver, serverPaths);
		config = new DebRepositoryConfigurationJaxImpl("project01", "MyTestRepoName");
		config.addBuildType(new DebRepositoryBuildTypeConfig("bt01", "potato", "main", ".+\\.deb").af(new Filter(".+\\.deb", "whezzy", "main")));
		configs.add(config);
		when(buildType.getBuildTypeId()).thenReturn("bt01");
		when(build.getBuildType()).thenReturn(buildType);
		when(build.isArtifactsExists()).thenReturn(true);
		when(build.getBuildTypeId()).thenReturn("bt01");
		when(debRepositoryConfigManager.findConfigurationsForBuildType(anyString())).thenReturn(configs);
	}

	@Test
	public void testAddArtifactsToRepositories() throws NonExistantRepositoryException {

		DebRepositoryBuildArtifactsPublisherImpl publisher = new DebRepositoryBuildArtifactsPublisherImpl(debRepositoryManager, debRepositoryConfigManager, debFileReaderFactory);
		buildArtifacts = new MyBuildArtifacts();
		publisher.addArtifactsToRepositories(build, buildArtifacts);

		verify(debRepositoryManager, times(1)).addBuildPackages(eq(config), any(List.class));
	}

	static class MyBuildArtifacts implements BuildArtifacts {

		List<BuildArtifact> artifacts = new ArrayList<>();

		@Override
		public BuildArtifact getArtifact(String relativePath) {
			return null;
		}

		@Override
		public BuildArtifactHolder findArtifact(String relativePath) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public BuildArtifact getRootArtifact() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public boolean isAvailable() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void iterateArtifacts(BuildArtifactsProcessor processor) {
			processor.processBuildArtifact(new MyBuildArtifact("directory/file.deb", "file.deb"));
			processor.processBuildArtifact(new MyBuildArtifact("directory/filename2.deb", "filename2.deb"));

		}

	}

	static class MyBuildArtifact implements BuildArtifact {

		String relativePath;
		String fileName;

		public MyBuildArtifact(String path, String file) {
			this.relativePath = path;
			this.fileName = file;
		}

		@Override
		public String getRelativePath() {
			return this.relativePath;
		}

		@Override
		public String getName() {
			return this.fileName;
		}

		@Override
		public boolean isDirectory() {
			return false;
		}

		@Override
		public boolean isArchive() {
			return false;
		}

		@Override
		public boolean isFile() {
			return true;
		}

		@Override
		public boolean isContainer() {
			return false;
		}

		@Override
		public long getSize() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public long getTimestamp() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public InputStream getInputStream() throws IOException {
			return null;
		}

		@Override
		public Collection<BuildArtifact> getChildren() {
			return null;
		}

	}
}


text:
PKGBASE=base-htmldoc-share
TINY_VERSION=0

.include "../../../mk/bsd.syspkg.mk"


text:
package org.springframework.cloud.stream.binder;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.DatatypeConverter;

import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.support.json.Jackson2JsonObjectMapper;
import org.springframework.messaging.Message;

/**
 * Encodes requested headers into payload with format
 * {@code 0xff, n(1), [ [lenHdr(1), hdr, lenValue(4), value] ... ]}.
 * The 0xff indicates this new format; n is number of headers (max 255); for
 * each header, the name length (1 byte) is followed by the name, followed by
 * the value length (int) followed by the value (json).
 * <p>
 * Previously, there was no leading 0xff; the value length was 1 byte and only
 * String header values were supported (no JSON conversion).
 *
 * @author Eric Bottard
 * @author Gary Russell
 */
public class EmbeddedHeadersMessageConverter {

	private final Jackson2JsonObjectMapper objectMapper = new Jackson2JsonObjectMapper();

	public static String decodeExceptionMessage(Message<?> requestMessage) {
		return "Could not convert message: " + DatatypeConverter.printHexBinary((byte[]) requestMessage.getPayload());
	}

	/**
	 * Return a new message where some of the original headers of {@code original}
	 * have been embedded into the new message payload.
	 */
	public byte[] embedHeaders(MessageValues original, String... headers) throws Exception {
		byte[][] headerValues = new byte[headers.length][];
		int n = 0;
		int headerCount = 0;
		int headersLength = 0;
		for (String header : headers) {
			Object value = original.get(header) == null ? null
					: original.get(header);
			if (value != null) {
				String json = this.objectMapper.toJson(value);
				headerValues[n++] = json.getBytes("UTF-8");
				headerCount++;
				headersLength += header.length() + json.length();
			}
			else {
				headerValues[n++] = null;
			}
		}
		// 0xff, n(1), [ [lenHdr(1), hdr, lenValue(4), value] ... ]
		byte[] newPayload = new byte[((byte[])original.getPayload()).length + headersLength + headerCount * 5 + 2];
		ByteBuffer byteBuffer = ByteBuffer.wrap(newPayload);
		byteBuffer.put((byte) 0xff); // signal new format
		byteBuffer.put((byte) headerCount);
		for (int i = 0; i < headers.length; i++) {
			if (headerValues[i] != null) {
				byteBuffer.put((byte) headers[i].length());
				byteBuffer.put(headers[i].getBytes("UTF-8"));
				byteBuffer.putInt(headerValues[i].length);
				byteBuffer.put(headerValues[i]);
			}
		}

		byteBuffer.put((byte[])original.getPayload());
		return byteBuffer.array();
	}

	/**
	 * Return a message where headers, that were originally embedded into the payload, have been promoted
	 * back to actual headers. The new payload is now the original payload.
	 *
	 * @param message the message to extract headers
	 * @param copyRequestHeaders boolean value to specify if original headers should be copied
	 */
	public MessageValues extractHeaders(Message<byte[]> message, boolean copyRequestHeaders) throws Exception {
		byte[] bytes = message.getPayload();
		ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
		int headerCount = byteBuffer.get() & 0xff;
		if (headerCount < 255) {
			return oldExtractHeaders(byteBuffer, bytes, headerCount, message, copyRequestHeaders);
		}
		else {
			headerCount = byteBuffer.get() & 0xff;
			Map<String, Object> headers = new HashMap<String, Object>();
			for (int i = 0; i < headerCount; i++) {
				int len = byteBuffer.get() & 0xff;
				String headerName = new String(bytes, byteBuffer.position(), len, "UTF-8");
				byteBuffer.position(byteBuffer.position() + len);
				len = byteBuffer.getInt();
				String headerValue = new String(bytes, byteBuffer.position(), len, "UTF-8");
				Object headerContent = this.objectMapper.fromJson(headerValue, Object.class);
				headers.put(headerName, headerContent);
				byteBuffer.position(byteBuffer.position() + len);
			}
			byte[] newPayload = new byte[byteBuffer.remaining()];
			byteBuffer.get(newPayload);
			return buildMessageValues(message, newPayload, headers, copyRequestHeaders);
		}
	}

	private MessageValues oldExtractHeaders(ByteBuffer byteBuffer, byte[] bytes, int headerCount,
			Message<byte[]> message, boolean copyRequestHeaders)
			throws UnsupportedEncodingException {
		Map<String, Object> headers = new HashMap<String, Object>();
		for (int i = 0; i < headerCount; i++) {
			int len = byteBuffer.get();
			String headerName = new String(bytes, byteBuffer.position(), len, "UTF-8");
			byteBuffer.position(byteBuffer.position() + len);
			len = byteBuffer.get() & 0xff;
			String headerValue = new String(bytes, byteBuffer.position(), len, "UTF-8");
			byteBuffer.position(byteBuffer.position() + len);
			if (IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER.equals(headerName)
					|| IntegrationMessageHeaderAccessor.SEQUENCE_SIZE.equals(headerName)) {
				headers.put(headerName, Integer.parseInt(headerValue));
			}
			else {
				headers.put(headerName, headerValue);
			}
		}
		byte[] newPayload = new byte[byteBuffer.remaining()];
		byteBuffer.get(newPayload);
		return buildMessageValues(message, newPayload, headers, copyRequestHeaders);
	}

	private MessageValues buildMessageValues(Message<byte[]> message, byte[] payload, Map<String, Object> headers,
			boolean copyRequestHeaders) {
		MessageValues messageValues = new MessageValues(payload, headers);
		if (copyRequestHeaders) {
			messageValues.copyHeadersIfAbsent(message.getHeaders());
		}
		return messageValues;
	}

}


text:
package io.cattle.platform.api.storagepool;

import io.cattle.platform.api.common.CachedOutputFilter;
import io.cattle.platform.core.constants.StoragePoolConstants;
import io.cattle.platform.core.dao.StoragePoolDao;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.context.ApiContext;
import io.github.ibuildthecloud.gdapi.id.IdFormatter;
import io.github.ibuildthecloud.gdapi.model.Resource;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StoragePoolOutputFilter extends CachedOutputFilter<Map<Long, Map<String, Object>>> {

    StoragePoolDao storagePoolDao;

    public StoragePoolOutputFilter(StoragePoolDao storagePoolDao) {
        super();
        this.storagePoolDao = storagePoolDao;
    }

    @Override
    public Resource filter(ApiRequest request, Object original, Resource converted) {
        if (original instanceof StoragePool) {
            Map<Long, Map<String, Object>> data = getCached(request);
            if (data == null) {
                return converted;
            }
            Map<String, Object> fields = data.get(((StoragePool) original).getId());
            if (fields != null) {
                converted.getFields().putAll(fields);
            }
        }
        return converted;
    }

    @Override
    protected Map<Long, Map<String, Object>> newObject(ApiRequest apiRequest) {
        Map<Long, Map<String, Object>> allFields = new HashMap<>();
        IdFormatter idF = ApiContext.getContext().getIdFormatter();
        List<Long> ids = getIds(apiRequest);
        Map<Long, List<Object>> hosts = storagePoolDao.findHostsForPools(ids, idF);
        Map<Long, List<Object>> volumes = storagePoolDao.findVolumesForPools(ids, idF);

        for (Map.Entry<Long, List<Object>> entry : hosts.entrySet()) {
            allFields.put(entry.getKey(), CollectionUtils.asMap(StoragePoolConstants.FIELD_HOST_IDS, entry.getValue()));
        }

        for (Map.Entry<Long, List<Object>> entry : volumes.entrySet()) {
            Map<String, Object> fields = allFields.get(entry.getKey());
            if (fields == null) {
                fields = new HashMap<>();
                allFields.put(entry.getKey(), fields);
            }
            fields.put(StoragePoolConstants.FIELD_VOLUME_IDS, entry.getValue());
        }

        return allFields;
    }

    @Override
    protected Long getId(Object obj) {
        if (obj instanceof StoragePool) {
            return ((StoragePool) obj).getId();
        }
        return null;
    }

}


text:
Example of a kubernets based deployment

# Application
A scala play framework application that uses postgres as its datastore.

# Kubernetes
Uses version 1.0 of kubernetes.


text:
'use strict';

angular.module('popcode-kit.demo.auth', [
    'popcode-kit.auth',
    'ui.router',
    'ui.bootstrap'
])
    .constant('Settings', {
        apiUrl: 'http://192.168.200.211/api/',
        apiBaseUrl: 'http://192.168.200.211/'
    })
    .controller('HeaderCtrl', function($scope, $state, PCAuth){
        $scope.logout = function(){
            PCAuth.logout()
                .then(function(){
                    alert('Logout success.');
                    $state.go('login');
                });
        };
    })
    .controller('MainCtrl', function($scope, PCUser, PCAuth, $resource, Settings, $q, $uibModal){
        $scope.users = PCUser.index();

        PCAuth.me.then(function(me){
            $scope.me = me;
            console.log('Me', $scope.me);
            // console.log('Has role 1?', $scope.me.hasRole(1));
            // console.log('Has role 2?', $scope.me.hasRole(2));
            // console.log('Has role 1|2?', $scope.me.hasRole([1,2]));
            // console.log('Has role 3|4?', $scope.me.hasRole([3,4]));
        });

        var confirmStuff = function(text){
            return $uibModal.open({
                templateUrl: '/confirm.html',
                controller: function($scope){
                    $scope.text = text;
                },
                controllerAs: '$ctrl',
                resolve: {
                    text: function(){return text;}
                }
            }).result;
        };

        $scope.delete = function(user){
            confirmStuff('Are you sure?').then(function(){
                PCUser.delete(user, $scope.users);
            });
        };

        $scope.save = function($form){
            PCUser.save($scope.user, $form)
                .then(function(result){
                    $scope.user = {};
                })
                .catch(function(response){
                    console.log('b', $form);
                });
        };

        $scope.edit = function(user){
            $scope.user = angular.copy(user);
        };

    })
    .controller('LoginCtrl', function($scope, PCAuth){
        $scope.login = function($form){
            PCAuth.login($scope.user, $form)
                .then(function(data){
                    console.log('current user', PCAuth.me);
                    $state.go('main');
                })
                .catch(function(response){
                    console.log('Failed to login', response);
                });
        };

        var testFn = function(user){
            console.log('typeof user', typeof user);
            console.log('onStatusChange', user);
        };

        var statusChangeHandler = PCAuth.onStatusChange(testFn);

        $scope.$on('$destroy', statusChangeHandler);
    })
    .controller('route1', function($scope){

    })
    // .provider('httpHandlers', function TestProvider(){
    //     var _state;
    //     this.test = function(){
    //         console.log('test handler');
    //         _state.go('login');
    //     };
    //     this.$get = function($state){
    //         console.log('initiating httpHandlersProvider');
    //         _state = $state;
    //         return new TestProvider();
    //     };
    // })
    .config(function(PCUserProvider, PCAuthProvider, PCAuthInterceptorProvider,
        $stateProvider, $urlRouterProvider,
        $locationProvider, Settings, $injector){

        var state;

        PCUserProvider.config.endpoint = Settings.apiUrl+'users';
        PCAuthProvider.config.endpoint = Settings.apiUrl;
        PCAuthProvider.config.tokenRefreshEndpoint = Settings.apiBaseUrl + 'refresh-token';
        PCAuthProvider.config.onTokenExpiration = function(auth){
            console.log('Token expired, handle in project');
            auth.refreshToken()
        };

        PCAuthInterceptorProvider.config.responseErrorHandlers[401] = function(response, _$injector){
            console.log('Got 401; redirecting to login');
            // $injector.get('$state');

                var $state = _$injector.get('$state');
                console.log('ASDF $state', $state);
                console.log($injector === _$injector);

            // (state || (state = $injector.get('$state')))
            $state
            // $stateProvider
                .transitionTo('login');

        };
        PCAuthInterceptorProvider.config.responseErrorHandlers[403] = function(response){
            console.log('Got 403');
        };

        $urlRouterProvider
            .otherwise('/');

        // $locationProvider
        //     .html5Mode({
        //         enabled: true
        //     });

        $stateProvider
            .state('main', {
                url: '/',
                templateUrl: '/main.html',
                controller: 'MainCtrl',
                restrict: [2,3,4]
            })
            .state('route1', {
                url: '/route1',
                templateUrl: '/route1.html',
                controller: 'route1',
                restrict: [2,3,4]
            })
            .state('login', {
                url: '/login',
                templateUrl: '/login.html',
                controller: 'LoginCtrl'
            })
            ;
    })
    .run(function($state){
        window.$state = $state;
    })
;


text:
<?php

namespace M42e\WorkflowIs\Parameter;
use \M42e\WorkflowIs;
use \CFPropertyList\CFPropertyList;
use \CFPropertyList\CFDictionary;

/**
 * WFSpeakTextWait
 * @author Matthias Bilger
 */

class WFSpeakTextWait extends WFParameter
{

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading;

namespace Archon.Enums
{
	public static class EnumUtility
	{
		static readonly IDictionary<Type, EnumDescriptor[]> reflectionCache = new Dictionary<Type, EnumDescriptor[]>();
		static readonly ReaderWriterLockSlim reflectionCacheLock = new ReaderWriterLockSlim();

		public static string CategoryOf(this Enum enumType)
		{
			var descriptions = Describe(enumType.GetType());
			var descriptor = descriptions.Single(d => d.Value.Equals(enumType));
			return descriptor.Category;
		}

		public static string DescriptionOf(this Enum enumType)
		{
			var descriptions = Describe(enumType.GetType());
			var descriptor = descriptions.Single(d => d.Value.Equals(enumType));
			return descriptor.Description;
		}

		public static IEnumerable<EnumDescriptor> Describe(Type enumType)
		{
			if (enumType == null)
				throw new ArgumentNullException("enumType");

			reflectionCacheLock.EnterReadLock();

			try
			{
				if (reflectionCache.ContainsKey(enumType))
					return reflectionCache[enumType];
			}
			finally
			{
				reflectionCacheLock.ExitReadLock();
			}

			reflectionCacheLock.EnterWriteLock();

			try
			{
				if (reflectionCache.ContainsKey(enumType))
					return reflectionCache[enumType];

				Array values = Enum.GetValues(enumType);
				var descriptions = new EnumDescriptor[values.Length];

				for (int i = 0; i < values.Length; i++)
				{
					descriptions[i] = new EnumDescriptor((Enum)values.GetValue(i));
				}

				reflectionCache.Add(enumType, descriptions);
				return descriptions;
			}
			finally
			{
				reflectionCacheLock.ExitWriteLock();
			}
		}

		public static T GetEnumValueFromEnumDescription<T>(this string description)
		{
			var type = typeof(T).GetTypeInfo();

			if (!type.IsEnum)
				throw new ArgumentException();

			FieldInfo[] fields = type.GetFields();

			var field = fields
				.SelectMany(f => f.GetCustomAttributes(typeof(DescriptionAttribute), false), (f, a) => new { Field = f, Att = a })
				.SingleOrDefault(a => ((DescriptionAttribute)a.Att).Description == description);

			return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
		}
	}
}


text:
<?php

namespace Oro\Bundle\ConfigBundle\Tests\Unit\Entity\Repository;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;

use Oro\Bundle\ConfigBundle\Entity\Repository\ConfigValueRepository;

class ConfigValueRepositoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ConfigValueRepository
     */
    protected $repository;

    /**
     * @var EntityManager
     */
    protected $om;

    /**
     * prepare mocks
     */
    public function setUp()
    {
        $this->om = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->setMethods(array('createQueryBuilder', 'beginTransaction', 'commit'))
            ->getMock();

        $this->repository = new ConfigValueRepository(
            $this->om,
            new ClassMetadata('Oro\Bundle\ConfigBundle\Entity\Config\Value')
        );
    }

    /**
     * test removeValues
     */
    public function testRemoveValues()
    {
        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->setMethods(array('delete', 'andWhere', 'where', 'setParameter', 'getQuery'))
            ->getMock();

        $query = $this->getMockBuilder('Doctrine\ORM\AbstractQuery')
            ->disableOriginalConstructor()
            ->setMethods(array('execute'))
            ->getMockForAbstractClass();
        $query->expects($this->once())
            ->method('execute');

        $queryBuilder->expects($this->once())
            ->method('delete')
            ->with('OroConfigBundle:ConfigValue', 'cv')
            ->will($this->returnSelf());
        $queryBuilder->expects($this->once())
            ->method('where')
            ->will($this->returnSelf());
        $queryBuilder->expects($this->exactly(2))
            ->method('andWhere')
            ->will($this->returnSelf());
        $queryBuilder->expects($this->exactly(3))
            ->method('setParameter')
            ->will($this->returnSelf());
        $queryBuilder->expects($this->once())
            ->method('getQuery')
            ->will($this->returnValue($query));

        $this->om->expects($this->once())
            ->method('createQueryBuilder')
            ->will($this->returnValue($queryBuilder));

        $this->om->expects($this->once())
            ->method('beginTransaction');

        $this->om->expects($this->once())
            ->method('commit');

        $removed = array(
            array('oro_user', 'level')
        );

        $configMock = $this->getMock('Oro\Bundle\ConfigBundle\Entity\Config');

        $this->repository->removeValues($configMock, $removed);
    }
}


text:
module Spaceship
  module Tunes
    class IAPSubscriptionPricingTier < TunesBase
      # @return (String) Number of the subscription price tier (e.g. "1" for Tier 1 )
      attr_accessor :tier_stem

      # @return (String) Name of the tier (e.g. "ITC.addons.pricing.tier.1" for Tier 1)
      attr_accessor :tier_name

      # @return ([Spaceship::Tunes::IAPSubscriptionPricingInfo]) A list of all prices for the respective countries
      attr_accessor :pricing_info

      attr_mapping(
        "tierStem" => :tier_stem,
        "tierName" => :tier_name
      )

      def pricing_info
        @pricing_info ||= raw_data['pricingInfo'].map { |info| IAPSubscriptionPricingInfo.new(info) }
      end
    end

    class IAPSubscriptionPricingInfo < TunesBase
      # @return (String) country code, e.g. "US"
      attr_accessor :country_code

      # @return (String) currency symbol, e.g. "$"
      attr_accessor :currency_symbol

      # @return (String) currency code, e.g. "USD"
      attr_accessor :currency_code

      # @return (Number) net proceedings for the developer in the first year
      attr_accessor :wholesale_price

      # @return (Number) net proceedings for the developer after the first year
      attr_accessor :wholesale_price2

      # @return (Number) customer price
      attr_accessor :retail_price

      # @return (String) formatted customer price, e.g. "$0.00"
      attr_accessor :f_retail_price

      # @return (String) formatted net proceedings in the first year, e.g. "$0.00"
      attr_accessor :f_wholesale_price

      # @return (String) formatted net proceedings after the first year, e.g. "$0.00"
      attr_accessor :f_wholesale_price2

      attr_mapping(
        "countryCode" => :country_code,
        "currencySymbol" => :currency_symbol,
        "currencyCode" => :currency_code,
        "wholesalePrice" => :wholesale_price,
        "wholesalePrice2" => :wholesale_price2,
        "retailPrice" => :retail_price,
        "fRetailPrice" => :f_retail_price,
        "fWholesalePrice" => :f_wholesale_price,
        "fWholesalePrice2" => :f_wholesale_price2
      )
    end
  end
end


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

class ModelBase
  attr_accessor :punched_on, :patched_up_on, :fell_at
end

class StringDateInheritor < ModelBase
  include StringDateAccessors
  string_date_accessors :punched_on, :patched_up_on, :fell_at
end

describe StringDateAccessors do
  before do
    StringDateAccessors.date_format = '%Y/%m/%d'
  end

  describe "formatted" do
    context "datetime" do
      it "should convert to UTC" do
        input = '21/05/10 10:30'
        StringDateAccessors.datetime_format = '%d/%m/%y %H:%M'
        Time.stub(:zone).and_return('(GMT+00:00) London')
        StringDateAccessors.formatted(input).zone.should == 'UTC'
      end
    end
  end

  describe "UK format" do
    before do
      StringDateAccessors.date_format = '%d/%m/%y'
      StringDateAccessors.datetime_format = '%d/%m/%y %H:%M'
    end

    context "entering time strings with slashes" do
      subject do
        inheritor = StringDateInheritor.new

        offset = Time.zone_offset(Time.now.zone)

        @utc_min = 3
        @utc_hour = 15
        @utc_day = 11
        @utc_month = 12
        @utc_year = 2009

        @dt = DateTime.new(@utc_year,
                           @utc_month,
                           @utc_day,
                           @utc_hour,
                           @utc_min).utc + offset.seconds

        string_to_set = "#{@dt.day}/#{@dt.month}/#{@dt.year.to_s[2..3]} #{@dt.hour}:#{@dt.min}"

        inheritor.punched_on = string_to_set
        inheritor.punched_on
      end

      its(:min) { should == @utc_min }
      its(:hour) { should == @utc_hour }
      its(:day) { should == @utc_day }
      its(:month) { should == @utc_month }
      its(:year) { should == @utc_year }
      it { should be_a(Time) }
    end

    context "entering date strings with slashes" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = '11/12/09'
        inheritor.punched_on
      end

      its(:day) { should == 11 }
      its(:month) { should == 12 }
      its(:year) { should == 2009 }
      it { should be_a(Date) }
    end
  end

  describe "invalid dates" do
    subject do
      inheritor = StringDateInheritor.new
      inheritor.punched_on = 'bad'
      inheritor.patched_up_on = '2009/12/25'
      inheritor.fell_at = '25/05/10 15:00'
      inheritor
    end

    its(:invalid_date_accessors) { should include(:punched_on) }
    its(:invalid_date_accessors) { should_not include(:patched_up_on) }
    its(:invalid_date_accessors) { should_not include(:fell_at) }
  end

  describe "date accessor" do
    context "entering strings with slashes" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = '2011/12/11'
        inheritor.punched_on
      end

      its(:day) { should == 11 }
      its(:month) { should == 12 }
      its(:year) { should == 2011 }
      it { should be_a(Date) }
    end

    context "entering Date objects" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = Date.new(2011, 12, 11)
        inheritor.punched_on
      end

      its(:day) { should == 11 }
      its(:month) { should == 12 }
      its(:year) { should == 2011 }
    end

    context "entering DateTime objects" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = DateTime.new(2011, 12, 11, 15, 30)
        inheritor.punched_on
      end

      its(:min) { should == 30 }
      its(:hour) { should == 15 }
      its(:day) { should == 11 }
      its(:month) { should == 12 }
      its(:year) { should == 2011 }
    end

    context "entering blank strings" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = ''
        inheritor.punched_on
      end

      it { should be_nil }
    end

    context "entering nil" do
      subject do
        inheritor = StringDateInheritor.new
        inheritor.punched_on = nil
        inheritor.punched_on
      end

      it { should be_nil }
    end
  end
end


text:
/**
 *
 */
WizPg0 = function()
{
	this.between_1_2 = document.getElementById('img_between_1_2');
	this.between_2_3 = document.getElementById('img_between_2_3');
	this.between_3_4 = document.getElementById('img_between_3_4');
	this.after_4 = document.getElementById('img_after_4');

    this.step1Div = document.getElementById('step1_div');
    this.step2Div = document.getElementById('step2_div');
    this.step3Div = document.getElementById('step3_div');
    this.step4Div = document.getElementById('step4_div');

	this.initText();

	var availableTemplatesContainer = document.getElementById( "availableTemplatesContainer" );
	this.templatesListCtrl = new TemplatesListCtrl( "availableTemplatesDiv", WizPg0.CN_TEMPLATES_LIST, /*isSingleSelect*/true );
	availableTemplatesContainer.appendChild( this.templatesListCtrl.getRoot());
	this.templatesListCtrl.setDefaultSelectedItemClassName( "selectedItem" );
}
/*static*/WizPg0.CN_TEMPLATES_LIST = "columnsList";

WizPg0.prototype.initText = function()
{
	Messages.setElementText("selectModelTitle", "selectModelTitle");
	Messages.setElementText("step1DetailsTitle", "step1DetailsTitle");
	Messages.setElementText("availModelsTitle", "availModelsTitle");
	Messages.setElementText("viewsdiv", "loadingViewsProgressMsg");
	Messages.setElementText("businessViewTitle", "businessViewTitle");
	Messages.setElementText("step1Desc", "descTitle");
	Messages.setElementText("defineTmpltTitle", "defineTmpltTitle");
	Messages.setElementText("tmpltDetailsTitle", "tmpltDetailsTitle");
	Messages.setElementText("availTmpltsTitle", "availTmpltsTitle");
	Messages.setElementText("thumbnailTitle", "thumbnailTitle");
	Messages.setElementText("step1Desc2", "descTitle");
}
WizPg0.prototype.showPg = function()
{

	var title = Messages.getString("step1Title");
	document.getElementById('content0').style.display='block';

	this.step1Div.style.backgroundImage="url('images/steps_active_slice.gif')";
    this.between_1_2.src = "images/steps_middle_mixed.gif";
	this.step2Div.style.backgroundImage="url('images/steps_inactive_slice.gif')";
    this.between_2_3.src = "images/steps_middle_inactive.gif";
	this.step3Div.style.backgroundImage="url('images/steps_inactive_slice.gif')";
    this.between_3_4.src = "images/steps_middle_inactive.gif";
	this.step4Div.style.backgroundImage="url('images/steps_inactive_slice.gif')";
    this.after_4.src = "images/steps_middle_inactive.gif";

    setHeights_step0();
}
WizPg0.prototype.hidePg = function()
{
	document.getElementById('content0').style.display='none';
}

/**
 * @param tableNames array of Strings, where each string is
 * the name of a business view in a model
 */
WizPg0.prototype.setCategories = function( tableNames )
{
	var html = "
";
	for (var ii=0; ii<tableNames.length; ++ii )
	{
		html += "
" + tableNames[ii] + "
";
	}
	html += "
";
	document.getElementById('categoriesContainer').innerHTML = html;
}
/**
 * @param description String description for the current business model
 */
WizPg0.prototype.setDescription = function( description )
{
	document.getElementById('modelDescription').innerHTML = description;
}
WizPg0.prototype.updateBusinessViewSelection = function( modelId, viewId )
{
	var tblElem = document.getElementById( "businessViewList" );

	var elems = tblElem.getElementsByTagName( "tr" );
	for ( var ii=0; ii<elems.length; ++ii )
	{
		var elem = elems[ii];
		elem.className = "unselectedItem";
	}
	var targ = document.getElementById( modelId + "_" + viewId );
	targ.className = "selectedItem";
}
/**
 * @return TemplatesListCtrl the list control that displays the list of templates
 */
WizPg0.prototype.getTemplatesListCtrl = function()
{
	return this.templatesListCtrl;
}


text:
//
// Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://aws.amazon.com/apache2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol  AWSSignInProviderApplicationIntercept <NSObject>

/**
 * Passes parameters used to launch the application to the current identity provider. For some
 * third party providers, this completes the User Sign-in call flow, which used a browser to
 * get information from the user, directly. The current sign-in provider will be set to nil if
 * the sign-in provider is not registered using `registerAWSSignInProvider:forKey` method  of
 * `AWSSignInProviderFactory` class.
 * @param application application
 * @param launchOptions options used to launch the application
 * @return true if this call handled the operation
 */
- (BOOL)interceptApplication:(UIApplication *)application
didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions;

/**
 * Passes parameters used to launch the application to the current identity provider. For some
 * third party providers, this completes the User Sign-in call flow, which used a browser to
 * get information from the user, directly.
 * @param application application
 * @param url url used to open the application
 * @param sourceApplication source application
 * @param annotation annotation
 * @return true if this call handled the operation
 */
- (BOOL)interceptApplication:(UIApplication *)application
                     openURL:(NSURL *)url
           sourceApplication:(nullable NSString *)sourceApplication
                  annotation:(id)annotation;

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace Atotrukis\MainBundle\Tests\Service;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Atotrukis\MainBundle\Entity\User;

class UserKeywordServiceTest extends WebTestCase
{
    private $newKeyword = 'test123456789test';

    public function testNewKeyword()
    {
        $this->addKeyword($this->newKeyword);
        $keyCreated = $this->checkIfExist($this->newKeyword, 3);
        $this->assertTrue($keyCreated);
    }

    public function testNewExistingKeyword()
    {
        $this->addKeyword($this->newKeyword);
        $keyCreated = $this->getKernel()->get('userKeywordService')->getKeyword(
            $this->getKernel()->get('userService')->getUserById(3),
            $this->newKeyword
        );
        $this->assertEquals($keyCreated->getValue(), 2);
    }

    public function testDeleteKeyword()
    {
        $this->deleteKeyword($this->newKeyword);
        $keyCreated = $this->checkIfExist($this->newKeyword, 3);
        $this->assertFalse($keyCreated);
    }

    public function testGetEventRate()
    {
        $eventKeywords = array(
            'test' => 1,
            'test2' => 1,
            'testNULL' => 1,
        );
        $userId =  $this->getKernel()->get('userService')->getUserById(3);
        $this->addKeyword('test');
        $this->addKeyword('test2');
        $eventRate = $this->getKernel()->get('userKeywordService')->getEventRate($eventKeywords, $userId);
        $this->deleteKeyword('test');
        $this->deleteKeyword('test2');
        $this->assertEquals($eventRate, 2);
    }

    private function deleteKeyword($keyword)
    {
        $this->getKernel()->get('userKeywordService')->keywordDelete(
            $keyword,
            $this->getKernel()->get('userService')->getUserById(3)
        );
    }

    private function addKeyword($keyword)
    {
        $this->getKernel()->get('userKeywordService')->addKeyword(
            $keyword,
            $this->getKernel()->get('userService')->getUserById(3)
        );
    }

    private function checkIfExist($keyword, $userId)
    {
        $kernel = $this->getKernel();
        $userKeywordService = $kernel->get('UserKeywordService');
        $key = $userKeywordService->getKeyword($userId, $keyword);
        if ($key == null) {
            return false;
        } else {
            return true;
        }
    }

    private function getKernel()
    {
        $kernel = static::createKernel();
        $kernel->boot();
        return $kernel->getContainer();
    }

}