text:
require 'jdbc_common'
require 'db/derby'

class CreateDummies < ActiveRecord::Migration
  def self.up
    create_table :dummies, :force => true do |t|
      t.string :year, :default => "", :null => false
    end
    add_index :dummies, :year, :unique => true
  end

end

class ChangeColumn < ActiveRecord::Migration
  def self.up
    create_table :people, :id => false, :force => true do |t|
      t.string :id, :limit => 22, :null => false
      t.string :name, :null => false
    end
    change_column(:people, :name, :string, {:limit=>22})
    execute("SELECT id FROM people WHERE id = 'some string'")
  end

  def self.down
  end

end

class CreateIndex < ActiveRecord::Migration
  def self.up
    create_table :people, :id => false, :force => true do |t|
      t.string :id, :limit => 22, :null => false
      t.string :first_name, :null => false
      t.string :last_name, :null => false
      t.string :nickname, :null => false
      t.string :long_name, :null => false
      t.string :very_long_name, :null => false
      t.string :extremely_long_name, :null => false
    end

    add_index(:people, [:first_name, :last_name, :nickname, :long_name, :very_long_name, :extremely_long_name], :unique => true)

    remove_index(:people, [:first_name, :last_name, :nickname, :long_name, :very_long_name, :extremely_long_name])
  end

  def self.down
  end

end

class DerbyMigrationTest < Test::Unit::TestCase
  include FixtureSetup

  def test_create_table_column_quoting_vs_keywords
    CreateDummies.up
  end

  def test_migrate_change_column_for_non_standard_id
    ChangeColumn.up
    ChangeColumn.down
  end

  def test_migrate_create_index
    CreateIndex.up
    CreateIndex.down
  end

end


text:
 - Goal tree
   - a hierarchy of goals
   - goal is written by state

 - State can be changed by actions
   - state change can achieve a goal

redpajama_set_name: RedPajamaGithub


text:
package org.encog.examples.ml.world;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

import org.encog.ml.data.specific.BiPolarNeuralData;
import org.encog.neural.thermal.HopfieldNetwork;
import org.encog.util.EngineArray;

public class QLearningPanel extends JPanel implements MouseListener {

	public HopfieldNetwork hopfield;
	private boolean grid[];
	private int margin;

	private int gridX;
	private int gridY;
	private int cellWidth;
	private int cellHeight;

	public QLearningPanel(int gridX,int gridY) {
		this.gridX = gridX;
		this.gridY = gridY;
		this.grid = new boolean[this.gridX * this.gridY];
		this.addMouseListener(this);
		this.hopfield = new HopfieldNetwork(this.gridX * this.gridY);
	}

	/**
	 * Clear the grid.
	 */
	public void clear() {
		int index = 0;
		for (int y = 0; y < this.gridY; y++) {
			for (int x = 0; x < this.gridX; x++) {
				this.grid[index++] = false;
			}
		}

		repaint();
	}

	/**
	 * Clear the weight matrix.
	 */
	public void clearMatrix() {
		EngineArray.fill(this.hopfield.getWeights(),0);
	}

	/**
	 * Run the neural network.
	 */
	public void go() {
		for(int i=0;i<this.grid.length;i++) {
			this.hopfield.getCurrentState().setData(i, grid[i]);
		}

		this.hopfield.run();

		for(int i=0;i<this.grid.length;i++) {
			grid[i] = this.hopfield.getCurrentState().getBoolean(i);
		}
		repaint();

	}

	public void mouseReleased(final MouseEvent e) {
		final int x = ((e.getX() - this.margin) / this.cellWidth);
		final int y = e.getY() / this.cellHeight;
		if (((x >= 0) && (x < this.gridY)) && ((y >= 0) && (y < this.gridY))) {
			final int index = (y * this.gridX) + x;
			this.grid[index] = !this.grid[index];
		}
		repaint();

	}

	@Override
	public void paint(final Graphics g) {
		int width = this.getWidth();
		int height = this.getHeight();
		this.cellHeight = height/this.gridY;
		this.cellWidth = width/this.gridX;

		g.setColor(Color.WHITE);
		g.fillRect(0,0, width, height);
		g.setColor(Color.BLACK);
		this.margin = (this.getWidth() - (this.cellWidth * this.gridX)) / 2;
		int index = 0;
		for (int y = 0; y < this.gridY; y++) {
			for (int x = 0; x < this.gridX; x++) {
				if (this.grid[index++]) {
					g.fillRect(this.margin + (x * this.cellWidth), y
							* this.cellHeight, this.cellWidth,
							this.cellHeight);
				} else {
					g.drawRect(this.margin + (x * this.cellWidth), y
							* this.cellHeight, this.cellWidth,
							this.cellHeight);
				}
			}
		}
	}

	/**
	 * Train the neural network.
	 */
	public void train() {
		BiPolarNeuralData pattern = new BiPolarNeuralData(this.grid.length);

		for(int i=0;i<this.grid.length;i++) {
			pattern.setData(i, grid[i]);
		}

		this.hopfield.addPattern(pattern);

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

}


text:
<?php echo $employee_position['full_name']; ?> Details

			Date Started:
			<?php echo $employee_position['date_started']; ?>

			Date Ended:
			<?php echo $employee_position['date_ended']; ?>

			Company:
			<?php echo $employee_position['company']; ?>

			Department:
			<?php echo $employee_position['department']; ?>

	<button class="btn btn-primary" data-dismiss="modal">Close</button>


text:
<?php

/*
 * This work is hereby released into the Public Domain.
 * To view a copy of the public domain dedication,
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 *
 */

if (is_file(dirname(__FILE__) . "/Artichow.cfg.php")) { // For PHP 4+5 version
    require_once dirname(__FILE__) . "/Artichow.cfg.php";
}

/*
 * Register a class with the prefix in configuration file
 */

function registerClass($class, $abstract = FALSE) {

    if (ARTICHOW_PREFIX === 'aw') {
        return;
    }

    if ($abstract) {
        $abstract = 'abstract';
    } else {
        $abstract = '';
    }

    eval($abstract . " class " . ARTICHOW_PREFIX . $class . " extends aw" . $class . " { }");
}

/*
 * Register an interface with the prefix in configuration file
 */

function registerInterface($interface) {

    if (ARTICHOW_PREFIX === 'aw') {
        return;
    }

    eval("interface " . ARTICHOW_PREFIX . $interface . " extends aw" . $interface . " { }");
}

// Some useful files
require_once ARTICHOW . "/Component.class.php";

require_once ARTICHOW . "/inc/Grid.class.php";
require_once ARTICHOW . "/inc/Tools.class.php";
require_once ARTICHOW . "/inc/Driver.class.php";
require_once ARTICHOW . "/inc/Math.class.php";
require_once ARTICHOW . "/inc/Tick.class.php";
require_once ARTICHOW . "/inc/Axis.class.php";
require_once ARTICHOW . "/inc/Legend.class.php";
require_once ARTICHOW . "/inc/Mark.class.php";
require_once ARTICHOW . "/inc/Label.class.php";
require_once ARTICHOW . "/inc/Text.class.php";
require_once ARTICHOW . "/inc/Color.class.php";
require_once ARTICHOW . "/inc/Font.class.php";
require_once ARTICHOW . "/inc/Gradient.class.php";
require_once ARTICHOW . "/inc/Shadow.class.php";
require_once ARTICHOW . "/inc/Border.class.php";

require_once ARTICHOW . "/common.php";

/**
 * An image for a graph
 *
 * @package Artichow
 */
class awImage {

    /**
     * Graph width
     *
     * @var int
     */
    public $width;

    /**
     * Graph height
     *
     * @var int
     */
    public $height;

    /**
     * Use anti-aliasing ?
     *
     * @var bool
     */
    protected $antiAliasing = FALSE;

    /**
     * Image format
     *
     * @var int
     */
    protected $format = awImage::PNG;

    /**
     * Image background color
     *
     * @var Color
     */
    protected $background;

    /**
     * GD resource
     *
     * @var resource
     */
    protected $resource;

    /**
     * A Driver object
     *
     * @var Driver
     */
    protected $driver;

    /**
     * Driver string
     *
     * @var string
     */
    protected $driverString;

    /**
     * Shadow
     *
     * @var Shadow
     */
    public $shadow;

    /**
     * Image border
     *
     * @var Border
     */
    public $border;

    /**
     * Use JPEG for image
     *
     * @var int
     */
    const JPEG = IMG_JPG;

    /**
     * Use PNG for image
     *
     * @var int
     */
    const PNG = IMG_PNG;

    /**
     * Use GIF for image
     *
     * @var int
     */
    const GIF = IMG_GIF;

    /**
     * Build the image
     */
    public function __construct() {

        $this->background = new awColor(255, 255, 255);
        $this->shadow = new awShadow(awShadow::RIGHT_BOTTOM);
        $this->border = new awBorder;
    }

    /**
     * Get driver of the image
     *
     * @param int $w Driver width (from 0 to 1) (default to 1)
     * @param int $h Driver height (from 0 to 1) (default to 1)
     * @param float $x Position on X axis of the center of the driver (default to 0.5)
     * @param float $y Position on Y axis of the center of the driver (default to 0.5)
     * @return Driver
     */
    public function getDriver($w = 1, $h = 1, $x = 0.5, $y = 0.5) {
        $this->create();
        $this->driver->setSize($w, $h);
        $this->driver->setPosition($x, $y);
        return $this->driver;
    }

    /**
     * Sets the driver that will be used to draw the graph
     *
     * @param string $driverString
     */
    public function setDriver($driverString) {
        $this->driver = $this->selectDriver($driverString);

        $this->driver->init($this);
    }

    /**
     * Change the image size
     *
     * @var int $width Image width
     * @var int $height Image height
     */
    public function setSize($width, $height) {

        if ($width !== NULL) {
            $this->width = (int) $width;
        }
        if ($height !== NULL) {
            $this->height = (int) $height;
        }
    }

    /**
     * Change image background
     *
     * @param mixed $background
     */
    public function setBackground($background) {
        if ($background instanceof awColor) {
            $this->setBackgroundColor($background);
        } elseif ($background instanceof awGradient) {
            $this->setBackgroundGradient($background);
        }
    }

    /**
     * Change image background color
     *
     * @param awColor $color
     */
    public function setBackgroundColor(awColor $color) {
        $this->background = $color;
    }

    /**
     * Change image background gradient
     *
     * @param awGradient $gradient
     */
    public function setBackgroundGradient(awGradient $gradient) {
        $this->background = $gradient;
    }

    /**
     * Return image background, whether a Color or a Gradient
     *
     * @return mixed
     */
    public function getBackground() {
        return $this->background;
    }

    /**
     * Turn antialiasing on or off
     *
     * @var bool $bool
     */
    public function setAntiAliasing($bool) {
        $this->antiAliasing = (bool) $bool;
    }

    /**
     * Return the antialiasing setting
     *
     * @return bool
     */
    public function getAntiAliasing() {
        return $this->antiAliasing;
    }

    /**
     * Change image format
     *
     * @var int $format New image format
     */
    public function setFormat($format) {
        if ($format === awImage::JPEG or $format === awImage::PNG or $format === awImage::GIF) {
            $this->format = $format;
        }
    }

    /**
     * Returns the image format as an integer
     *
     * @return unknown
     */
    public function getFormat() {
        return $this->format;
    }

    /**
     * Returns the image format as a string
     *
     * @return string
     */
    public function getFormatString() {

        switch ($this->format) {
            case awImage::JPEG :
                return 'jpeg';
            case awImage::PNG :
                return 'png';
            case awImage::GIF :
                return 'gif';
        }
    }

    /**
     * Create a new awimage
     */
    public function create() {

        if ($this->driver === NULL) {
            $driver = $this->selectDriver($this->driverString);

            $driver->init($this);

            $this->driver = $driver;
        }
    }

    /**
     * Select the correct driver
     *
     * @param string $driver The desired driver
     * @return mixed
     */
    protected function selectDriver($driver) {
        $drivers = array('gd');
        $driver = strtolower((string) $driver);

        if (in_array($driver, $drivers, TRUE)) {
            $string = $driver;
        } else {
            $string = ARTICHOW_DRIVER;
        }

        switch ($string) {
            case 'gd':
                require_once ARTICHOW . '/inc/drivers/gd.class.php';
                $this->driverString = $string;
                return new awGDDriver();

            default:
                // We should never get here, unless the wrong string is used AND the ARTICHOW_DRIVER
                // global has been messed with.
                awImage::drawError('Class Image: Unknown driver type (\'' . $string . '\')');
                break;
        }
    }

    /**
     * Draw a component on the image
     *
     * @var awComponent $component A component
     */
    public function drawComponent(awComponent $component) {

        $shadow = $this->shadow->getSpace(); // Image shadow
        $border = $this->border->visible() ? 1 : 0; // Image border size

        $driver = clone $this->driver;
        $driver->setImageSize(
                $this->width - $shadow->left - $shadow->right - $border * 2, $this->height - $shadow->top - $shadow->bottom - $border * 2
        );

        // No absolute size specified
        if ($component->w === NULL and $component->h === NULL) {

            list($width, $height) = $driver->setSize($component->width, $component->height);

            // Set component size in pixels
            $component->setAbsSize($width, $height);
        } else {

            $driver->setAbsSize($component->w, $component->h);
        }

        if ($component->top !== NULL and $component->left !== NULL) {
            $driver->setAbsPosition(
                    $border + $shadow->left + $component->left, $border + $shadow->top + $component->top
            );
        } else {
            $driver->setPosition($component->x, $component->y);
        }

        $driver->movePosition($border + $shadow->left, $border + $shadow->top);

        list($x1, $y1, $x2, $y2) = $component->getPosition();

        $component->init($driver);

        $component->drawComponent($driver, $x1, $y1, $x2, $y2, $this->antiAliasing);
        $component->drawEnvelope($driver, $x1, $y1, $x2, $y2);

        $component->finalize($driver);
    }

    protected function drawShadow() {

        $driver = $this->getDriver();

        $this->shadow->draw(
                $driver, new awPoint(0, 0), new awPoint($this->width, $this->height), awShadow::IN
        );
    }

    /**
     * Send the image into a file or to the user browser
     *
     */
    public function send() {
        $this->driver->send($this);
    }

    /**
     * Return the image content as binary data
     *
     */
    public function get() {
        return $this->driver->get($this);
    }

    /**
     * Send the correct HTTP header according to the image type
     *
     */
    public function sendHeaders() {

        if (headers_sent() === FALSE) {

            switch ($this->driverString) {
                case 'gd' :
                    header('Content-type: image/' . $this->getFormatString());
                    break;
            }
        }
    }

    private static $errorWriting = FALSE;

    /*
     * Display an error image and exit
     *
     * @param string $message Error message
     */

    public static function drawError($message) {

        if (self::$errorWriting) {
            return;
        }

        self::$errorWriting = TRUE;

        $message = wordwrap($message, 40, "\n", TRUE);

        $width = 400;
        $height = max(100, 40 + 22.5 * (substr_count($message, "\n") + 1));

        $image = new awImage();
        $image->setSize($width, $height);
        $image->setDriver('gd');

        $driver = $image->getDriver();
        $driver->init($image);

        // Display title
        $driver->filledRectangle(
                new awWhite, new awLine(
                new awPoint(0, 0), new awPoint($width, $height)
                )
        );

        $driver->filledRectangle(
                new awRed, new awLine(
                new awPoint(0, 0), new awPoint(110, 25)
                )
        );

        $text = new awText(
                "Artichow error", new awFont3, new awWhite, 0
        );

        $driver->string($text, new awPoint(5, 6));

        // Display red box
        $driver->rectangle(
                new awRed, new awLine(
                new awPoint(0, 25), new awPoint($width - 90, $height - 1)
                )
        );

        // Display error image
        $file = ARTICHOW_IMAGE . DIRECTORY_SEPARATOR . 'error.png';

        $imageError = new awFileImage($file);
        $driver->copyImage(
                $imageError, new awPoint($width - 81, $height - 81), new awPoint($width - 1, $height - 1)
        );

        // Draw message
        $text = new awText(
                strip_tags($message), new awFont2, new awBlack, 0
        );

        $driver->string($text, new awPoint(10, 40));

        $image->send();

        exit;
    }

    /*
     * Display an error image located in a file and exit
     *
     * @param string $error Error name
     */

    public static function drawErrorFile($error) {

        $file = ARTICHOW_IMAGE . DIRECTORY_SEPARATOR . 'errors' . DIRECTORY_SEPARATOR . $error . '.png';

        header("Content-Type: image/png");
        readfile($file);
        exit;
    }

}

registerClass('Image');

/**
 * Load an image from a file
 *
 * @package Artichow
 */
class awFileImage extends awImage {

    /**
     * Build a new awimage
     *
     * @param string $file Image file name
     */
    public function __construct($file) {

        $driver = $this->selectDriver($this->driverString);

        $driver->initFromFile($this, $file);

        $this->driver = $driver;
    }

}

registerClass('FileImage');
?>


text:
layout: model
title: Google T5 (Text-To-Text Transfer Transformer) Small
author: John Snow Labs
name: t5_small
date: 2022-05-31
tags: [t5, small, en, summarization, translation, seq2seq, open_source]
task: Text Generation
language: en
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: T5Transformer
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

The T5 transformer model is described in the seminal paper "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". This model can perform a variety of tasks, such as text summarization, question answering, and translation. More details about using the model can be found in the paper (https://arxiv.org/pdf/1910.10683.pdf).

## Predicted Entities

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
[Open in Colab](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/T5TRANSFORMER.ipynb){:.button.button-orange.button-orange-trans.co.button-icon}
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/t5_small_en_4.0.0_3.0_1654005333499.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

Either set the following tasks or have them in line with your input:

- summarize:
- translate English to German:
- translate English to French:
- stsb sentence1: Big news. sentence2: No idea.

The full list of tasks is in the Appendix of the paper: https://arxiv.org/pdf/1910.10683.pdf

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
document_assembler = DocumentAssembler() \
.setInputCol("text") \
.setOutputCol("documents")

t5 = T5Transformer() \
.pretrained("t5_small") \
.setTask("summarize:")\
.setMaxOutputLength(200)\
.setInputCols(["documents"]) \
.setOutputCol("summaries")

pipeline = Pipeline().setStages([document_assembler, t5])
results = pipeline.fit(data_df).transform(data_df)

results.select("summaries.result").show(truncate=False)
```
```scala
val documentAssembler = new DocumentAssembler()
.setInputCol("text")
.setOutputCol("documents")

val t5 = T5Transformer
.pretrained("t5_small")
.setTask("summarize:")
.setInputCols(Array("documents"))
.setOutputCol("summaries")

val pipeline = new Pipeline().setStages(Array(documentAssembler, t5))

val model = pipeline.fit(dataDf)
val results = model.transform(dataDf)

results.select("summaries.result").show(truncate = false)
```

{:.nlu-block}
```python
import nlu
nlu.load("en.t5.small").predict("""Put your text here.""")
```

</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|t5_small|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[documents]|
|Output Labels:|[t5]|
|Language:|en|
|Size:|148.0 MB|

## References

https://huggingface.co/t5-small


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

#require File.expand_path(File.dirname(__FILE__) + '/../support/postgresql/assertions')
require File.expand_path(File.dirname(__FILE__) + '/../support/postgresql/import_examples')

should_support_postgresql_import_functionality


text:
"use strict";

var saveData = require("splat-ecs/lib/save-data");

function deleteAllComponents(game, component) {
	var entitiesWithVelocity = game.entities.find(component).slice();
	for (var i = 0; i < entitiesWithVelocity.length; i++) {
		game.entities.remove(entitiesWithVelocity[i], component);
	}
}

module.exports = function(ecs, game) { // eslint-disable-line no-unused-vars
	game.entities.registerSearch("resolve-collisions",["player", "collisions"]);
	ecs.addEach(function resolveCollisions(entity) { // eslint-disable-line no-unused-vars
		var collisions = game.entities.get(entity, "collisions");
		var hasCollided = false;
		var highscore = game.entities.get(entity, "highscore");
		var score = game.entities.get(entity, "score");
		for (var i = 0; i < collisions.length; i++) {
			var obstacle = game.entities.get(collisions[i], "obstacle");
			if (obstacle) {
				deleteAllComponents(game, "velocity");
				deleteAllComponents(game, "spawner");
				hasCollided = true;
				game.entities.set(entity, "highscoreHolder", 1);
				game.instantiatePrefab("restartButton");
				game.instantiatePrefab("titleScreen");
				game.sounds.play("death.wav");
				if (score > highscore) {
					game.entities.set(entity, "highscore", score);
					saveData.set({
						highscore: score
					}, function() {
					});
				}

			}
		}
		if (hasCollided) {
			game.entities.remove(entity, "collisions");
		}
	},"resolve-collisions");
};


text:
---
layout: default
---
## BibCite

BibCite let's you cite from your BibTeX files using a markdown-like syntax. It depends on jQuery and underscore.js.

Note: all this is still pretty experimental.

### JS
Load the dependencies and you're good to go:
{% highlight html %}

{% endhighlight %}

### Markdown
{% highlight md %}
Parenthesized citations are very common @(Lazaridou2016).
You can add a tooltip showing the full reference just
as easily @@(Lazaridou2016). Alternatively, cite in the
running text, just like @@Descartes2006. If you prefer
footnotes @^Lazaridou2016 that is also fine.[^fn1] Or cite
without showing the reference @!Banerjee2015; or get the
full reference: @@Lazaridou2016

[^fn1]: `BibCite` works nicely with footnotes in Jekyll

# References

{% endhighlight %}

### Result
Parenthesized citations are very common @(Lazaridou2016).
You can add a tooltip showing the full reference just
as easily @@(Lazaridou2016). Alternatively, cite in the
running text, just like @@Descartes2006. If you prefer
footnotes @^Lazaridou2016 that is also fine.[^fn1] Or cite
without showing the reference @!Banerjee2015; or get the
full reference: @@Lazaridou2016
{: .result}

[^fn1]: `BibCite` works nicely with footnotes in Jekyll

References

## Syntax
The citation syntax follows the general pattern **`[@ or @@][mode][citation key]{[before]}{[after]}`**. Each part is explained below.

* **`[@ or @@]`**. A single `@` results in a plain text citation, double `@@` results in an interacte citation with a full reference in a tooltip.
* **`[mode]`**. There are currently five citation modes; they are summarized in the following table.

| Syntax   | Meaning                 | Example          | Method     |
|----------|-------------------------|------------------|------------|
| `@key`   | Default inline citation | @Descartes2006   | `citet`    |
| `@(key)` | Parenthesized citation  | @(Descartes2006) | `citep`    |
| `@^key`  | Footnote citation       | @^Descartes2006  | `footcite` |
| `@*key`  | Full reference          | @*Descartes2006  | `fullcite` |
| `@!key`  | Show in references only | @!Descartes2006  | `nocite`   |

* **`[citation key]`**. The citation key from the BibTeX file. Note that this is case _in_sensitive.
* **`{[before]}`**. The text `[before]` is inserted before the citation
* **`{[after]}`**. The text `[after]` is inserted after the citation. Note that `before` and `after` can contain HTML elements (or initially, markdown), as long as it contains no curly brackets.

## Options
The `BibCite` object takes various options. These are always passed along internally and you can overwrite them in, e.g. individual citations `MyBibCite.pcite(myCitation, myOptions)`.

- **`defaultMode`** The default citation mode; defaults to `"t"` (i.e. `citet`)
- **`selector`** CSS selector for the elements in which to look for citations; defaults to `"p, li"`.
- **`before`** Default text shown before a citation, defaults to `""`.
- **`after`** Default text shown after a citation, defaults to `""`.
- ...

## More examples
- @Banerjee2015
- @@Banerjee2015
- @(Banerjee2015)
- @@(Banerjee2015)
- @@(Banerjee2015){}
- @@(Banerjee2015){Before [this is a link?](example.com)}
- @@(Banerjee2015){Before}{After}
- @@(Banerjee2015){}{After}
- @@(Banerjee2015){Before}{after} @@(Banerjee2015){before}
- Footnotes are always interactive: @^Banerjee2015 @@^Banerjee2015
- And you can include messages there: @^Banerjee2015{Look this is [a link](http://example.com).}{And an afterthough}
- @@*Banerjee2015


text:
package integration

import (
	"testing"
	"time"

	"github.com/m3db/m3/src/cluster/services"
	"github.com/m3db/m3/src/cluster/shard"
	"github.com/m3db/m3/src/dbnode/namespace"
	"github.com/m3db/m3/src/dbnode/retention"
	"github.com/m3db/m3/src/dbnode/sharding"
	"github.com/m3db/m3/src/dbnode/storage/bootstrap/bootstrapper/uninitialized"
	"github.com/m3db/m3/src/dbnode/topology"
	"github.com/m3db/m3/src/dbnode/topology/testutil"
	xtest "github.com/m3db/m3/src/x/test"

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

// TestPeersBootstrapNoneAvailable makes sure that a cluster with the peer bootstrapper enabled can still turn on
// if none of the nodes peers shard states are available or leaving.
func TestPeersBootstrapNoneAvailable(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	// Test setups
	log := xtest.NewLogger(t)
	retentionOpts := retention.NewOptions().
		SetRetentionPeriod(20 * time.Hour).
		SetBlockSize(2 * time.Hour).
		SetBufferPast(10 * time.Minute).
		SetBufferFuture(2 * time.Minute)
	namesp, err := namespace.NewMetadata(testNamespaces[0], namespace.NewOptions().SetRetentionOptions(retentionOpts))
	require.NoError(t, err)
	opts := NewTestOptions(t).
		SetNamespaces([]namespace.Metadata{namesp}).
		// Use TChannel clients for writing / reading because we want to target individual nodes at a time
		// and not write/read all nodes in the cluster.
		SetUseTChannelClientForWriting(true).
		SetUseTChannelClientForReading(true)

	minShard := uint32(0)
	maxShard := uint32(opts.NumShards()) - uint32(1)
	start := []services.ServiceInstance{
		node(t, 0, newClusterShardsRange(minShard, maxShard, shard.Initializing)),
		node(t, 1, newClusterShardsRange(minShard, maxShard, shard.Initializing)),
	}

	hostShardSets := []topology.HostShardSet{}
	for _, instance := range start {
		h, err := topology.NewHostShardSetFromServiceInstance(instance, sharding.DefaultHashFn(int(maxShard)))
		require.NoError(t, err)
		hostShardSets = append(hostShardSets, h)
	}

	shards := testutil.ShardsRange(minShard, maxShard, shard.Initializing)
	shardSet, err := sharding.NewShardSet(
		shards,
		sharding.DefaultHashFn(int(maxShard)),
	)
	require.NoError(t, err)

	topoOpts := topology.NewStaticOptions().
		SetReplicas(2).
		SetHostShardSets(hostShardSets).
		SetShardSet(shardSet)
	topoInit := topology.NewStaticInitializer(topoOpts)

	setupOpts := []BootstrappableTestSetupOptions{
		{
			DisablePeersBootstrapper: false,
			TopologyInitializer:      topoInit,
			FinalBootstrapper:        uninitialized.UninitializedTopologyBootstrapperName,
		},
		{
			DisablePeersBootstrapper: false,
			TopologyInitializer:      topoInit,
			FinalBootstrapper:        uninitialized.UninitializedTopologyBootstrapperName,
		},
	}
	setups, closeFn := NewDefaultBootstrappableTestSetups(t, opts, setupOpts)
	defer closeFn()

	setups.parallel(func(s TestSetup) {
		require.NoError(t, s.StartServer())
	})
	log.Debug("servers are now up")

	for i, s := range setups {
		assert.True(t, s.ServerIsBootstrapped(), "setups[%v] should be bootstrapped", i)
	}

	// Stop the servers
	defer func() {
		setups.parallel(func(s TestSetup) {
			require.NoError(t, s.StopServer())
		})
		log.Debug("servers are now down")
	}()
}


text:
package org.slf4j.dummyExt;

import static org.junit.Assert.assertEquals;

import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

public class XLoggerTest {

    ListAppender listAppender;
    org.apache.log4j.Logger log4jRoot;

    final static String EXPECTED_FILE_NAME = "XLoggerTest.java";

    @Before
    public void setUp() throws Exception {

        // start from a clean slate for each test

        listAppender = new ListAppender();
        listAppender.extractLocationInfo = true;
        log4jRoot = org.apache.log4j.Logger.getRootLogger();
        log4jRoot.addAppender(listAppender);
        log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
    }

    void verify(LoggingEvent le, String expectedMsg) {
        assertEquals(expectedMsg, le.getMessage());
        assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
    }

    void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) {
        verify(le, expectedMsg);
        assertEquals(t.toString(), le.getThrowableStrRep()[0]);
    }

    void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) {
        verify(le, expectedMsg);
        assertEquals(t.toString(), le.getThrowableStrRep()[0]);
        assertEquals(le.getLevel().toString(), level.toString());
    }

    @Test
    public void testEntering() {
        XLogger logger = XLoggerFactory.getXLogger("UnitTest");
        logger.entry();
        logger.entry(1);
        logger.entry("test");
        logger.entry("a", "b", "c", "d");
        logger.entry("a", "b", "c", "d", "e");
        logger.entry("a", "b", "c", "d", "e", "f");

        assertEquals(6, listAppender.list.size());
        verify((LoggingEvent) listAppender.list.get(0), "entry");
        verify((LoggingEvent) listAppender.list.get(1), "entry with (1)");
        verify((LoggingEvent) listAppender.list.get(2), "entry with (test)");
    }

    @Test
    public void testExiting() {
        XLogger logger = XLoggerFactory.getXLogger("UnitTest");
        logger.exit();
        assertEquals(Integer.valueOf(0), logger.exit(0));
        assertEquals(Boolean.FALSE, logger.exit(false));

        assertEquals(3, listAppender.list.size());
        verify((LoggingEvent) listAppender.list.get(0), "exit");
        verify((LoggingEvent) listAppender.list.get(1), "exit with (0)");
        verify((LoggingEvent) listAppender.list.get(2), "exit with (false)");
    }

    @Test
    public void testThrowing() {
        XLogger logger = XLoggerFactory.getXLogger("UnitTest");
        Throwable t = new UnsupportedOperationException("Test");
        assertEquals(t, logger.throwing(t));
        assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t));
        assertEquals(2, listAppender.list.size());
        verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t);
        LoggingEvent event = (LoggingEvent) listAppender.list.get(1);
        verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t);
    }

    @Test
    public void testCaught() {
        XLogger logger = XLoggerFactory.getXLogger("UnitTest");
        long x = 5;
        Throwable t = null;
        try {
            @SuppressWarnings("unused")
            long y = x / 0;
        } catch (Exception ex) {
            t = ex;
            logger.catching(ex);
            logger.catching(XLogger.Level.DEBUG, ex);
        }
        verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t);
        verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t);
    }

    // See http://jira.qos.ch/browse/SLF4J-105
    // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=114
    @Test
    public void testLocationExtraction_Bug114() {
        XLogger logger = XLoggerFactory.getXLogger("UnitTest");
        int line = 135; // requires update if line numbers change
        logger.exit();
        logger.debug("hello");

        assertEquals(2, listAppender.list.size());

        {
            LoggingEvent e = listAppender.list.get(0);
            LocationInfo li = e.getLocationInformation();
            assertEquals(this.getClass().getName(), li.getClassName());
            assertEquals("" + line, li.getLineNumber());
        }

        {
            LoggingEvent e = listAppender.list.get(1);
            LocationInfo li = e.getLocationInformation();
            assertEquals(this.getClass().getName(), li.getClassName());
            assertEquals("" + (line + 1), li.getLineNumber());
        }

    }
}


text:
package com.google.android.gms.wearable.internal;

import com.google.android.gms.wearable.DataItemAsset;

import org.microg.safeparcel.AutoSafeParcelable;
import org.microg.safeparcel.SafeParceled;

public class DataItemAssetParcelable extends AutoSafeParcelable implements DataItemAsset {

    @SafeParceled(1)
    private int versionCode = 1;
    @SafeParceled(2)
    private String id;
    @SafeParceled(3)
    private String key;

    private DataItemAssetParcelable() {
    }

    public DataItemAssetParcelable(String id, String key) {
        this.id = id;
        this.key = key;
    }

    @Override
    public String getDataItemKey() {
        return key;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public DataItemAsset freeze() {
        return this;
    }

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

    public static final Creator<DataItemAssetParcelable> CREATOR = new AutoCreator<DataItemAssetParcelable>(DataItemAssetParcelable.class);
}


text:
import logging
import argparse
import queue

from cloudify.amqp_client import get_client
from manager_rest import config
from manager_rest.flask_utils import setup_flask_app

from .amqp_consumer import AMQPLogsEventsConsumer, AckingAMQPConnection
from .postgres_publisher import DBLogEventPublisher

logger = logging.getLogger(__name__)
BROKER_PORT_SSL = 5671
BROKER_PORT_NO_SSL = 5672

DEFAULT_LOG_PATH = '/var/log/cloudify/amqp-postgres/amqp_postgres.log'
CONFIG_PATH = '/opt/manager/cloudify-rest.conf'

def _create_connections():
    acks_queue = queue.Queue()
    cfy_config = config.instance
    port = BROKER_PORT_SSL if cfy_config.amqp_ca else BROKER_PORT_NO_SSL
    amqp_client = get_client(
        amqp_host=cfy_config.amqp_host,
        amqp_user=cfy_config.amqp_username,
        amqp_pass=cfy_config.amqp_password,
        amqp_vhost='/',
        amqp_port=port,
        ssl_enabled=bool(cfy_config.amqp_ca),
        ssl_cert_data=cfy_config.amqp_ca,
        cls=AckingAMQPConnection
    )
    amqp_client.acks_queue = acks_queue
    db_publisher = DBLogEventPublisher(config.instance, amqp_client)
    amqp_consumer = AMQPLogsEventsConsumer(
        message_processor=db_publisher.process
    )

    amqp_client.add_handler(amqp_consumer)
    db_publisher.start()
    return amqp_client, db_publisher

def main(args):
    logging.basicConfig(
        level=args.get('loglevel', 'INFO').upper(),
        filename=args.get('logfile', DEFAULT_LOG_PATH),
        format="%(asctime)s %(message)s")
    config.instance.load_from_file(args['config'])
    with setup_flask_app().app_context():
        config.instance.load_from_db()
    amqp_client, db_publisher = _create_connections()

    logger.info('Starting consuming...')
    amqp_client.consume()
    if db_publisher.error_exit:
        raise db_publisher.error_exit

def cli():
    """Parse arguments and run main"""
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default=CONFIG_PATH,
                        help='Path to the config file')
    parser.add_argument('--logfile', default=DEFAULT_LOG_PATH,
                        help='Path to the log file')
    parser.add_argument('--log-level', dest='loglevel', default='INFO',
                        help='Logging level')
    args = parser.parse_args()
    main(vars(args))

if __name__ == '__main__':
    cli()


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

class Cities_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function get($id = null)
    {
        if (!is_null($id)) {
            $query = $this->db->select('*')->from('cities')->where('id', $id)->get();
            if ($query->num_rows() === 1) {
                return $query->row_array();
            }

            return null;
        }

        $query = $this->db->select('*')->from('cities')->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }

        return null;
    }

    public function save($city)
    {
        $this->db->set($this->_setCity($city))->insert('cities');

        if ($this->db->affected_rows() === 1) {
            return $this->db->insert_id();
        }

        return null;
    }

    public function update($city)
    {
        $id = $city['id'];

        $this->db->set($this->_setCity($city))->where('id', $id)->update('cities');

        if ($this->db->affected_rows() === 1) {
            return true;
        }

        return null;
    }

    public function delete($id)
    {
        $this->db->where('id', $id)->delete('cities');

        if ($this->db->affected_rows() === 1) {
            return true;
        }

        return null;
    }

    private function _setCity($city)
    {
        return array(
            'name' => $city['name']
        );
    }
}


text:
namespace cc {
namespace {

bool IsValidPaintShaderType(PaintShader::Type type) {
  return static_cast<uint8_t>(type) <
         static_cast<uint8_t>(PaintShader::Type::kShaderCount);
}

bool IsValidPaintShaderScalingBehavior(PaintShader::ScalingBehavior behavior) {
  return behavior == PaintShader::ScalingBehavior::kRasterAtScale ||
         behavior == PaintShader::ScalingBehavior::kFixedScale;
}

struct TypefaceCtx {
  explicit TypefaceCtx(SkStrikeClient* client) : client(client) {}
  bool invalid_typeface = false;
  raw_ptr<SkStrikeClient> client = nullptr;
};

sk_sp<SkTypeface> DeserializeTypeface(const void* data,
                                      size_t length,
                                      void* ctx) {
  auto* typeface_ctx = static_cast<TypefaceCtx*>(ctx);
  auto tf = typeface_ctx->client->deserializeTypeface(data, length);
  if (tf)
    return tf;

  typeface_ctx->invalid_typeface = true;
  return nullptr;
}

}  // namespace

// static
void PaintOpReader::FixupMatrixPostSerialization(SkMatrix* matrix) {
  // Can't trust malicious clients to provide the correct derived matrix type.
  // However, if a matrix thinks that it's identity, then make it so.
  if (matrix->isIdentity())
    matrix->setIdentity();
  else
    matrix->dirtyMatrixTypeCache();
}

// static
bool PaintOpReader::ReadAndValidateOpHeader(const volatile void* input,
                                            size_t input_size,
                                            uint8_t* type,
                                            uint32_t* skip) {
  if (input_size < 4)
    return false;
  uint32_t first_word = reinterpret_cast<const volatile uint32_t*>(input)[0];
  *type = static_cast<uint8_t>(first_word & 0xFF);
  *skip = first_word >> 8;

  if (input_size < *skip)
    return false;
  if (*skip % PaintOpBuffer::PaintOpAlign != 0)
    return false;
  if (*type > static_cast<uint8_t>(PaintOpType::LastPaintOpType))
    return false;
  return true;
}

template <typename T>
void PaintOpReader::ReadSimple(T* val) {
  static_assert(base::is_trivially_copyable<T>::value,
                "Not trivially copyable");

  // Align everything to 4 bytes, as the writer does.
  static constexpr size_t kAlign = 4;
  size_t size = base::bits::AlignUp(sizeof(T), kAlign);

  if (remaining_bytes_ < size)
    SetInvalid(DeserializationError::kInsufficientRemainingBytes_ReadSimple);
  if (!valid_)
    return;

  // Most of the time this is used for primitives, but this function is also
  // used for SkRect/SkIRect/SkMatrix whose implicit operator= can't use a
  // volatile.  TOCTOU violations don't matter for these simple types so
  // use assignment.
  *val = *reinterpret_cast<const T*>(const_cast<const char*>(memory_));

  memory_ += size;
  remaining_bytes_ -= size;
}

uint8_t* PaintOpReader::CopyScratchSpace(size_t bytes) {
  DCHECK(SkIsAlign4(reinterpret_cast<uintptr_t>(memory_)));

  if (options_.scratch_buffer->size() < bytes)
    options_.scratch_buffer->resize(bytes);
  memcpy(options_.scratch_buffer->data(), const_cast<const char*>(memory_),
         bytes);
  return options_.scratch_buffer->data();
}

template <typename T>
void PaintOpReader::ReadFlattenable(
    sk_sp<T>* val,
    Factory<T> factory,
    DeserializationError error_on_factory_failure) {
  size_t bytes = 0;
  ReadSize(&bytes);
  if (remaining_bytes_ < bytes)
    SetInvalid(
        DeserializationError::kInsufficientRemainingBytes_ReadFlattenable);
  if (!valid_)
    return;
  if (bytes == 0)
    return;

  auto* scratch = CopyScratchSpace(bytes);
  val->reset(factory(scratch, bytes, nullptr).release());
  if (!val)
    SetInvalid(error_on_factory_failure);

  memory_ += bytes;
  remaining_bytes_ -= bytes;
}

void PaintOpReader::ReadData(size_t bytes, void* data) {
  if (remaining_bytes_ < bytes)
    SetInvalid(DeserializationError::kInsufficientRemainingBytes_ReadData);
  if (!valid_)
    return;
  if (bytes == 0)
    return;

  memcpy(data, const_cast<const char*>(memory_), bytes);
  memory_ += bytes;
  remaining_bytes_ -= bytes;
}

void PaintOpReader::ReadSize(size_t* size) {
  AlignMemory(8);
  uint64_t size64 = 0;
  ReadSimple(&size64);
  *size = size64;
}

void PaintOpReader::Read(SkScalar* data) {
  ReadSimple(data);
}

    void
    PaintOpReader::Read(uint8_t* data) {
  ReadSimple(data);
}

void PaintOpReader::Read(uint32_t* data) {
  ReadSimple(data);
}

void PaintOpReader::Read(uint64_t* data) {
  ReadSimple(data);
}

void PaintOpReader::Read(int32_t* data) {
  ReadSimple(data);
}

void PaintOpReader::Read(SkRect* rect) {
  ReadSimple(rect);
}

void PaintOpReader::Read(SkIRect* rect) {
  ReadSimple(rect);
}

void PaintOpReader::Read(SkRRect* rect) {
  ReadSimple(rect);
}

void PaintOpReader::Read(SkPath* path) {
  uint32_t path_id;
  ReadSimple(&path_id);
  if (!valid_)
    return;

  uint32_t entry_state_int = 0u;
  ReadSimple(&entry_state_int);
  if (entry_state_int > static_cast<uint32_t>(PaintCacheEntryState::kLast)) {
    valid_ = false;
    return;
  }

  auto entry_state = static_cast<PaintCacheEntryState>(entry_state_int);
  switch (entry_state) {
    case PaintCacheEntryState::kEmpty:
      return;
    case PaintCacheEntryState::kCached:
      if (!options_.paint_cache->GetPath(path_id, path))
        SetInvalid(DeserializationError::kMissingPaintCachePathEntry);
      return;
    case PaintCacheEntryState::kInlined:
    case PaintCacheEntryState::kInlinedDoNotCache: {
      size_t path_bytes = 0u;
      ReadSize(&path_bytes);
      if (path_bytes > remaining_bytes_)
        SetInvalid(
            DeserializationError::kInsufficientRemainingBytes_Read_SkPath);
      if (path_bytes == 0u)
        SetInvalid(DeserializationError::kZeroSkPathBytes);
      if (!valid_)
        return;

      auto* scratch = CopyScratchSpace(path_bytes);
      size_t bytes_read = path->readFromMemory(scratch, path_bytes);
      if (bytes_read == 0u) {
        SetInvalid(DeserializationError::kSkPathReadFromMemoryFailure);
        return;
      }
      if (entry_state == PaintCacheEntryState::kInlined) {
        options_.paint_cache->PutPath(path_id, *path);
      } else {
        // If we know that this path will only be drawn once, which is
        // implied by kInlinedDoNotCache, we signal to skia that it should not
        // do any caching either.
        path->setIsVolatile(true);
      }
      memory_ += path_bytes;
      remaining_bytes_ -= path_bytes;
      return;
    }
  }
}

void PaintOpReader::Read(PaintFlags* flags) {
  ReadSimple(&flags->color_);
  Read(&flags->width_);
  Read(&flags->miter_limit_);

  Read(&flags->blend_mode_);

  ReadSimple(&flags->bitfields_uint_);

  ReadFlattenable(&flags->path_effect_, SkPathEffect::Deserialize,
                  DeserializationError::kSkPathEffectUnflattenFailure);
  ReadFlattenable(&flags->mask_filter_, SkMaskFilter::Deserialize,
                  DeserializationError::kSkMaskFilterUnflattenFailure);
  ReadFlattenable(&flags->color_filter_, SkColorFilter::Deserialize,
                  DeserializationError::kSkColorFilterUnflattenFailure);

  if (enable_security_constraints_) {
    size_t bytes = 0;
    ReadSize(&bytes);
    if (bytes != 0u) {
      SetInvalid(DeserializationError::kDrawLooperForbidden);
      return;
    }
  } else {
    ReadFlattenable(&flags->draw_looper_, SkDrawLooper::Deserialize,
                    DeserializationError::kSkDrawLooperUnflattenFailure);
  }

  Read(&flags->image_filter_);
  Read(&flags->shader_);
}

void PaintOpReader::Read(PaintImage* image) {
  uint8_t serialized_type_int = 0u;
  Read(&serialized_type_int);
  if (serialized_type_int >
      static_cast<uint8_t>(PaintOp::SerializedImageType::kLastType)) {
    SetInvalid(DeserializationError::kInvalidSerializedImageType);
    return;
  }

  auto serialized_type =
      static_cast<PaintOp::SerializedImageType>(serialized_type_int);
  if (serialized_type == PaintOp::SerializedImageType::kNoImage)
    return;

  if (enable_security_constraints_) {
    switch (serialized_type) {
      case PaintOp::SerializedImageType::kNoImage:
        NOTREACHED();
        return;
      case PaintOp::SerializedImageType::kImageData: {
        SkColorType color_type;
        Read(&color_type);
        uint32_t width;
        Read(&width);
        uint32_t height;
        Read(&height);
        size_t pixel_size;
        ReadSize(&pixel_size);
        if (!valid_)
          return;

        SkImageInfo image_info =
            SkImageInfo::Make(width, height, color_type, kPremul_SkAlphaType);
        const volatile void* pixel_data = ExtractReadableMemory(pixel_size);
        if (!valid_)
          return;

        SkPixmap pixmap(image_info, const_cast<const void*>(pixel_data),
                        image_info.minRowBytes());

        *image = PaintImageBuilder::WithDefault()
                     .set_id(PaintImage::GetNextId())
                     .set_texture_image(SkImage::MakeRasterCopy(pixmap),
                                        PaintImage::kNonLazyStableId)
                     .TakePaintImage();
      }
        return;
      case PaintOp::SerializedImageType::kTransferCacheEntry:
      case PaintOp::SerializedImageType::kMailbox:
        SetInvalid(DeserializationError::kForbiddenSerializedImageType);
        return;
    }

    NOTREACHED();
    return;
  }

  if (serialized_type == PaintOp::SerializedImageType::kMailbox) {
    if (!options_.shared_image_provider) {
      SetInvalid(DeserializationError::kMissingSharedImageProvider);
      return;
    }

    gpu::Mailbox mailbox;
    Read(&mailbox);
    if (mailbox.IsZero()) {
      SetInvalid(DeserializationError::kZeroMailbox);
      return;
    }

    SharedImageProvider::Error error;
    sk_sp<SkImage> sk_image =
        options_.shared_image_provider->OpenSharedImageForRead(mailbox, error);
    if (error != SharedImageProvider::Error::kNoError) {
      switch (error) {
        case SharedImageProvider::Error::kNoAccess:
          SetInvalid(DeserializationError::kSharedImageProviderNoAccess);
          break;
        case SharedImageProvider::Error::kSkImageCreationFailed:
          SetInvalid(
              DeserializationError::kSharedImageProviderSkImageCreationFailed);
          break;
        case SharedImageProvider::Error::kUnknownMailbox:
          SetInvalid(DeserializationError::kSharedImageProviderUnknownMailbox);
          break;
        default:
          NOTREACHED();
          break;
      }
      SetInvalid(DeserializationError::kSharedImageOpenFailure);
      return;
    }
    DCHECK(sk_image);

    *image = PaintImageBuilder::WithDefault()
                 .set_id(PaintImage::GetNextId())
                 .set_texture_image(std::move(sk_image),
                                    PaintImage::kNonLazyStableId)
                 .TakePaintImage();
    return;
  }

  if (serialized_type != PaintOp::SerializedImageType::kTransferCacheEntry) {
    SetInvalid(DeserializationError::kUnexpectedSerializedImageType);
    return;
  }

  uint32_t transfer_cache_entry_id;
  ReadSimple(&transfer_cache_entry_id);
  if (!valid_)
    return;

  bool needs_mips;
  ReadSimple(&needs_mips);
  if (!valid_)
    return;

  // If we encountered a decode failure, we may write an invalid id for the
  // image. In these cases, just return, leaving the image as nullptr.
  if (transfer_cache_entry_id == kInvalidImageTransferCacheEntryId)
    return;

  // The transfer cache entry for an image may not exist if the upload fails.
  if (auto* entry =
          options_.transfer_cache->GetEntryAs<ServiceImageTransferCacheEntry>(
              transfer_cache_entry_id)) {
    if (needs_mips)
      entry->EnsureMips();
    *image =
        PaintImageBuilder::WithDefault()
            .set_id(PaintImage::GetNextId())
            .set_texture_image(entry->image(), PaintImage::kNonLazyStableId)
            .TakePaintImage();
  }
}

void PaintOpReader::Read(sk_sp<SkData>* data) {
  size_t bytes = 0;
  ReadSize(&bytes);
  if (remaining_bytes_ < bytes)
    SetInvalid(DeserializationError::kInsufficientRemainingBytes_Read_SkData);
  if (!valid_)
    return;

  // Separate out empty vs not valid cases.
  if (bytes == 0) {
    bool has_data = false;
    Read(&has_data);
    if (has_data)
      *data = SkData::MakeEmpty();
    return;
  }

  // This is safe to cast away the volatile as it is just a memcpy internally.
  *data = SkData::MakeWithCopy(const_cast<const char*>(memory_), bytes);

  memory_ += bytes;
  remaining_bytes_ -= bytes;
}

void PaintOpReader::Read(sk_sp<SkColorSpace>* color_space) {
  size_t size = 0;
  ReadSize(&size);
  if (remaining_bytes_ < size)
    valid_ = false;
  if (!valid_ || size == 0)
    return;

  auto* scratch = CopyScratchSpace(size);
  *color_space = SkColorSpace::Deserialize(scratch, size);
  // If this had non-zero bytes, it should be a valid color space.
  if (!color_space)
    SetInvalid(DeserializationError::kSkColorSpaceDeserializeFailure);

  memory_ += size;
  remaining_bytes_ -= size;
}

void PaintOpReader::Read(sk_sp<SkTextBlob>* blob) {
  AlignMemory(4);
  uint32_t blob_id = 0u;
  Read(&blob_id);
  if (!valid_)
    return;

  size_t data_bytes = 0u;
  ReadSize(&data_bytes);
  if (remaining_bytes_ < data_bytes)
    SetInvalid(
        DeserializationError::kInsufficientRemainingBytes_Read_SkTextBlob);
  if (!valid_)
    return;

  if (data_bytes == 0u) {
    auto cached_blob = options_.paint_cache->GetTextBlob(blob_id);
    if (!cached_blob) {
      SetInvalid(DeserializationError::kMissingPaintCacheTextBlobEntry);
      return;
    }

    *blob = std::move(cached_blob);
    return;
  }

  DCHECK(options_.strike_client);
  SkDeserialProcs procs;
  TypefaceCtx typeface_ctx(options_.strike_client);
  procs.fTypefaceProc = &DeserializeTypeface;
  procs.fTypefaceCtx = &typeface_ctx;
  auto* scratch = CopyScratchSpace(data_bytes);
  sk_sp<SkTextBlob> deserialized_blob =
      SkTextBlob::Deserialize(scratch, data_bytes, procs);
  if (!deserialized_blob) {
    SetInvalid(DeserializationError::kSkTextBlobDeserializeFailure);
    return;
  }
  if (typeface_ctx.invalid_typeface) {
    SetInvalid(DeserializationError::kInvalidTypeface);
    return;
  }
  options_.paint_cache->PutTextBlob(blob_id, deserialized_blob);

  *blob = std::move(deserialized_blob);
  memory_ += data_bytes;
  remaining_bytes_ -= data_bytes;
}

void PaintOpReader::Read(sk_sp<PaintShader>* shader) {
  bool has_shader = false;
  ReadSimple(&has_shader);
  if (!has_shader) {
    *shader = nullptr;
    return;
  }
  PaintShader::Type shader_type;
  ReadSimple(&shader_type);
  // Avoid creating a shader if something is invalid.
  if (!valid_ || !IsValidPaintShaderType(shader_type)) {
    SetInvalid(DeserializationError::kInvalidPaintShaderType);
    return;
  }

  *shader = sk_sp<PaintShader>(new PaintShader(shader_type));
  PaintShader& ref = **shader;
  ReadSimple(&ref.flags_);
  ReadSimple(&ref.end_radius_);
  ReadSimple(&ref.start_radius_);
  Read(&ref.tx_);
  Read(&ref.ty_);
  ReadSimple(&ref.fallback_color_);
  ReadSimple(&ref.scaling_behavior_);
  if (!IsValidPaintShaderScalingBehavior(ref.scaling_behavior_))
    SetInvalid(DeserializationError::kInvalidPaintShaderScalingBehavior);
  bool has_local_matrix = false;
  ReadSimple(&has_local_matrix);
  if (has_local_matrix) {
    ref.local_matrix_.emplace();
    Read(&*ref.local_matrix_);
  }
  ReadSimple(&ref.center_);
  ReadSimple(&ref.tile_);
  ReadSimple(&ref.start_point_);
  ReadSimple(&ref.end_point_);
  ReadSimple(&ref.start_degrees_);
  ReadSimple(&ref.end_degrees_);
  Read(&ref.image_);
  bool has_record = false;
  ReadSimple(&has_record);
  uint32_t shader_id = PaintShader::kInvalidRecordShaderId;
  size_t shader_size = 0;
  if (has_record) {
    if (shader_type != PaintShader::Type::kPaintRecord) {
      SetInvalid(DeserializationError::kUnexpectedPaintShaderType);
      return;
    }
    Read(&shader_id);
    if (shader_id == PaintShader::kInvalidRecordShaderId) {
      SetInvalid(DeserializationError::kInvalidRecordShaderId);
      return;
    }

    // Track dependent transfer cache entries to make cached shader size
    // more realistic.
    size_t pre_size = options_.transfer_cache->GetTotalEntrySizes();
    size_t record_size = Read(&ref.record_);
    size_t post_size = options_.transfer_cache->GetTotalEntrySizes();
    shader_size = post_size - pre_size + record_size;

    ref.id_ = shader_id;
  }
  decltype(ref.colors_)::size_type colors_size = 0;
  ReadSize(&colors_size);

  // If there are too many colors, abort.
  if (colors_size > remaining_bytes_) {
    SetInvalid(DeserializationError::
                   kInsufficientRemainingBytes_Read_PaintShader_ColorSize);
    return;
  }
  size_t colors_bytes = colors_size * sizeof(SkColor);
  if (colors_bytes > remaining_bytes_) {
    SetInvalid(DeserializationError::
                   kInsufficientRemainingBytes_Read_PaintShader_ColorBytes);
    return;
  }
  ref.colors_.resize(colors_size);
  ReadData(colors_bytes, ref.colors_.data());

  decltype(ref.positions_)::size_type positions_size = 0;
  ReadSize(&positions_size);
  // Positions are optional. If they exist, they have the same count as colors.
  if (positions_size > 0 && positions_size != colors_size) {
    SetInvalid(DeserializationError::kInvalidPaintShaderPositionsSize);
    return;
  }
  size_t positions_bytes = positions_size * sizeof(SkScalar);
  if (positions_bytes > remaining_bytes_) {
    SetInvalid(DeserializationError::
                   kInsufficientRemainingBytes_Read_PaintShader_Positions);
    return;
  }
  ref.positions_.resize(positions_size);
  ReadData(positions_size * sizeof(SkScalar), ref.positions_.data());

  // We don't write the cached shader, so don't attempt to read it either.

  if (!(*shader)->IsValid()) {
    SetInvalid(DeserializationError::kInvalidPaintShader);
    return;
  }

  // All shader types but records are done.
  if (shader_type != PaintShader::Type::kPaintRecord) {
    (*shader)->ResolveSkObjects();
    return;
  }

  // Record shaders have shader ids.  Attempt to use cached versions of
  // these so that Skia can cache based on SkPictureShader::fUniqueId.
  // These shaders are always serialized (and assumed to not be large
  // records).  Handling this edge case in this roundabout way prevents
  // transfer cache entries from needing to depend on other transfer cache
  // entries.
  auto* entry =
      options_.transfer_cache->GetEntryAs<ServiceShaderTransferCacheEntry>(
          shader_id);
  // Only consider entries that use the same scale.  This limits the service
  // side transfer cache to only having one entry per shader but this will hit
  // the common case of enabling Skia reuse.
  if (entry && entry->shader()->tile_ == ref.tile_) {
    DCHECK(!ref.sk_cached_picture_);
    ref.sk_cached_picture_ = entry->shader()->sk_cached_picture_;
  } else {
    ref.ResolveSkObjects();
    DCHECK(ref.sk_cached_picture_);
    options_.transfer_cache->CreateLocalEntry(
        shader_id, std::make_unique<ServiceShaderTransferCacheEntry>(
                       *shader, shader_size));
  }
}

void PaintOpReader::Read(SkMatrix* matrix) {
  ReadSimple(matrix);
  FixupMatrixPostSerialization(matrix);
}

void PaintOpReader::Read(SkM44* matrix) {
  ReadSimple(matrix);
}

void PaintOpReader::Read(SkSamplingOptions* sampling) {
  bool useCubic;
  Read(&useCubic);
  if (useCubic) {
    SkCubicResampler cubic;
    Read(&cubic.B);
    Read(&cubic.C);
    *sampling = SkSamplingOptions(cubic);
  } else {
    SkFilterMode filter;
    SkMipmapMode mipmap;
    Read(&filter);
    Read(&mipmap);
    *sampling = SkSamplingOptions(filter, mipmap);
  }
}

void PaintOpReader::Read(SkYUVColorSpace* yuv_color_space) {
  uint32_t raw_yuv_color_space = kIdentity_SkYUVColorSpace;
  ReadSimple(&raw_yuv_color_space);

  if (raw_yuv_color_space > kLastEnum_SkYUVColorSpace) {
    SetInvalid(DeserializationError::kInvalidSkYUVColorSpace);
    return;
  }

  *yuv_color_space = static_cast<SkYUVColorSpace>(raw_yuv_color_space);
}

void PaintOpReader::Read(SkYUVAInfo::PlaneConfig* plane_config) {
  uint32_t raw_plane_config =
      static_cast<uint32_t>(SkYUVAInfo::PlaneConfig::kUnknown);
  ReadSimple(&raw_plane_config);

  if (raw_plane_config >
      static_cast<uint32_t>(SkYUVAInfo::PlaneConfig::kLast)) {
    SetInvalid(DeserializationError::kInvalidPlaneConfig);
    return;
  }

  *plane_config = static_cast<SkYUVAInfo::PlaneConfig>(raw_plane_config);
}

void PaintOpReader::Read(SkYUVAInfo::Subsampling* subsampling) {
  uint32_t raw_subsampling =
      static_cast<uint32_t>(SkYUVAInfo::Subsampling::kUnknown);
  ReadSimple(&raw_subsampling);

  if (raw_subsampling > static_cast<uint32_t>(SkYUVAInfo::Subsampling::kLast)) {
    SetInvalid(DeserializationError::kInvalidSubsampling);
    return;
  }

  *subsampling = static_cast<SkYUVAInfo::Subsampling>(raw_subsampling);
}

void PaintOpReader::Read(gpu::Mailbox* mailbox) {
  ReadData(sizeof(gpu::Mailbox::Name), (*mailbox).name);
}

void PaintOpReader::Read(scoped_refptr<SkottieWrapper>* skottie) {
  if (!options_.is_privileged) {
    valid_ = false;
    return;
  }

  uint32_t transfer_cache_entry_id;
  ReadSimple(&transfer_cache_entry_id);
  if (!valid_)
    return;
  auto* entry =
      options_.transfer_cache->GetEntryAs<ServiceSkottieTransferCacheEntry>(
          transfer_cache_entry_id);
  if (entry) {
    *skottie = entry->skottie();
  } else {
    valid_ = false;
  }

  size_t bytes_to_skip = 0u;
  ReadSize(&bytes_to_skip);
  if (!valid_)
    return;
  if (bytes_to_skip > remaining_bytes_) {
    valid_ = false;
    return;
  }
  memory_ += bytes_to_skip;
  remaining_bytes_ -= bytes_to_skip;
}

void PaintOpReader::AlignMemory(size_t alignment) {
  size_t padding = base::bits::AlignUp(memory_, alignment) - memory_;
  if (padding > remaining_bytes_)
    SetInvalid(DeserializationError::kInsufficientRemainingBytes_AlignMemory);

  memory_ += padding;
  remaining_bytes_ -= padding;
}

// Don't inline this function so that crash reports can show the caller.
NOINLINE void PaintOpReader::SetInvalid(DeserializationError error) {
  static crash_reporter::CrashKeyString<4> deserialization_error_crash_key(
      "PaintOpReader deserialization error");
  base::UmaHistogramEnumeration("GPU.PaintOpReader.DeserializationError",
                                error);
  if (valid_ && options_.crash_dump_on_failure && base::RandInt(1, 10) == 1) {
    crash_reporter::ScopedCrashKeyString crash_key_scope(
        &deserialization_error_crash_key,
        base::NumberToString(static_cast<int>(error)));
    base::debug::DumpWithoutCrashing();
  }
  valid_ = false;
}

const volatile void* PaintOpReader::ExtractReadableMemory(size_t bytes) {
  if (remaining_bytes_ < bytes)
    SetInvalid(DeserializationError::
                   kInsufficientRemainingBytes_ExtractReadableMemory);
  if (!valid_)
    return nullptr;
  if (bytes == 0)
    return nullptr;

  const volatile void* extracted_memory = memory_;
  memory_ += bytes;
  remaining_bytes_ -= bytes;
  return extracted_memory;
}

void PaintOpReader::Read(sk_sp<PaintFilter>* filter) {
  PaintFilter::Type type;
  ReadEnum(&type);
  if (!valid_)
    return;

  if (type == PaintFilter::Type::kNullFilter) {
    *filter = nullptr;
    return;
  }

  uint32_t has_crop_rect = 0;
  absl::optional<PaintFilter::CropRect> crop_rect;
  ReadSimple(&has_crop_rect);
  if (has_crop_rect) {
    SkRect rect = SkRect::MakeEmpty();
    ReadSimple(&rect);
    crop_rect.emplace(rect);
  }

  AlignMemory(4);
  switch (type) {
    case PaintFilter::Type::kNullFilter:
      NOTREACHED();
      break;
    case PaintFilter::Type::kColorFilter:
      ReadColorFilterPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kBlur:
      ReadBlurPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kDropShadow:
      ReadDropShadowPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kMagnifier:
      ReadMagnifierPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kCompose:
      ReadComposePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kAlphaThreshold:
      ReadAlphaThresholdPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kXfermode:
      ReadXfermodePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kArithmetic:
      ReadArithmeticPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kMatrixConvolution:
      ReadMatrixConvolutionPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kDisplacementMapEffect:
      ReadDisplacementMapEffectPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kImage:
      ReadImagePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kPaintRecord:
      ReadRecordPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kMerge:
      ReadMergePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kMorphology:
      ReadMorphologyPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kOffset:
      ReadOffsetPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kTile:
      ReadTilePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kTurbulence:
      ReadTurbulencePaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kShader:
      ReadShaderPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kMatrix:
      ReadMatrixPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kLightingDistant:
      ReadLightingDistantPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kLightingPoint:
      ReadLightingPointPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kLightingSpot:
      ReadLightingSpotPaintFilter(filter, crop_rect);
      break;
    case PaintFilter::Type::kStretch:
      ReadStretchPaintFilter(filter, crop_rect);
      break;
  }
}

void PaintOpReader::ReadColorFilterPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  sk_sp<SkColorFilter> color_filter;
  sk_sp<PaintFilter> input;

  ReadFlattenable(&color_filter, SkColorFilter::Deserialize,
                  DeserializationError::kSkColorFilterUnflattenFailure);
  Read(&input);
  if (!color_filter)
    SetInvalid(DeserializationError::kZeroSkColorFilterBytes);
  if (!valid_)
    return;
  filter->reset(new ColorFilterPaintFilter(std::move(color_filter),
                                           std::move(input),
                                           base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadBlurPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkScalar sigma_x = 0.f;
  SkScalar sigma_y = 0.f;
  SkTileMode tile_mode;
  sk_sp<PaintFilter> input;

  Read(&sigma_x);
  Read(&sigma_y);
  Read(&tile_mode);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new BlurPaintFilter(sigma_x, sigma_y, tile_mode,
                                    std::move(input),
                                    base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadDropShadowPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkScalar dx = 0.f;
  SkScalar dy = 0.f;
  SkScalar sigma_x = 0.f;
  SkScalar sigma_y = 0.f;
  SkColor color = SK_ColorBLACK;
  DropShadowPaintFilter::ShadowMode shadow_mode;
  sk_sp<PaintFilter> input;

  Read(&dx);
  Read(&dy);
  Read(&sigma_x);
  Read(&sigma_y);
  Read(&color);
  ReadEnum(&shadow_mode);
  Read(&input);

  if (!valid_)
    return;
  filter->reset(new DropShadowPaintFilter(dx, dy, sigma_x, sigma_y, color,
                                          shadow_mode, std::move(input),
                                          base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadMagnifierPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkRect src_rect = SkRect::MakeEmpty();
  SkScalar inset = 0.f;
  sk_sp<PaintFilter> input;

  Read(&src_rect);
  Read(&inset);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new MagnifierPaintFilter(src_rect, inset, std::move(input),
                                         base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadComposePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  sk_sp<PaintFilter> outer;
  sk_sp<PaintFilter> inner;

  Read(&outer);
  Read(&inner);
  if (!valid_)
    return;
  filter->reset(new ComposePaintFilter(std::move(outer), std::move(inner)));
}

void PaintOpReader::ReadAlphaThresholdPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkRegion region;
  SkScalar inner_min = 0.f;
  SkScalar outer_max = 0.f;
  sk_sp<PaintFilter> input;

  Read(&region);
  ReadSimple(&inner_min);
  ReadSimple(&outer_max);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new AlphaThresholdPaintFilter(
      region, inner_min, outer_max, std::move(input),
      base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadXfermodePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkBlendMode blend_mode;
  sk_sp<PaintFilter> background;
  sk_sp<PaintFilter> foreground;

  Read(&blend_mode);
  Read(&background);
  Read(&foreground);
  if (!valid_)
    return;

  filter->reset(new XfermodePaintFilter(blend_mode, std::move(background),
                                        std::move(foreground),
                                        base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadArithmeticPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  float k1 = 0.f;
  float k2 = 0.f;
  float k3 = 0.f;
  float k4 = 0.f;
  bool enforce_pm_color = false;
  sk_sp<PaintFilter> background;
  sk_sp<PaintFilter> foreground;
  Read(&k1);
  Read(&k2);
  Read(&k3);
  Read(&k4);
  Read(&enforce_pm_color);
  Read(&background);
  Read(&foreground);
  if (!valid_)
    return;
  filter->reset(new ArithmeticPaintFilter(
      k1, k2, k3, k4, enforce_pm_color, std::move(background),
      std::move(foreground), base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadMatrixConvolutionPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkISize kernel_size = SkISize::MakeEmpty();
  SkScalar gain = 0.f;
  SkScalar bias = 0.f;
  SkIPoint kernel_offset = SkIPoint::Make(0, 0);
  SkTileMode tile_mode;
  bool convolve_alpha = false;
  sk_sp<PaintFilter> input;

  ReadSimple(&kernel_size);
  if (!valid_)
    return;
  auto size =
      static_cast<size_t>(sk_64_mul(kernel_size.width(), kernel_size.height()));
  if (size > remaining_bytes_) {
    SetInvalid(
        DeserializationError::
            kInsufficientRemainingBytes_ReadMatrixConvolutionPaintFilter);
    return;
  }
  std::vector<SkScalar> kernel(size);
  for (size_t i = 0; i < size; ++i)
    Read(&kernel[i]);
  Read(&gain);
  Read(&bias);
  ReadSimple(&kernel_offset);
  Read(&tile_mode);
  Read(&convolve_alpha);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new MatrixConvolutionPaintFilter(
      kernel_size, kernel.data(), gain, bias, kernel_offset, tile_mode,
      convolve_alpha, std::move(input), base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadDisplacementMapEffectPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkColorChannel channel_x;
  SkColorChannel channel_y;
  SkScalar scale = 0.f;
  sk_sp<PaintFilter> displacement;
  sk_sp<PaintFilter> color;

  ReadEnum<SkColorChannel, SkColorChannel::kA>(&channel_x);
  ReadEnum<SkColorChannel, SkColorChannel::kA>(&channel_y);
  Read(&scale);
  Read(&displacement);
  Read(&color);

  if (!valid_)
    return;
  filter->reset(new DisplacementMapEffectPaintFilter(
      channel_x, channel_y, scale, std::move(displacement), std::move(color),
      base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadImagePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  PaintImage image;
  Read(&image);
  if (!image) {
    SetInvalid(DeserializationError::kReadImageFailure);
    return;
  }

  SkRect src_rect;
  Read(&src_rect);
  SkRect dst_rect;
  Read(&dst_rect);
  PaintFlags::FilterQuality quality;
  Read(&quality);

  if (!valid_)
    return;
  filter->reset(
      new ImagePaintFilter(std::move(image), src_rect, dst_rect, quality));
}

void PaintOpReader::ReadRecordPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  bool has_filter = false;
  ReadSimple(&has_filter);
  if (!has_filter) {
    *filter = nullptr;
    return;
  }

  SkRect record_bounds = SkRect::MakeEmpty();
  gfx::SizeF raster_scale = {0.f, 0.f};
  PaintShader::ScalingBehavior scaling_behavior =
      PaintShader::ScalingBehavior::kRasterAtScale;
  sk_sp<PaintRecord> record;

  ReadSimple(&record_bounds);
  ReadSimple(&raster_scale);
  if (raster_scale.width() <= 0.f || raster_scale.height() <= 0.f) {
    SetInvalid(DeserializationError::kInvalidRasterScale);
    return;
  }

  ReadSimple(&scaling_behavior);
  if (!IsValidPaintShaderScalingBehavior(scaling_behavior)) {
    SetInvalid(DeserializationError::kInvalidPaintShaderScalingBehavior);
    return;
  }

  // RecordPaintFilter also requires kRasterAtScale to have {1.f, 1.f} as the
  // raster_scale, since that is intended for kFixedScale
  if (scaling_behavior == PaintShader::ScalingBehavior::kRasterAtScale &&
      (raster_scale.width() != 1.f || raster_scale.height() != 1.f)) {
    SetInvalid(DeserializationError::kInvalidRasterScale);
    return;
  }

  Read(&record);
  if (!valid_)
    return;
  filter->reset(new RecordPaintFilter(std::move(record), record_bounds,
                                      raster_scale, scaling_behavior));
}

void PaintOpReader::ReadMergePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  size_t input_count = 0;
  ReadSize(&input_count);

  // The minimum size for a serialized filter is 4 bytes (a zero uint32_t to
  // indicate a null filter). Make sure the |input_count| doesn't exceed the
  // maximum number of filters possible for the remaining data.
  const size_t max_filters = remaining_bytes_ / 4u;
  if (input_count > max_filters)
    SetInvalid(DeserializationError::kPaintFilterHasTooManyInputs);
  if (!valid_)
    return;
  std::vector<sk_sp<PaintFilter>> inputs(input_count);
  for (auto& input : inputs)
    Read(&input);
  if (!valid_)
    return;
  filter->reset(new MergePaintFilter(inputs.data(),
                                     static_cast<int>(input_count),
                                     base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadMorphologyPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  MorphologyPaintFilter::MorphType morph_type;
  float radius_x = 0;
  float radius_y = 0;
  sk_sp<PaintFilter> input;
  ReadEnum(&morph_type);
  Read(&radius_x);
  Read(&radius_y);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new MorphologyPaintFilter(morph_type, radius_x, radius_y,
                                          std::move(input),
                                          base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadOffsetPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkScalar dx = 0.f;
  SkScalar dy = 0.f;
  sk_sp<PaintFilter> input;

  Read(&dx);
  Read(&dy);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new OffsetPaintFilter(dx, dy, std::move(input),
                                      base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadTilePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkRect src = SkRect::MakeEmpty();
  SkRect dst = SkRect::MakeEmpty();
  sk_sp<PaintFilter> input;

  Read(&src);
  Read(&dst);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new TilePaintFilter(src, dst, std::move(input)));
}

void PaintOpReader::ReadTurbulencePaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  TurbulencePaintFilter::TurbulenceType turbulence_type;
  SkScalar base_frequency_x = 0.f;
  SkScalar base_frequency_y = 0.f;
  int num_octaves = 0;
  SkScalar seed = 0.f;
  SkISize tile_size = SkISize::MakeEmpty();

  ReadEnum(&turbulence_type);
  Read(&base_frequency_x);
  Read(&base_frequency_y);
  Read(&num_octaves);
  Read(&seed);
  ReadSimple(&tile_size);
  if (!valid_)
    return;
  filter->reset(new TurbulencePaintFilter(
      turbulence_type, base_frequency_x, base_frequency_y, num_octaves, seed,
      &tile_size, base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadShaderPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  using Dither = SkImageFilters::Dither;

  sk_sp<PaintShader> shader;
  uint8_t alpha = 255;
  PaintFlags::FilterQuality quality = PaintFlags::FilterQuality::kNone;
  Dither dither = Dither::kNo;

  Read(&shader);
  Read(&alpha);
  Read(&quality);
  ReadEnum<Dither, Dither::kYes>(&dither);

  if (!shader || !valid_)
    return;

  filter->reset(new ShaderPaintFilter(std::move(shader), alpha, quality, dither,
                                      base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadMatrixPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkMatrix matrix = SkMatrix::I();
  PaintFlags::FilterQuality filter_quality = PaintFlags::FilterQuality::kNone;
  sk_sp<PaintFilter> input;

  Read(&matrix);
  Read(&filter_quality);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(
      new MatrixPaintFilter(matrix, filter_quality, std::move(input)));
}

void PaintOpReader::ReadLightingDistantPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  PaintFilter::LightingType lighting_type;
  SkPoint3 direction = SkPoint3::Make(0.f, 0.f, 0.f);
  SkColor light_color = SK_ColorBLACK;
  SkScalar surface_scale = 0.f;
  SkScalar kconstant = 0.f;
  SkScalar shininess = 0.f;
  sk_sp<PaintFilter> input;

  ReadEnum(&lighting_type);
  ReadSimple(&direction);
  Read(&light_color);
  Read(&surface_scale);
  Read(&kconstant);
  Read(&shininess);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new LightingDistantPaintFilter(
      lighting_type, direction, light_color, surface_scale, kconstant,
      shininess, std::move(input), base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadLightingPointPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  PaintFilter::LightingType lighting_type;
  SkPoint3 location = SkPoint3::Make(0.f, 0.f, 0.f);
  SkColor light_color = SK_ColorBLACK;
  SkScalar surface_scale = 0.f;
  SkScalar kconstant = 0.f;
  SkScalar shininess = 0.f;
  sk_sp<PaintFilter> input;

  ReadEnum(&lighting_type);
  ReadSimple(&location);
  Read(&light_color);
  Read(&surface_scale);
  Read(&kconstant);
  Read(&shininess);
  Read(&input);
  if (!valid_)
    return;
  filter->reset(new LightingPointPaintFilter(
      lighting_type, location, light_color, surface_scale, kconstant, shininess,
      std::move(input), base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadLightingSpotPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  PaintFilter::LightingType lighting_type;
  SkPoint3 location = SkPoint3::Make(0.f, 0.f, 0.f);
  SkPoint3 target = SkPoint3::Make(0.f, 0.f, 0.f);
  SkScalar specular_exponent = 0.f;
  SkScalar cutoff_angle = 0.f;
  SkColor light_color = SK_ColorBLACK;
  SkScalar surface_scale = 0.f;
  SkScalar kconstant = 0.f;
  SkScalar shininess = 0.f;
  sk_sp<PaintFilter> input;

  ReadEnum(&lighting_type);
  ReadSimple(&location);
  ReadSimple(&target);
  Read(&specular_exponent);
  Read(&cutoff_angle);
  Read(&light_color);
  Read(&surface_scale);
  Read(&kconstant);
  Read(&shininess);
  Read(&input);

  if (!valid_)
    return;
  filter->reset(new LightingSpotPaintFilter(
      lighting_type, location, target, specular_exponent, cutoff_angle,
      light_color, surface_scale, kconstant, shininess, std::move(input),
      base::OptionalOrNullptr(crop_rect)));
}

void PaintOpReader::ReadStretchPaintFilter(
    sk_sp<PaintFilter>* filter,
    const absl::optional<PaintFilter::CropRect>& crop_rect) {
  SkScalar stretch_x = 0.f;
  SkScalar stretch_y = 0.f;
  SkScalar width = 0.f;
  SkScalar height = 0.f;
  sk_sp<PaintFilter> input;

  Read(&stretch_x);
  Read(&stretch_y);
  Read(&width);
  Read(&height);
  Read(&input);

  if (!valid_)
    return;
  filter->reset(new StretchPaintFilter(stretch_x, stretch_y, width, height,
                                       std::move(input),
                                       base::OptionalOrNullptr(crop_rect)));
}

size_t PaintOpReader::Read(sk_sp<PaintRecord>* record) {
  size_t size_bytes = 0;
  ReadSize(&size_bytes);
  AlignMemory(PaintOpBuffer::PaintOpAlign);
  if (enable_security_constraints_) {
    // Validate that the record was not serialized if security constraints are
    // enabled.
    if (size_bytes != 0) {
      SetInvalid(DeserializationError::kPaintRecordForbidden);
      return 0;
    }
    *record = sk_make_sp<PaintOpBuffer>();
    return 0;
  }

  if (size_bytes > remaining_bytes_)
    SetInvalid(
        DeserializationError::kInsufficientRemainingBytes_Read_PaintRecord);
  if (!valid_)
    return 0;

  *record = PaintOpBuffer::MakeFromMemory(memory_, size_bytes, options_);
  if (!*record) {
    SetInvalid(DeserializationError::kPaintOpBufferMakeFromMemoryFailure);
    return 0;
  }
  memory_ += size_bytes;
  remaining_bytes_ -= size_bytes;
  return size_bytes;
}

void PaintOpReader::Read(SkRegion* region) {
  size_t region_bytes = 0;
  ReadSize(&region_bytes);
  if (region_bytes == 0)
    SetInvalid(DeserializationError::kZeroRegionBytes);
  if (region_bytes > remaining_bytes_)
    SetInvalid(DeserializationError::kInsufficientRemainingBytes_Read_SkRegion);
  if (!valid_)
    return;
  std::unique_ptr<char[]> data(new char[region_bytes]);
  ReadData(region_bytes, data.get());
  if (!valid_)
    return;
  size_t result = region->readFromMemory(data.get(), region_bytes);
  if (!result)
    SetInvalid(DeserializationError::kSkRegionReadFromMemoryFailure);
}

}  // namespace cc


text:
using Cake.Storm.Fluent.Interfaces;

namespace Cake.Storm.Fluent.Steps
{
	[MultiStep]
	[PreCleanStep] [CleanStep] [PostCleanStep]
	[PreBuildStep] [BuildStep] [PostBuildStep]
	[PreReleaseStep] [ReleaseStep] [PostReleaseStep]
	[PreDeployStep] [DeployStep] [PostDeployStep]
	public abstract class BaseMultipleStep : IStep
	{
		private readonly StepType _onStep;

		protected BaseMultipleStep(StepType onStep)
		{
			_onStep = onStep;
		}

		public void Execute(IConfiguration configuration, StepType currentStep)
		{
			if (currentStep == _onStep)
			{
				Execute(configuration);
			}
		}

		protected abstract void Execute(IConfiguration configuration);
	}
}


text:
#ifndef NCLOG_H
#define NCLOG_H

#include <stdarg.h>
#include "ncexternl.h"

#ifndef NCCATCH
#undef NCCATCH
#endif

#define NCENVLOGGING "NCLOGGING"
#define NCENVTRACING "NCTRACING"

/* Suggested tag values */
#define NCLOGNOTE 0
#define NCLOGWARN 1
#define NCLOGERR 2
#define NCLOGDBG 3

#if defined(_CPLUSPLUS_) || defined(__CPLUSPLUS__)
extern "C" {
#endif

EXTERNL void ncloginit(void);
EXTERNL int ncsetlogging(int tf);
EXTERNL int nclogopen(FILE* stream);

/* The tag value is an arbitrary integer */
EXTERNL void nclog(int tag, const char* fmt, ...);
EXTERNL int ncvlog(int tag, const char* fmt, va_list ap);
EXTERNL void nclogtext(int tag, const char* text);
EXTERNL void nclogtextn(int tag, const char* text, size_t count);

/* Trace support */
EXTERNL int nctracelevel(int level);
EXTERNL void nctrace(int level, const char* fcn, const char* fmt, ...);
EXTERNL void nctracemore(int level, const char* fmt, ...);
EXTERNL void ncvtrace(int level, const char* fcn, const char* fmt, va_list ap);
EXTERNL int ncuntrace(const char* fcn, int err,const char* fmt,...);
EXTERNL int ncthrow(int err,const char* file,int line);
EXTERNL int ncbreakpoint(int err);

/* Debug support */
#if defined(NCCATCH)
#define NCTHROW(e) ((e) == NC_NOERR ? (e) : ncthrow(e,__FILE__,__LINE__))
#else
#define NCTHROW(e) (e)
#endif

#ifdef HAVE_EXECINFO_H
EXTERNL void ncbacktrace(void);
#else
#define ncbacktrace()
#endif

#if defined(_CPLUSPLUS_) || defined(__CPLUSPLUS__)
}
#endif

#endif /*NCLOG_H*/


text:
package com.google.common.css.compiler.ast;

import com.google.common.css.compiler.ast.testing.FunctionalTestCommonBase;
import com.google.common.css.compiler.ast.testing.NewFunctionalTestBase;
import com.google.common.css.compiler.passes.CreateComponentNodes;
import com.google.common.css.compiler.passes.CreateConditionalNodes;
import com.google.common.css.compiler.passes.CreateDefinitionNodes;
import com.google.common.css.compiler.passes.PrettyPrinter;

/**
 * Utility methods for all of the functional tests.
 *
 * @author oana@google.com (Oana Florescu)
 */
public class FunctionalTestBase extends FunctionalTestCommonBase {

  protected CssTree newTree = null;
  protected NewFunctionalTestBase newTestBase;

  /**
   * Utility method that given an input string parses it using the CssParser and
   * then converts it into a CssTree object.
   *
   * @param sourceCode A string representing the css input for the parser
   */
  @Override
  protected void parseAndBuildTree(String sourceCode) {
    buildTreeWithNewParser(sourceCode);
    runPassesOnNewTree();
  }

  protected void runPassesOnNewTree() {
    CreateDefinitionNodes pass1 = new CreateDefinitionNodes(
        newTree.getMutatingVisitController(), newTestBase.getErrorManager());
    pass1.runPass();
    CreateConditionalNodes pass2 = new CreateConditionalNodes(
        newTree.getMutatingVisitController(), newTestBase.getErrorManager());
    pass2.runPass();
    CreateComponentNodes pass3 = new CreateComponentNodes(
        newTree.getMutatingVisitController(), newTestBase.getErrorManager());
    pass3.runPass();
  }

  protected String getPrettyPrintedTree(CssTree tree) {
    PrettyPrinter prettyPrinter = new PrettyPrinter(tree.getVisitController());
    prettyPrinter.setStripQuotes(true);
    prettyPrinter.runPass();
    return prettyPrinter.getPrettyPrintedString();
  }

  protected void buildTreeWithNewParser(String sourceCode) {
    newTestBase = new NewFunctionalTestBase();
    newTestBase.parseAndBuildTree(sourceCode);
    newTree = newTestBase.getTree();
    tree = newTestBase.getTree();
  }

}


text:
<?php
namespace Hip\MandrillBundle;

class Dispatcher
{
    /**
     * Mandrill service
     *
     * @var \Mandrill $service
     */
    protected $service;

    /**
     * Default Sender Email
     *
     * @var string
     */
    protected $defaultSender;

    /**
     * Default subaccount
     *
     * @var string
     */
    protected $subaccount;

    /**
     * Default Sender Name
     *
     * @var string
     */
    protected $defaultSenderName;

    /**
     * Proxy options
     *
     * @var array
     */
    protected $proxy;

    /**
     * @var bool
     */
    protected $disableDelivery;

    public function __construct($service, $defaultSender, $defaultSenderName, $subaccount, $disableDelivery, $proxy, $debug = false)
    {
        $this->service = $service;
        $this->defaultSender = $defaultSender;
        $this->defaultSenderName = $defaultSenderName;
        $this->subaccount = $subaccount;
        $this->disableDelivery = $disableDelivery;
        $this->proxy = $proxy;

        $this->service->debug = $debug;

        if ($this->useProxy()) {
            $this->addCurlProxyOptions();
        }
    }

    /**
     * Send a message
     *
     * @param Message $message
     * @param string $templateName
     * @param array $templateContent
     * @param bool $async
     * @param string $ipPool
     * @param string $sendAt
     *
     * @return array|bool
     */
    public function send(Message $message, $templateName = '', $templateContent = array(), $async = false, $ipPool = null, $sendAt = null)
    {
        if ($this->disableDelivery) {
            return false;
        }

        if (strlen($message->getFromEmail()) == 0) {
            $message->setFromEmail($this->defaultSender);
        }

        if (strlen($message->getFromName()) == 0 && null !== $this->defaultSenderName) {
            $message->setFromName($this->defaultSenderName);
        }

        if (strlen($message->getSubaccount()) == 0 && null !== $this->subaccount) {
            $message->setSubaccount($this->subaccount);
        }

        if (!empty($templateName)) {
            return $this->service->messages->sendTemplate($templateName, $templateContent, $message->toArray(), $async, $ipPool, $sendAt);
        }

        return $this->service->messages->send($message->toArray(), $async, $ipPool, $sendAt);
    }

    /**
     * Get Mandrill service
     *
     * @return \Mandrill
     */
    public function getService()
    {
        return $this->service;
    }

    private function useProxy()
    {
        return $this->proxy['use'];
    }

    private function addCurlProxyOptions()
    {
        if ($this->proxy['host'] !== null) {
            curl_setopt($this->service->ch, CURLOPT_PROXY, $this->proxy['host']);
        }

        if ($this->proxy['port'] !== null) {
            curl_setopt($this->service->ch, CURLOPT_PROXYPORT, $this->proxy['port']);
        }

        if ($this->proxy['user'] !== null && $this->proxy['password'] !== null) {
            curl_setopt($this->service->ch, CURLOPT_PROXYUSERPWD, sprintf(
                '%s:%s',
                $this->proxy['user'],
                $this->proxy['password']
            ));
        }
    }
}


text:
================================================================================
VirtualSCSIPassthroughDeviceBackingInfo
================================================================================

.. describe:: Extends

    :py:class:`~pyvisdk.mo.virtual_device_device_backing_info.VirtualDeviceDeviceBackingInfo`

.. class:: pyvisdk.do.virtual_scsi_passthrough_device_backing_info.VirtualSCSIPassthroughDeviceBackingInfo


text:
Rakudobrew Bash Completion
==========================

Bash autocompletion for
[rakudobrew](https://github.com/tadzik/rakudobrew).

Installation
------------

```sh
sudo wget https://raw.github.com/kusabashira/rakudobrew-bash-completion/master/rakudobrew.bash -O /etc/bash_completion.d/rakudobrew.bash
```

License
-------

MIT License

Author
------

kusabashira <kusabashira227@gmail.com>


text:
layout: page
title: Default Credentials
permalink: /docs/en-US/default-credentials/
---

All database usernames and passwords for WordPress installations included by default are:

__User:__ `wp`
__Password:__ `wp`

All WordPress admin usernames and passwords for WordPress installations included by default are:

__User:__ `admin`
__Password:__ `password`

MySQL Root:

__User:__ `root`
__Password:__ `root`

See: [Connecting to MySQL](https://github.com/varying-vagrant-vagrants/vvv/wiki/Connecting-to-MySQL) from your local machine

Vagrant Box Ubuntu Root:

__User:__ `root`
__Password:__ `vagrant`

#### WordPress Stable
* LOCAL PATH: vagrant-local/www/wordpress-default
* VM PATH: /srv/www/wordpress-default
* URL: `http://local.wordpress.dev`
* DB Name: `wordpress_default`

#### WordPress Develop
* LOCAL PATH: vagrant-local/www/wordpress-develop
* VM PATH: /srv/www/wordpress-develop
* /src URL: `http://src.wordpress-develop.dev`
* /build URL: `http://build.wordpress-develop.dev`
* DB Name: `wordpress_develop`
* DB Name: `wordpress_unit_tests`


text:
classdef TestFastNlMeansDenoisingColored
    %TestFastNlMeansDenoisingColored
    properties (Constant)
        im = imread(fullfile(mexopencv.root(),'test','lena.jpg'));
    end

    methods (Static)
        function test_1
            img = imnoise(TestFastNlMeansDenoisingColored.im, 'gaussian');
            out = cv.fastNlMeansDenoisingColored(img, 'H',10, 'HColor',10);
            validateattributes(out, {class(img)}, {'size',size(img)});
        end

        function test_error_1
            try
                cv.fastNlMeansDenoisingColored();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using VSLangProj;
using System.IO;
using Microsoft.Practices.ComponentModel;

namespace SPALM.SPSF.Library.Editors
{
  [ServiceDependency(typeof(DTE))]
  public partial class SelectLayoutFileForm : Form
  {
    public string selectedPath = "";

    public SelectLayoutFileForm()
    {
      InitializeComponent();
    }

    public SelectLayoutFileForm(DTE envdte, object currentselection)
    {
      InitializeComponent();

      try
      {
        LoadTree(envdte);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
    }

    private void LoadTree(DTE envdte)
    {
      treeView1.Nodes.Clear();

      foreach (Project project in envdte.Solution.Projects)
      {
        if (project.Object is SolutionFolder)
        {
          SolutionFolder x = (SolutionFolder)project.Object;
          foreach (ProjectItem pitem in x.Parent.ProjectItems)
          {
            if (pitem.Object != null)
            {
              if (pitem.Object is Project)
              {
                LoadProject(pitem.Object as Project);
              }
            }
          }
        }
        else
        {
          LoadProject(project);
        }
      }
    }

    private void LoadProject(Project project)
    {
      Load12Hive(project);
    }

    private void Load12Hive(Project project)
    {
      ProjectItem layoutsFolder = null;
      ProjectItem imagesFolder = null;
			ProjectItem adminFolder = null;

      try
      {
        layoutsFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Layouts");
      }
      catch (Exception)
      {
      }

      try
      {
				imagesFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Images");
      }
      catch (Exception)
      {
      }

			try
			{
				adminFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Admin");
			}
			catch (Exception)
			{
			}

			if ((layoutsFolder != null) || (imagesFolder != null) || (adminFolder != null))
      {
        TreeNode node = treeView1.Nodes.Add(project.Name);
        node.Tag = project;
        node.ImageKey = "Folder";
        node.SelectedImageKey = "Folder";

        if (layoutsFolder != null)
        {
          TreeNode nodelayouts = new TreeNode("Layouts");
          nodelayouts.Tag = layoutsFolder;
          node.Nodes.Add(nodelayouts);
          SetIcon(nodelayouts, layoutsFolder);
          LoadItems(layoutsFolder, nodelayouts);
        }

        if (imagesFolder != null)
        {
          TreeNode nodelayouts = new TreeNode("Images");
          nodelayouts.Tag = imagesFolder;
          node.Nodes.Add(nodelayouts);
          SetIcon(nodelayouts, layoutsFolder);
          LoadItems(imagesFolder, nodelayouts);
        }

				if (adminFolder != null)
				{
					TreeNode nodelayouts = new TreeNode("Admin");
					nodelayouts.Tag = adminFolder;
					node.Nodes.Add(nodelayouts);
					SetIcon(nodelayouts, adminFolder);
					LoadItems(adminFolder, nodelayouts);
				}
      }
    }

    private void SetIcon(TreeNode nodelayouts, ProjectItem item)
    {
			if (item != null)
			{
				if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
				{
					try
					{
						switch (Path.GetExtension(item.get_FileNames(1)))
						{
							case ".ascx":
							case ".asmx":
							case ".aspx":
							case ".htm":
							case ".html":
								nodelayouts.ImageKey = "Page";
								nodelayouts.SelectedImageKey = "Picture";
								return;
							case ".jpg":
							case ".jpeg":
							case ".gif":
							case ".png":
							case ".bmp":
								nodelayouts.ImageKey = "Picture";
								nodelayouts.SelectedImageKey = "Picture";
								return;
							default:
								nodelayouts.ImageKey = "Document";
								nodelayouts.SelectedImageKey = "Document";
								return;
						}
					}
					catch (Exception)
					{
						nodelayouts.ImageKey = "Document";
						nodelayouts.SelectedImageKey = "Document";
					}
				}
				else
				{
					nodelayouts.ImageKey = "Folder";
					nodelayouts.SelectedImageKey = "Folder";
				}
			}
			else
			{
				nodelayouts.ImageKey = "Folder";
				nodelayouts.SelectedImageKey = "Folder";
			}
    }

    private void LoadItems(ProjectItem p, TreeNode parentNode)
    {
      foreach (ProjectItem child in p.ProjectItems)
      {
        TreeNode node = parentNode.Nodes.Add(child.Name);
        node.Tag = child;
        SetIcon(node, child);
        LoadItems(child, node);
      }
    }

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
      if (e.Node.Tag != null)
      {
        if (e.Node.Tag is ProjectItem)
        {
          ProjectItem pitem = e.Node.Tag as ProjectItem;
          if (pitem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
          {
            SetText(e.Node.FullPath);
            return;
          }
        }
      }
      textBox1.Text = "";
    }

    private void SetText(string path)
    {
        DTE service = (DTE)this.GetService(typeof(DTE));

      //remove
      path = path.Substring(path.IndexOf("/")).ToLower();
      if (path.StartsWith("/layouts/"))
      {
          path = path.Replace("/layouts/", "/_layouts" + Helpers.GetVersionedFolder(service) + "/");
      }
      if (path.StartsWith("/images/"))
      {
          path = path.Replace("/images/", "/_layouts" + Helpers.GetVersionedFolder(service) + "/images/");
      }
			if (path.StartsWith("/admin/"))
			{
				path = path.Replace("/admin/", "/_admin/");
			}
      textBox1.Text = path;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      if (textBox1.Text != "")
      {
        button_ok.Enabled = true;
      }
      else
      {
        button_ok.Enabled = false;
      }
    }

    private void buttonOK_Click(object sender, EventArgs e)
    {
      selectedPath = textBox1.Text;
      Close();
    }
  }
}