text:
<?php
namespace MCPI;

use Exception;

/**
 * Transaction Controller
 */
class Transaction_Controller extends Core_Controller_Abstract
{

    const DIR_UPLOAD = DIR_UPLOAD . 'transaction' . DS;
    const DIR_FILE = DIR_TMP . 'file' . DS;

    static public function route()
    {
        $request = self::getRequest();
        $response = self::getResponse();
        $budget_menu = self::getBudgetMenu();

        if ($request->index(0,'transaction'))
        {
            $transaction_model = new Transaction_Model();
            $response->main_data['show_menu'] = true;

            // List
            if (empty($request->index(1)) or $request->index(1,'list'))
            {
                $response->menu['transaction']['class'] = 'active';
                $response->main_data['show_transaction_buttons'] = true;
                self::getDateFilter()->enable();
                self::getBudgetMenu()->enable();

                $response->body_template = 'transaction_list';
                $response->body_data = [
                    'category' => $transaction_model->getCategory(),
                    'show_all_url' => $request->url(null, ['category' => null]),
                    'transactions' => array_values($transaction_model->getListing()),
                ];
            }

            // Image Form?
            if ($request->index(1,'image'))
            {
                if ($request->file('image'))
                {
                    self::processImage($request->file('image'), $response);
                }

                $response->body_template = 'transaction_image';
            }

            // Text Form?
            if ($request->index(1,'text'))
            {
                $extra_data = [];
                $text = false;
                $action = 'render';

                if ($request->post('text'))
                {
                    $text = $request->post('text');
                }
                else
                {
                    $data = $request->body;
                    $page_title = $data['page_title'];
                    $page_url = $data['page_url'];
                    $text = $data['selection'];

                    $extra_data['notes'] = "Page:\n$page_title\n\n";
                    $extra_data['notes'].= "URL:\n$page_url";

                    if (!empty($data['app_window']))
                    {
                        $extra_data['app_window'] = 1;
                    }
                }

                if (!empty($text))
                {
                    self::processText($text, $response, $extra_data);
                }

                $response->body_template = 'transaction_text';
            }

            // Standard Form?
            if ($request->index(1,'form'))
            {

                // Start with defaults
                $body_data = [
                    // Will change if editing
                    'form_title' => 'New Transaction',
					'are_duplicates' => '',
                ];

                // posted data? try to save
                if ($request->post())
                {
                    $body_data["duplicates"] = self::processForm($request, $response);
                }

                // Load from DB if applicable
                $id = $request->get('id');
                if ($id)
                {
                    $db_data = Transaction_Model::getById($id);
                    if (empty($db_data[$id]))
                    {
                        $response->fail("Transaction id '$id' not found.", '404');
                    }
                    else
                    {
                        $body_data['form_title'] = 'Edit Transaction';
                        $body_data = array_merge($body_data, $db_data[$id]);
                        $body_data['repeat'] = Transaction_Recurrance_Controller::getFormData($id);
                    }
                }

                // Merge in get data
                if ($request->get())
                {
                    $body_data = array_merge($body_data, $_GET);
                }

                // Merge in post data
                if ($request->post())
                {
                    $body_data = array_merge($body_data, $_POST);
                }

                $account_options = Account_Model::getGroupedAccounts();

                // OCR if applicable
                $image = empty($body_data['image']) ? false : $body_data['image'];
                $file = empty($body_data['file']) ? false : $body_data['file'];

                $image_or_file = $image ? $image : $file;
                $dir = $image ? self::DIR_UPLOAD : self::DIR_FILE;

                $body_data['amount_options'] = [];
                if (!empty($body_data['amount']))
                {
                    $amount = number_format((float) $body_data['amount'], 2, '.', '');
                    $body_data['amount_options'][$amount]= [
                        'amount' => $amount,
                    ];
                }

				$option_sort_callbacks = [];

                if ($image_or_file)
                {
                    // Load from cache (ran on original image)
                    $ocr = new OCR_Model(
                        $image ? ($dir . $image) : false,
                        $file ? ($dir . $file) : false
                    );
                    $ocr_text = join(EOL, $ocr->getText());
                    $body_data['ocr-text'] = $ocr_text;

                    if (empty($body_data['amount']))
                    {
                        $dollars = $ocr->getDollars();
                        if (!empty($dollars))
                        {
                            $body_data['amount'] = number_format((float) max($dollars), 2, '.', '');

                            $dollars = array_unique($dollars);
                            array_map(function ($amount) {
                                return number_format((float) $amount, 2, '.', '');
                            }, $dollars);
                            rsort($dollars);

                            foreach ($dollars as $amount)
                            {
                                $body_data['amount_options'][$amount] = [
                                    'amount' => $amount
                                ];
                            }
                        }
                    }
                    else
                    {
                        $amount = number_format((float) $body_data['amount'], 2, '.', '');
                        $body_data['amount'] = $amount;
                        $body_data['amount_options'][$amount] = [
                            'amount' => $amount
                        ];
                    }

                    // Use the most recent valid date found (if any)
                    if (empty($body_data['date_occurred']))
                    {
                        $dates = $ocr->getDates();
                        $latest_time = 0;
                        $now = time();
                        if (!empty($dates))
                        {
                            foreach ($dates as $date)
                            {
                                $time = strtotime($date);

                                // Going for latest time found
                                if (false !== $time and $time > $latest_time /*and $time <= $now*/)
                                {
                                    $latest_time = $time;
                                }
                            }
                        }
                        if ($latest_time)
                        {
                            $body_data['date_occurred'] = date('Y-m-d', $latest_time);
                        }
                    }

                    // Account From
                    // Use first valid account found (if any)
                    if (empty($body_data['account_from']))
                    {
                        $account_numbers = $ocr->getPattern('[^/\d](\d{4})($|\D)', 1);
                        if (!empty($account_numbers))
                        {
                            $account_map = Account_Model::getNumberMap();
                            if (!empty($account_map))
                            {
                                foreach ($account_numbers as $number)
                                {
                                    if (isset($account_map[$number]))
                                    {
                                        $body_data['account_from'] = $account_map[$number]['id'];
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    // Check for valid account names which could indicate
                    //  the transaction recipient
					$account_to_matches = [];
                    if (empty($body_data['account_to']))
                    {
                        $lower_text = strtolower($ocr_text);

						// 0 - group => Bank Account
						// 1 - group => Credit Card
						// 2 - group => Other
                        foreach($account_options[2]['options'] as $option)
                        {
							$exact_matches = 0;
							$lower_title = strtolower($option['title']);

							// Look for an exact match (loosely - based on word characters)
                            $pattern = $lower_title;
                            $pattern = preg_replace("/[^\w]+/", "\b[^\w]*\b", $pattern);
                            $pattern = "/\b$pattern\b/";
                            if (preg_match_all($pattern, $lower_text, $matches))
                            {
								$exact_matches = count($matches[0]);
                            }

							// Split account title over spaces and punctuation
							$words = preg_split("/[^0-9a-z]/", $lower_title);

							// Note number & percentage of words matched
							$matched_words = [];
							$unmatched_words = [];
							$matched_words_count = 0;
							$matchable_words_count = 0;

							// Note number & percentage of characters matched
							$matched_chars_count = 0;
							$matchable_chars_count = 0;

							foreach ($words as $word)
							{
								// Skip empty strings
								if (strlen($word) < 1) {
									continue;
								}

								$chars = strlen($word);

								$matchable_words_count++;
								$matchable_chars_count+= $chars;

								// Check if we already know it's a match
								if (in_array($word, $matched_words) or $exact_matches > 0) {
									$matched_words_count++;
									$matched_chars_count+= $chars;
									continue;
								}

								if (in_array($word, $unmatched_words)) {
									continue;
								}

								if (preg_match("/\b".$word."\b/", $lower_text)) {
									$matched_words[]= $word;
									$matched_words_count++;
									$matched_chars_count+= $chars;
									continue;
								}

								$unmatched_words[]= $word;
							} // end looping through all words

							$matched_words_percent = empty($matchable_words_count) ? 0 : $matched_words_count / ($matchable_words_count ?? 1);
							$matched_chars_percent = empty($matchable_chars_count) ? 0 : $matched_chars_count / ($matchable_chars_count ?? 1);

							if ($matched_words_count > 0) {
								$account_to_matches[]= [
									'exact_matches' => $exact_matches,
									'matched_words' => $matched_words,
									'matched_words_count' => $matched_words_count,
									'matched_chars_count' => $matched_chars_count,
									'matched_words_percent' => $matched_words_percent,
									'matched_chars_percent' => $matched_chars_percent,
									'option_id' => $option['id'],
									'option' => $option,
								];
							}

                        } // endforeach - looping through all "other" accounts

						if (!empty($account_to_matches)) {

							// Sort by best matches
							usort($account_to_matches, function ($a, $b) {
								if ($a['exact_matches'] !== $b['exact_matches']) {
									return $b['exact_matches'] <=> $a['exact_matches'];
								}
								if ($a['matched_words_count'] !== $b['matched_words_count']) {
									return $b['matched_words_count'] <=> $a['matched_words_count'];
								}
								if ($a['matched_chars_count'] !== $b['matched_chars_count']) {
									return $b['matched_chars_count'] <=> $a['matched_chars_count'];
								}
								if ($a['matched_words_percent'] !== $b['matched_words_percent']) {
									return $b['matched_words_percent'] <=> $a['matched_words_percent'];
								}
								if ($a['matched_chars_percent'] !== $b['matched_chars_percent']) {
									return $b['matched_chars_percent'] <=> $a['matched_chars_percent'];
								}
							});

							if ( false !== strpos($lower_text, '__debug_account_matching__') ) {
								// Show a table output to test out sorting
								echo "

";
									echo "Option	";
									echo "Exact Match	";
									echo "Matched Words	";
									echo "Word # Match	";
									echo "Word % Match	";
									echo "Char # Match	";
									echo "Char % Match	";
								echo "
";
								foreach ($account_to_matches as $row) {
									echo "
";
										echo "" . $row['option']['title'] . " (". $row['option_id'] .")	";
										echo "" . $row['exact_matches'] . "	";
										echo "" . implode(",", $row['matched_words']) . "	";
										echo "" . $row['matched_words_count'] . "	";
										echo "" . $row['matched_words_percent'] . "	";
										echo "" . $row['matched_chars_count'] . "	";
										echo "" . $row['matched_chars_percent'] . "	";
									echo "
";
								}
								echo "
";
							}

							// Set best match and other matches for ordering
							$body_data['account_to'] = $account_to_matches[0]['option_id'];
							$sorted_option_ids = array_column($account_to_matches, 'option_id');
							$sorted_option_ids = array_flip($sorted_option_ids);

							// Sort "Other" accounts
							$option_sort_callbacks['account_to'][2] = function ($a, $b) use ($sorted_option_ids) {
								$a_id = $a['id'];
								$a_order = isset($sorted_option_ids[$a_id]) ? $sorted_option_ids[$a_id] : null;
								$b_id = $b['id'];
								$b_order = isset($sorted_option_ids[$b_id]) ? $sorted_option_ids[$b_id] : null;

								// Same order index? then sort by name
								if ($a_order === $b_order) {
									return strnatcmp($a['title'], $b['title']);
								}

								// a is a match and b is not
								if ( !is_null($a_order) and is_null($b_order)) {
									return -1;
								}

								// b is a match and a is not
								if ( !is_null($b_order) and is_null($a_order)) {
									return 1;
								}

								// Sort by their order
								return $a_order <=> $b_order;

							};
						}

                    } // End if - auto-detecting account_to

                } // End if - processing image or file

                // Options always needed for template
				$options = $transaction_model->getOptions($body_data, $option_sort_callbacks);

                $body_data = array_merge($body_data, $options);

                // Prep the date for field
                $date = empty($body_data['date_occurred']) ? false : strtotime($body_data['date_occurred']);
                $body_data['date_occurred'] = $date ? date('Y-m-d', $date) : "";

                $body_data['today_datestamp'] = date('Y-m-d');
                $body_data['yesterday_datestamp'] = date('Y-m-d', strtotime('yesterday'));

                // Debug data behind the form
                if (isset($_GET['debug_body_data'])){
                    die("
".print_r($body_data,true)."
");
                }

                if (!isset($body_data["duplicates"]))
                {
                    $body_data["duplicates"] = Transaction_Model::findDuplicates($body_data);
                }

                // If warned about duplicates, then we'll ignore them next time and save anyway when requested
                if (!empty($body_data["duplicates"]))
                {
                    $duplicates = $body_data["duplicates"];
                    $body_data["duplicates"] = [];
                    foreach ($duplicates as $duplicate)
                    {
                        $duplicate['date_formatted'] = date('m/d/y', strtotime($duplicate['date_occurred']));
                        $duplicate['amount_formatted'] = '$' . number_format($duplicate['amount'], 2);
                        $body_data["duplicates"][]= $duplicate;
                    }
                    $body_data["are_duplicates"] = 1;
                }

                $response->body_data = $body_data;
                $response->body_template = 'transaction_form';

            }

            // Delete?
            if ($request->index(1,'delete'))
            {

                $id = $request->get('id');
                if ($id)
                {
                    // Allow muliple
                    $id = explode(",", $id);

                    Transaction_Recurrance_Controller::delete($id);

                    Transaction_Model::delete($id);
                }

                // Back to index or close window
                if ($request->get('app_window'))
                {
                    $response->close_window('Transaction Deleted');
                }
                $response->redirect('/transaction/list');
            }

            $response->finalize();
        }
    }

    // Process image submission
    static public function processImage($image, $response)
    {

        $image_filename = strtolower($image['name']);
        if (!preg_match('/\.(png|jpe?g|gif)$/', $image_filename))
            $response->fail('Image must be png, jpg or gif.');

        if (
            !empty($image['error'])
            or empty($image['tmp_name'])
        ){
            $response->fail('Failed to upload image. May be too large. Limit is ' . ini_get('upload_max_filesize') . '.');
        }

        $image_filename = preg_replace('/[^\w\-_.]+/', '-', $image_filename);
        $image_filename = date('Ymd-His_') . $image_filename;

        $dir = self::DIR_UPLOAD;
        if (!is_dir($dir))
            mkdir($dir);

        $original_filepath = $dir . $image_filename;

        $success = move_uploaded_file( $image['tmp_name'], $original_filepath );

        if (!$success)
            $response->fail('Failed to move uploaded file - check permissions');

        $rotated_filename = preg_replace('/\.\w+$/', '_rotated.png', $image_filename);
		$rotated_filepath = $dir . $rotated_filename;

        $resized_filename = preg_replace('/\.\w+$/', '_resized.png', $image_filename);
		$resized_filepath = $dir . $resized_filename;

		self::autoOrientImage($original_filepath, $rotated_filepath);
        unlink($original_filepath);

        try {
            // Run OCR and cache for later
            $ocr = new OCR_Model($rotated_filepath);
            $ocr->getText();
        } catch (Exception $e) {
            $response->fail("Issue processing image: " . $e->getMessage());
        }

        self::shrinkImage($rotated_filepath, $resized_filepath);
        unlink($rotated_filepath);

        $response->redirect('/transaction/form', ['image'=>$resized_filename]);
    }

	// Process text submission
	static public function processText($text, $response, $extra_data=[])
    {
        // Build unique filename based on
        //  - first 10 alphanumeric characters of text
        //  - date/time
        //  - all lowercase
        $alphanumeric = preg_replace('/[^a-z0-9]+/', '', strtolower($text));
        $filename = substr($alphanumeric, 0, 50);
        $filename = date('Ymd-His_') . $filename . '.txt';

        $dir = self::DIR_FILE;
        if (!is_dir($dir))
            mkdir($dir);

        $path = $dir . $filename;

        $success = file_put_contents($path, $text);

        if ($success == false)
            die('Unable to save text to ' . $path);

        $response->redirect('/transaction/form', array_merge($extra_data, ['file'=>$filename]));
    }

	// Auto-orient an image as needed and save to destination
	static function autoOrientImage($source, $destination, $unlink_invalid=true)
	{
		list($image, $info) = self::getImageFromSource($source, $unlink_invalid);

		// Auto-orient the image as needed
		// Suppress warning - some files are just not readable
		$exif = @exif_read_data($source);
		if($exif && isset($exif['Orientation']))
		{
			$orientation = $exif['Orientation'];
			// if there is some rotation necessary
			if($orientation != 1)
			{
				$deg = 0;
				switch ($orientation)
				{
					case 3:
						$deg = 180;
						break;
					case 6:
						$deg = 270;
						break;
					case 8:
						$deg = 90;
						break;
				}
				if ($deg)
				{
					$image = imagerotate($image, $deg, 0);
				}
			}
		}

		// Will save the image either way, as the new filename is expected
		self::writeImageToFile($image, $destination);
	}

    // Shrink an image
    static function shrinkImage($source, $destination, $unlink_invalid=true)
    {
		list($image, $info) = self::getImageFromSource($source, $unlink_invalid);

        // Size to width 500px
        $width = $info[0];
        $height = $info[1];

        $new_width = 750;
        $new_height = 750;

        if ($width > $new_width or $height > $new_height)
        {
            // Resize whichever is higher to new dimension
            if ($height > $width)
                $new_width = round($width * ($new_height / $height));
            else
                $new_height = round($height * ($new_width / $width));

            $new_image = \imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            $image = $new_image;
        }

		return self::writeImageToFile($image, $destination);
    }

	/**
	 * Get an image object from file source
	 *  - check against valid types
	 *  - optionally delete invalid type of file
	 *
	 * @return [GdImage, $info]
	 */
	static function getImageFromSource($source, $unlink_invalid=true)
	{
        $info = getimagesize($source);

        if ($info['mime'] == 'image/jpeg')
            $image = \imagecreatefromjpeg($source);
        elseif ($info['mime'] == 'image/gif')
            $image = \imagecreatefromgif($source);
        elseif ($info['mime'] == 'image/png')
            $image = \imagecreatefrompng($source);
        else
        {
            if ($unlink_invalid)
            {
                unlink($source);
                die('Image must be png, jpg or gif.  Go back and try again.');
            }
            else
                return false;
        }

		return [$image, $info];
	}

	/**
	 * Write an image out to a file destination
	 */
	static function writeImageToFile($image, $destination)
	{
        // Convert to png
        \imagepng($image, $destination, 1);
	}

    // Process main form submission
    static public function processForm($request, $response)
    {
        $data_to_save = $_POST;

        $success = true;
        $app_window = !empty($data_to_save['app_window']);
        unset($data_to_save['app_window']);

        // Take care of custom amount
        if (empty($data_to_save['amount']))
        {
            $data_to_save['amount'] = $data_to_save['amount_other'];
        }
        unset($data_to_save['amount_other']);

        // save a new account?
        if (empty($data_to_save['account_from']) and !empty($data_to_save['account_from_other']))
        {
            if (Account_Model::create([
                'title' => trim($data_to_save['account_from_other']),
                'classification' => Account_Model::OTHER
            ]))
            {
                $data_to_save['account_from'] = Account_Model::lastInsertId();
                unset($data_to_save['account_from_other']);
            }
            else
            {
                $success = false;
            }
        }
        else
        {
            unset($data_to_save['account_from_other']);
        }

        // save a new account?
        if (empty($data_to_save['account_to']) and !empty($data_to_save['account_to_other']))
        {
            if (Account_Model::create([
                'title' => trim($data_to_save['account_to_other']),
                'classification' => Account_Model::OTHER
            ]))
            {
                $data_to_save['account_to'] = Account_Model::lastInsertId();
                unset($data_to_save['account_to_other']);
            }
            else
            {
                $success = false;
            }
        }
        else
        {
            unset($data_to_save['account_to_other']);
        }

        $submit = $data_to_save['submit'];
        unset($data_to_save['submit']);

        $repeat = false;
        if (isset($data_to_save['repeat']))
        {
            $repeat = $data_to_save['repeat'];
            unset($data_to_save['repeat']);
        }

        $update_children = false;
        if (isset($data_to_save['update_recurrances']))
        {
            $update_children = ($data_to_save['update_recurrances'] == 'yes');
            unset($data_to_save['update_recurrances']);
        }

        $duplicates = Transaction_Model::findDuplicates($data_to_save);
        if (!empty($duplicates))
        {
            return $duplicates;
        }
        unset($data_to_save['ignore_duplicates']);

        if (Transaction_Model::save($data_to_save))
        {
            $id = empty($data_to_save['id']) ? Transaction_Model::lastInsertId() : $data_to_save['id'];

            // Update recurrance
            if ($repeat)
            {
                $repeat['date_start'] = $data_to_save['date_occurred'];
            }
            Transaction_Recurrance_Controller::save($id, $repeat, $update_children);
        }
        else
        {
            $success = false;
        }

        // Redirect based on selection
        if ($success)
        {
            switch($submit)
            {
                case 'apply':
                    // Redirect and load from id
                    $get = ['id' => $id];
                    if ($app_window) $get['app_window'] = 1;
                    $response->redirect('/transaction/form', $get);
                    break;
                case 'save_new':
                    $get = [];
                    if ($app_window) $get['app_window'] = 1;
                    $response->redirect('/transaction/form', $get);
                    break;
                case 'save_close':
                    if ($app_window)
                    {
                        $response->close_window('Transaction Saved');
                    }
                    $response->redirect('/transaction/list');
                    break;
            }
        }
        else
        {
            if ($app_window) $_GET['app_window'] = 1;

            // Redirect so POST doesn't mess with history
            $response->redirect('transaction/form', array_merge($_GET, $_POST));
        }
    }
}
Transaction_Controller::route();


text:
require 'helper'
require 'fullcontact'

describe FullContact::Client::ContactList do

  before do
    FullContact.configure do |config|
      config.api_key = "api_key"
    end
    @client = FullContact::Client.new
  end

  describe "#create_contact_list" do
    before do
      stub_post("contactLists.json").
        with(:query => { :apiKey => "api_key" }).
        to_return(:body => fixture("create_contact_list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end
    it "should send a post to contactLists" do
      @client.create_contact_list
      a_post("contactLists.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end

  describe "#delete_contact_list" do
    before do
      stub_delete("contactLists/12345.json").
        with(:query => { :apiKey => "api_key"}).
        to_return(:body => fixture("delete_contact_list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "should send a delete to contactLists" do
      @client.delete_contact_list("12345")
      a_delete("contactLists/12345.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end

  describe "#get_contact_lists" do
    before do
      stub_get("contactLists.json").
        with(:query => { :apiKey => "api_key"}).
        to_return(:body => fixture("get_contact_lists.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "should get the list of contact lists" do
      @client.get_contact_lists
      a_get("contactLists.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end

  describe "#get_contacts_in_a_list" do
    before do
      stub_get("contactLists/12345.json").
        with(:query => { :apiKey => "api_key"}).
        to_return(:body => fixture("get_contacts_in_a_list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "should get the contacts in a list" do
      @client.get_contacts_in_a_list(12345)
      a_get("contactLists/12345.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end

  describe "#queue_contact_list_for_enrichment" do
    before do
      stub_post("contactLists/12345/queue.json").
        with(:query => { :apiKey => "api_key"}).
        to_return(:body => fixture("queue_contact_list_for_enrichment.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "should queue the contact list for enrichment" do
      @client.queue_contact_list_for_enrichment("12345")
      a_post("contactLists/12345/queue.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end

  describe "#clear_contact_list" do
    before do
      stub_post("contactLists/12345/clear.json").
        with(:query => { :apiKey => "api_key"}).
        to_return(:body => fixture("clear_contact_list.json"), :headers => {:content_type => "application/json; charset=utf-8"})
    end

    it "should clear the contacts in a list" do
      @client.clear_contact_list("12345")
      a_post("contactLists/12345/clear.json").with(:query => { :apiKey => "api_key" }).should have_been_made
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.flex.core.io;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.ConfigurablePropertyAccessor;
import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

/**
 * Static helper util methods for Spring-based property access and introspection.
 *
 * @author Jeremy Grelle
 */
class PropertyProxyUtils {

    private static final Log log = LogFactory.getLog(PropertyProxyUtils.class);

    private PropertyProxyUtils(){}

    public static boolean hasAmfCreator(Class<?> beanType) {
        for (Constructor<?> constructor : beanType.getConstructors()) {
            if (constructor.getAnnotation(AmfCreator.class) != null) {
                return true;
            }
        }
        return false;
    }

    public static PropertyAccessor getPropertyAccessor(ConversionService conversionService, boolean useDirectFieldAccess, Object instance) {
        ConfigurablePropertyAccessor accessor = null;
        if (useDirectFieldAccess) {
            accessor = PropertyAccessorFactory.forDirectFieldAccess(instance);
        } else {
            accessor = PropertyAccessorFactory.forBeanPropertyAccess(instance);
        }
        accessor.setConversionService(conversionService);
        return accessor;
    }

    public static List<String> getFieldNames(Object instance) {
        final List<String> names = new ArrayList<String>();
        ReflectionUtils.doWithFields(instance.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                names.add(field.getName());
            }
        });
        if (log.isDebugEnabled()) {
            log.debug("Property names for "+instance+" : "+names);
        }
        return names;
    }

    public static List<String> getBeanPropertyNames(BeanWrapper beanWrapper) {
        List<String> names = new ArrayList<String>();
        for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
            if (!pd.getName().equals("class")) {
                names.add(pd.getName());
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Property names for "+beanWrapper.getWrappedInstance()+" : "+names);
        }
        return names;
    }

    public static List<String> findPropertyNames(ConversionService conversionService, boolean useDirectFieldAccess, Object instance) {
        if (useDirectFieldAccess) {
            return getFieldNames(instance);
        } else {
            return getBeanPropertyNames((BeanWrapper)getPropertyAccessor(conversionService, useDirectFieldAccess, instance));
        }
    }
}


text:
package showclixscanner;

import java.io.*;
import java.net.HttpCookie;
import java.sql.*;
import java.util.*;

/**
 *
 * @author SunnyBat
 */
public class DatabaseManager {

  private static String databaseDirectory = "C:\\Users\\NoUser\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\NoProfile.Selected\\";

  /**
   * Sets the directory that the Firefox cookie database is located in. NOTE that if the directory does NOT contain a cookie database, it WILL NOT BE
   * SET and the previous directory will be used instead!
   *
   * @param dir The new directory that the Firefox cookie database is located in
   */
  public static void setDatabaseDirectory(String dir) {
    if (!dir.endsWith("\\")) {
      dir += "\\";
    }
    if (!(new File(dir + "cookies.sqlite").exists())) {
      ShowclixScanner.println("NOTE: The given database does NOT contain a cookies database!", ShowclixScanner.LOGTYPE.MINIMUM);
      ShowclixScanner.println("Eranous path: " + dir, ShowclixScanner.LOGTYPE.MINIMUM);
      return;
    }
    databaseDirectory = dir;
  }

  /**
   * Returns the current database directory. Straight and simple.
   *
   * @return The current database directory.
   */
  public static String getDatabaseDirectory() {
    return databaseDirectory;
  }

  public static void deleteDatabaseLockFiles() {
    if (ProcessHandler.isProcessRunging("firefox.exe")) {
      ShowclixScanner.println("ERROR: Firefox is still running -- program cannot delete files!", ShowclixScanner.LOGTYPE.MINIMUM);
      return;
    } else {
      File databaseUseFile1 = new File(databaseDirectory + "cookies.sqlite-wal");
      File databaseUseFile2 = new File(databaseDirectory + "cookies.sqlite-shm");
      databaseUseFile1.delete();
      databaseUseFile2.delete();
    }
  }

  /**
   * Check whether or not the current database directory is a valid directory. This simply checks whether or not the database file exists -- it
   * doesn't check whether or not it can currently be read from or written to.
   *
   * @return True if valid, false if not
   */
  public static boolean isValidDatabase() {
    return new File(databaseDirectory + "cookies.sqlite").exists();
  }

  /**
   * Checks whether or not the cookie database is in use.
   *
   * @return True if it's NOT in use, false if it IS in use.
   */
  public static boolean isDatabaseAvailable() {
    File databaseUseFile1 = new File(databaseDirectory + "cookies.sqlite-wal");
    File databaseUseFile2 = new File(databaseDirectory + "cookies.sqlite-shm");
    return !databaseUseFile1.exists() && !databaseUseFile2.exists();
  }

  /**
   * Reads ALL cookies currently in the Firefox cookie database and prints them out. Note that this really shouldn't be used very much, as it's
   * preferred to only get cookies from a specific domain using {@link #readCookies(java.lang.String)}.
   */
  public static void readCookies() {
    readCookies("");
  }

  /**
   * Reads the cookies currently in the Firefox cookie database and prints out the ones belonging to the given domain. The domain should be somthing
   * like "example.com"
   *
   * @param filterDomain The domain to search for
   */
  public static void readCookies(String filterDomain) {
    if (!isValidDatabase()) {
      ShowclixScanner.println("ERROR: Non-valid database!");
      return;
    }
    Connection connection;
    ResultSet resultSet;
    Statement statement;
    try {
      Class.forName("org.sqlite.JDBC");
      connection = DriverManager.getConnection("jdbc:sqlite:" + databaseDirectory + "cookies.sqlite");
      statement = connection.createStatement();
      resultSet = statement.executeQuery("SELECT * FROM moz_cookies");
      ShowclixScanner.println("Database Column Names:");
      for (int a = 1; a < resultSet.getMetaData().getColumnCount(); a++) {
        ShowclixScanner.println(resultSet.getMetaData().getColumnName(a));
      }
      while (resultSet.next()) {
        if (filterDomain != null) {
          if (resultSet.getString("baseDomain").contains(filterDomain)) {
            ShowclixScanner.println("-------------Cookie Found-------------");
            for (int a = 1; a < resultSet.getMetaData().getColumnCount(); a++) {
              String cN = resultSet.getMetaData().getColumnName(a);
              ShowclixScanner.println(cN + " = " + resultSet.getString(cN));
            }
//          ShowclixScanner.println("Name = " + resultSet.getString("name"));
//          ShowclixScanner.println("Value = " + resultSet.getString("value"));
//          ShowclixScanner.println("Expires = " + resultSet.getString("expiry"));
//          ShowclixScanner.println("isSecure = " + resultSet.getString("isSecure"));
//          ShowclixScanner.println("Path = " + resultSet.getString("path"));
            ShowclixScanner.println("-----------End Cookie Output-----------");
          }
        }
      }
      resultSet.close();
      statement.close();
      connection.close();
    } catch (Exception e) {
      ShowclixScanner.println("ERROR reading cookies database!", ShowclixScanner.LOGTYPE.NOTES);
      e.printStackTrace();
    }
  }

  /**
   * Writes the given HttpCookies to the Firefox database. Note that the database should be set with {@link #setDatabaseDirectory(java.lang.String)}
   * before this is run.
   *
   * @param cookies The list of cookies to write to the database
   */
  public static boolean writeCookies(List<HttpCookie> cookies) {
    if (!isValidDatabase()) {
      return false;
    }
    List<HttpCookie> cookieList = new ArrayList(); // Apparently the List can be unchangeable, so create a new one and dump into it so it IS changeable
    cookieList.addAll(cookies);
    if (makeCookieBackup()) {
      ShowclixScanner.println("Cookie backup saved successfully!", ShowclixScanner.LOGTYPE.NOTES);
    } else {
      ShowclixScanner.println("WARNING: Unable to save cookies database backup file.", ShowclixScanner.LOGTYPE.MINIMUM);
    }
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    HttpCookie currCookie;
    List nameList = new ArrayList();
    Iterator<HttpCookie> iterator = cookieList.iterator();
    while (iterator.hasNext()) {
      nameList.add(iterator.next().getName());
    }
    try {
      Class.forName("org.sqlite.JDBC");
      connection = DriverManager.getConnection("jdbc:sqlite:" + databaseDirectory + "cookies.sqlite");
      System.out.println(databaseDirectory + "cookies.sqlite");
      statement = connection.createStatement();
      resultSet = statement.executeQuery("SELECT * FROM moz_cookies");
      statement = connection.createStatement();
      connection.setAutoCommit(false);
      int lastID = 1;
      while (resultSet.next()) {
        if (nameList.contains(resultSet.getString("name")) && resultSet.getString("baseDomain").contains("showclix")) {
          currCookie = cookieList.get(nameList.indexOf(resultSet.getString("name")));
          if (currCookie == null) {
            ShowclixScanner.println("ERROR with writing cookies: Cookie was null?", ShowclixScanner.LOGTYPE.MINIMUM);
            continue;
          }
          ShowclixScanner.println("=========Updating Cookie " + currCookie.getName() + "...===========");
          if (currCookie.getMaxAge() == -1 || currCookie.getMaxAge() < (System.currentTimeMillis() / 1000)) {
            System.out.println("Cookie is invalid. Reformatting.");
            currCookie.setMaxAge(System.currentTimeMillis() / 1000 + 86400); // Current seconds + 1 day's worth of seconds
          }
          for (int a = 1; a < resultSet.getMetaData().getColumnCount(); a++) {
            String cN = resultSet.getMetaData().getColumnName(a);
            ShowclixScanner.println(cN + " = " + resultSet.getString(cN));
          }
          ShowclixScanner.println("===================================================================");
          String sql = "UPDATE moz_cookies set value = '" + currCookie.getValue() + "' where id=" + resultSet.getInt("id") + ";";
          statement = connection.createStatement();
          ShowclixScanner.println("executeUpdate return: " + statement.executeUpdate(sql));
          connection.commit();
          cookieList.remove(currCookie);
          nameList.remove(currCookie.getName());
        } else if (nameList.contains(resultSet.getString("name"))) {
          ShowclixScanner.println("Name = " + resultSet.getString("name") + " :: Site = " + resultSet.getString("baseDomain"));
        }
        lastID = resultSet.getInt("id");
      }
      ShowclixScanner.println("lastID = " + lastID);
      lastID++;
      iterator = cookieList.iterator();
      while (iterator.hasNext()) {
        currCookie = iterator.next();
        if (currCookie.getMaxAge() == -1 || currCookie.getMaxAge() < (System.currentTimeMillis() / 1000)) {
          System.out.println("Cookie is invalid. Reformatting.");
          currCookie.setMaxAge(System.currentTimeMillis() / 1000 + 86400); // Current seconds + 1 day's worth of seconds
        }
        ShowclixScanner.println("Creating " + currCookie.getName() + " :: " + currCookie.getValue());
        ShowclixScanner.println("id = " + lastID);
        String sql = "INSERT INTO moz_cookies (ID,BASEDOMAIN,APPID,INBROWSERELEMENT,NAME,VALUE,HOST,PATH,EXPIRY,LASTACCESSED,CREATIONTIME,ISSECURE) "
            + "VALUES (" + lastID + ", 'showclix.com', 0, 0, '" + currCookie.getName() + "', '" + currCookie.getValue() + "', '.showclix.com', '"
            + currCookie.getPath() + "', 1503940117, " + (System.currentTimeMillis() * 1000) + ", " + (System.currentTimeMillis() * 1000) + ", '"
            + currCookie.getSecure() + "' );";
        statement = connection.createStatement();
        ShowclixScanner.println("executeUpdate return: " + statement.executeUpdate(sql));
        //statement.close();
        connection.commit();
        lastID++;
      }
      connection.commit();
      resultSet.close();
      statement.close();
      connection.close();
      readCookies("showclix");
    } catch (Exception e) {
      ShowclixScanner.println("ERROR");
      e.printStackTrace();
      return false;
    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
        if (statement != null) {
          statement.close();
        }
        if (resultSet != null) {
          resultSet.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return true;
  }

  /**
   * For internal use only. Use to make a backup of the cookie directory before making changes to it. This will allow you to recover most, if not all,
   * of your cookies should something go wrong. This should be called before every database change.
   *
   * @return True if successful, false if not.
   */
  private static boolean makeCookieBackup() {
    if (!isValidDatabase()) {
      return false;
    }
    try { // Code to make a copy of the current JAR file
      File inputFile = new File(databaseDirectory + "cookies.sqlite");
      InputStream fIn = new BufferedInputStream(new FileInputStream(inputFile));
      File outputFile = new File(databaseDirectory + "cookies.sqlite.bak");
      if (outputFile.exists()) {
        outputFile.delete();
      }
      BufferedOutputStream buffOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
      byte[] buffer = new byte[32 * 1024];
      int bytesRead = 0;
      while ((bytesRead = fIn.read(buffer)) != -1) {
        buffOutputStream.write(buffer, 0, bytesRead);
      }
      buffOutputStream.flush();
      buffOutputStream.close();
      fIn.close();
      ShowclixScanner.println("File copied.");
      return true;
    } catch (Exception e) {
      return false;
    }
  }
}


text:
require 'rails_helper'

RSpec.describe Emm, :type => :model do
end

# == Schema Information
#
# Table name: emms
#
#  id             :integer          not null, primary key
#  original_name  :string(255)      not null
#  save_file_name :string(255)      not null
#  lock_version   :integer
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#  video_id       :integer
#


text:
/* cleanup deleted user project members */
DELETE FROM project_member pm WHERE pm.entity_type = 'u' AND EXISTS (SELECT NULL FROM harbor_user u WHERE pm.entity_id = u.user_id AND u.deleted = true );

ALTER TABLE replication_policy ADD COLUMN IF NOT EXISTS speed_kb int;

/* add version fields for lock free quota */
ALTER TABLE quota ADD COLUMN IF NOT EXISTS version bigint DEFAULT 0;
ALTER TABLE quota_usage ADD COLUMN IF NOT EXISTS version bigint DEFAULT 0;

/* convert Negligible to None for the severity of the vulnerability record */
UPDATE vulnerability_record SET severity='None' WHERE severity='Negligible';


text:
<?php

use yii\db\Migration;

class m200602_112301__alter_table__shop_order_status extends Migration
{
    public function safeUp()
    {
        $tableName = "shop_order_status";

        $this->addColumn($tableName, "auto_next_shop_order_status_id", $this->integer(11)->comment("Следующий статус, который будет проставлен автоматически"));
        $this->addColumn($tableName, "auto_next_status_time", $this->integer(11)->comment("Время через которое следующий статус будет проставлен"));

        $this->createIndex("auto_next_shop_order_status_id", $tableName, "auto_next_shop_order_status_id");
        $this->createIndex("auto_next_status_time", $tableName, "auto_next_status_time");

        $this->addForeignKey(
            "{$tableName}__auto_next_shop_order_status", $tableName,
            'auto_next_shop_order_status_id', '{{%shop_order_status}}', 'id', 'SET NULL', 'SET NULL'
        );

    }

    public function safeDown()
    {
        echo "m200525_132301__alter_table__shop_order_status cannot be reverted.\n";
        return false;
    }
}


text:
import zstackwoodpecker.test_state as ts_header
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template2", path_list=[
        [TestAction.create_volume, "volume1", "=scsi"],
        [TestAction.create_volume, "volume2", "=scsi"],
        [TestAction.attach_volume,"vm1", "volume1"],
        [TestAction.clone_vm, "vm1", "vm2"],
        [TestAction.attach_volume,"vm2", "volume2"],
	[TestAction.create_data_volume_from_image, "volume3", "=scsi"],
	[TestAction.detach_volume, "volume1"] ,
	[TestAction.stop_vm, "vm1"],
	[TestAction.ps_migrate_volume, "vm1-root"],
	[TestAction.start_vm, "vm1"],
	[TestAction.ps_migrate_volume, "volume1"],
	[TestAction.cleanup_ps_cache],
	[TestAction.resize_data_volume, "volume1", 5*1024*1024],
	[TestAction.detach_volume, "volume2"] ,
	[TestAction.stop_vm, "vm2"],
	[TestAction.ps_migrate_volume, "vm2-root"],
	[TestAction.start_vm, "vm2"],
	[TestAction.ps_migrate_volume, "volume2"],

	[TestAction.reboot_vm, "vm1"]])


text:
/* Body Styles */
body
  {
 color: #000;
 }

/* Generic Ajax Styles */

.ajax_loader {
  width:100%;
  padding-top:20px;
  height:150px;
  background-image:url(/images/loading.gif);
  background-position: center center;
  background-repeat:no-repeat;
}

.cms_ajax_link {
  padding:0 4px;
  margin:0;
  color: #6765f6;
  text-decoration:none;
}

.cms_ajax_link:visited {
  padding:0 4px;
  margin:0;
  color: #6566f4;
  text-decoration:none;
}

.cms_ajax_link:hover {
  padding:0 4px;
  margin:0;
  color: #005acf;
  background-color:#cfc300;
  text-decoration:none;
}

.cms_ajax_link_selected {
  padding:0 4px;
  margin:0;
  color: #FFFFFF;
  background-color:#DDDDDD;
  text-decoration:none;
  font-weight:bold;
}

.cms_ajax_link_selected:visited {
  padding:0 4px;
  margin:0;
  color: #FFFFFF;
  background-color:#DDDDDD;
  text-decoration:none;
}

.cms_ajax_link_selected:hover {
  padding:0 4px;
  margin:0;
  color: #CCCCCC;
  background-color:#6765f6;
  text-decoration:none;
}

.cms_ajax_link_modified {
  padding:0 4px;
  margin:0;
  color: #FF0000;
  text-decoration:none;
  font-weight:bold;
}

.cms_ajax_link_modified:visited {
  padding:0 4px;
  margin:0;
  color: #6566f4;
  text-decoration:none;
  font-weight:bold;
}

.cms_ajax_link_modified:hover {
  padding:0 4px;
  margin:0;
  color: #005acf;
  background-color:#cfc300;
  text-decoration:none;
  font-weight:bold;
}

/* Header Styles */

#cms_header {
 margin:0px;
 padding: 0px 0px;
 height:100px;
 width:100%;
 position:absolute;
 top:0px;
 left:0px;
 z-index:1000;
 color:#000000;
}
  #cms_header { color:#000000; }

  #cms_header #cms_info_line { color:#000000; }

  body > div#cms_header {
  position:fixed;

  }

  #cms_header img {
  border:0px;
  padding:0px;
  margin:0px;
  }

  #cms_header a {
    border:0px;
    padding:0px;
    margin:0px;
    color:#3b648c
  }

  #cms_header a:hover {
    border:0px;
    padding:0px;
    margin:0px;
    color:#3b648c

  }

  #cms_info_line {
    padding:5px 5px;
    margin:0px;
    height:18px;
    border-bottom:1px solid #3b648c;

    position:relative;
    z-index:500;
    background-color:#bbd6e1;

  }

    #cms_page_info {
    float:left;
    }

    #cms_modification_info {
    float:right;
    }

  #cms_icon_line {
  clear:both;
  height:28px;
  padding: 5px 5px 4px 5px;
  border-bottom:1px solid #3b648c;
  position:relative;
  z-index:499;
  background-color:#bbd6e1;

  }

  #cms_toolbars {
  padding:2px 0;
  margin:0px;
  overflow:hidden;
  height:30px;
  text-align:left;
  z-index:498;
  position:relative;
 background-color:#F0F0EE;

  }

#cms_add_paragraph {
  padding:4px;
  color:#FFFFFF;
  background-color:#FFFFFF;
  font-weight:bold;
  text-align:center;
  white-space:nowrap;
  position:absolute;
  border:1px solid #CCCCCC;
}

.cms_add_paragraph_zone {
 background-color:#F4b639;
 color:#111111;
 text-align:center;
 font-size:12px;
 font-family: Arial;
 height:16px;
 cursor:pointer;
 z-index:101;
}

.cms_add_element_zone {
 padding:10px;
 margin:0px;
 background-color:#F4b639;
 font-size:12px;
 font-family: Arial;
 height:20px;
 color:#111111;
 text-align:center;
 cursor:pointer;
 z-index:101;
}

.cms_paragraph_zone_drop {
 opacity: .6;
 filter: alpha(opacity=60);
 background-color:#CCCCCC;
 min-height:20px;
 height:auto !important;
 height:20px;

}

#cms_html_toolbar {

}

#cms_page_content {
 padding:100px 0 0 0;
 z-index:100;
}

#cms_page_content div.cms_paragraph_icon {
  cursor:move;
  padding:0px;
  margin:0px;
}

#cms_page_content div.cms_paragraph_menu {
 background-color:#CCCCCC;
  padding:0px;
  margin:0px;
}

#cms_page_content div.cms_paragraph_menu_selected {
  background-color:#96ccd9;
  padding:0px;
  margin:0px;
}

/* Standard Styles **/
#cms_header div.cms_popup {
	padding:5px;
	margin:5px;
	background-color:#FFFFFF;
  color:#000000;
	border:1px solid #000000;
	position:absolute;
  white-space:nowrap;
  text-align:left;
  z-index:1000;
}

#cms_select_page {
 width: 600px;
 height: 400px;
 overflow:auto;

}

#cms_page_content div.cms_div {
  padding:0px;
  margin:0px;
}

#cms_page_content div.cms_paragraph {
 border:0px;
 text-align:left;
}

#cms_page_content div.cms_framework_feature {
 border:0px;
 text-align:left;
}

#cms_page_content div.cms_paragraph_editor {
 position:relative;
}

#cms_page_content div.cms_div {
 position:relative;
}

#cms_page_content div.cms_paragraph_editor_cover {
 position:absolute;
 width:100%;
 height:100%;
}

#cms_page_content div.cms_paragraph_editor_cover:hover  {
 position:absolute;
 width:100%;
 height:100%;
 opacity: .3;
 filter: alpha(opacity=30);
 background-color:#BBBBBB;
 cursor:pointer;

}

#cms_page_content div.cms_rendered_wrapper {
 padding:0px;
 margin:0px;
}

.mceToolbarExternal {
 text-align:left;
 visibility:hidden;
}

/* Overlay Styles */
#RB_redbox div.cms_form p {
  margin:0px;
  padding:0px;
}

#RB_redbox div.cms_form {
  border-top:1px solid #444444;
  border-left:1px solid #444444;
  border-right:3px solid #000000;
  border-bottom:3px solid #000000;
  padding:10px;
  height:auto;
  width:auto;
  overflow:auto;
  color:#000000;
  font-size:12px;
  font-family:Verdana;
}

#RB_redbox div.cms_form span {
  padding:0px;
  margin:0px;
}

#RB_redbox div.cms_form div {
  padding:0px;
  margin:0px;
}

#RB_redbox .cms_form h3 {
  font-style: normal;
  font-family: Verdana;
  font-size:14px;
  font-weight:bolder;
  border-bottom:1px solid #000000;
  margin-bottom:10px;
  color : #343434;
}

#RB_redbox div.cms_form table {
  width:auto;
}

#RB_redbox div.cms_form table td.header {
  font-weight:bolder;
  border-bottom:1px solid #000000;
}

#RB_redbox div.cms_form img {
  padding:0px;
  margin:0px;
  border:0px;
}

#RB_redbox div.cms_form hr {
  border:0px;
  border-top: 1px solid #AAAAAA;
}

#RB_redbox div.cms_form td {
  padding:2px 5px;
  font-size:12px;
  font-family:Verdana;
}

#RB_redbox div.cms_form td.data_vertical {
 padding:2px 5px 0px 5px;
}

#RB_redbox div.cms_form td.label {
  color:#444444;
}

#RB_redbox div.cms_form td.label_vertical {
  color:#444444;
}

#RB_redbox div.cms_form td.description  {
  color:#999999;
  padding-top:0px;
  padding-bottom:6px;
  font-size:11px;
}

#RB_redbox div.cms_form td.description_vertical {
  color:#999999;
  padding-top:0px;
  padding-bottom:6px;
  font-size:11px;
}

#RB_redbox div.cms_form td.text_field_control input {
 border:1px solid #999999;
 padding:2px;
}

#RB_redbox div.cms_form td.text_area_control input {
 border:1px solid #999999;
 padding:2px;
}

#RB_redbox div.cms_form td.error {
 color:#FF0000;
}

/* Generic Ajax Styles */

.ajax_loader {
  width:100%;
  padding-top:20px;
  height:150px;
  background-image:url(/images/loading.gif);
  background-position: center center;
  background-repeat:no-repeat;
}

.ajax_link {
  padding:0;
  margin:0 4px;
  color: #005acf;
  text-decoration:none;
}

.ajax_link:hover {
  padding:0;
  margin:0 4px;
  color: #005acf;
  background-color:#92b3e1;
  text-decoration:none;
}

.ajax_tabs {
	width:100%;
	position:relative;
}

.ajax_link_selected {
  padding:0;
  margin:0 4px;
  color: #000000;
  text-decoration:none;
}

.ajax_link_selected:hover {
  padding:0;
  margin:0 4px;
  color: #000000;
  text-decoration:none;

}

.large_ajax_link {
  padding:0;
  margin:0 4px;
  color: #005acf;
  font-size:14px;
  text-decoration:none;
}

    .large_ajax_link:hover {
      padding:0;
      margin:0 4px;
      color: #005acf;
      background-color:#92b3e1;
      text-decoration:none;
    }

    .large_ajax_link_selected {
      padding:0;
      margin:0 4px;
      color: #f79239;
      font-size:14px;
      text-decoration:none;
    }

    .large_ajax_link_selected:hover {
      padding:0;
      margin:0 4px;
      color: #f79239;
      text-decoration:none;

    }

.ajax_tabs {
	width:100%;
	position:relative;
}

    .ajax_tabs td.normal {
    padding:5px 10px;
    border-bottom:1px solid #CCCCCC;
    border-top:1px solid #CCCCCC;
    white-space: nowrap;
    background-color:#f3f6f8;
    }

    .ajax_tabs td.extra {
    white-space: nowrap;
    padding:0px 10px;
    width:100%;
    border:0;
    border-top:1px solid #CCCCCC;
    border-bottom:1px solid #CCCCCC;
    background-color:#f3f6f8;
    }

    .ajax_tabs td.selected {
      white-space: nowrap;
      padding:5px 10px;
      border:0;
      border-left:1px solid #CCCCCC;
      border-right:1px solid #CCCCCC;
      border-top:1px solid #CCCCCC;
    background-color:#FFFFFF;
    }

    .ajax_tabs td.content {
      border:0px;
      padding:5px;
      white-space: normal;
    }

/* Popup CSS */

#overDiv .cms_popup_text {
  padding:5px !important;
  background-color:white !important;
  color:black !important;
}

#overDiv .cms_popup_text a {
  color:black  !important;
  text-decoration:underline !important;
  padding:2px 0px  !important;
}

#overDiv .cms_popup_text hr {
  height:1px;
  margin:4px 0px;
  color:black;
  background-color:black;
}

#overDiv .cms_popup_bg {
  border:1px solid #a6cdda;
  background-color:white;
  color:black;

}

#overDiv .cms_popup_caption {
  color:#3b648c;
    background-color:#a6cdda;
  font-weight:bold;
}

/* Ordered Selection List Stuff */

.ordered_selection_list {
 padding:5px;
 border:1px solid #CCCCCC;
 margin:4px 0px;
 width:300px;
 overflow:auto;

}

.ordered_selection_list_item {
 clear:both;
 cursor:pointer;
 padding:2px;
 margin:2px !important;
 background-color:#DDDDDD;
 position:relative;
 font-weight:bold;
 color:#666666;
 margin:4px;
}

.ordered_selection_list_value {

}

.ordered_selection_list_remove {
 position:absolute;
 right:5px;

}

.ordered_selection_list_remove a { text-decoration: none; font-weight:bold; color:black; }

#cms_header   .site_node_modifier { width:17px; height:17px; display:inline-block; vertical-align:middle;}
#cms_header   .site_node { width:17px; height:17px; display:inline-block;  vertical-align:middle;}
#cms_header   .domain_node { background:url(../images/icons/site_tree.gif) -34px 0px no-repeat; }
#cms_header   .page_node { background:url(../images/icons/site_tree.gif) -51px 0px no-repeat; }
#cms_header   .module_node { background:url(../images/icons/site_tree.gif) -68px 0px no-repeat; }
#cms_header   .redirect_node { background:url(../images/icons/site_tree.gif) -85px 0px no-repeat; }
#cms_header   .document_node { background:url(../images/icons/site_tree.gif) -135px no-repeat; }
#cms_header   .group_node { background:url(../images/icons/site_tree.gif) -152px 0px no-repeat; }

#cms_header   .framework_modifier { background:url(../images/icons/site_tree.gif) 0px 0px no-repeat; }
#cms_header  .template_modifier{ background:url(../images/icons/site_tree.gif) -17px 0px no-repeat; }
#cms_header   .lock_modifier{ background:url(../images/icons/site_tree.gif) -101px 0px no-repeat; }
#cms_header   .ssl_modifier{ background:url(../images/icons/site_tree.gif) -118px 0px no-repeat; }
#cms_header   .domain_modifier{ background:url(../images/icons/site_tree.gif) -169px 0px no-repeat; }

#cms_header   .sprite_icon {  width:17px; height:17px; display:inline-block; vertical-align:middle;}
#cms_header   .folder_sprite { background:url(../images/icons/site_tree.gif) -152px 0px no-repeat; }
#cms_header   .folder_template_sprite { background:url(../images/icons/site_tree.gif) -186px no-repeat; }
#cms_header   .domain_sprite { background:url(../images/icons/site_tree.gif) -169px 0px no-repeat; }
#cms_header   .lock_sprite{ background:url(../images/icons/site_tree.gif) -101px 0px no-repeat; }


text:
<?php
namespace Cujo\Content;

class Merge extends Content
{
    private $contents;

    public function __construct(array $contents)
    {
        $this->contents = $contents;
    }

    public function get($key)
    {
        foreach ($this->contents as $content) {
            $value = $content->get($key);
            if (false !== $value && null !== $value) {
                return $value;
            }
        }
        return false;
    }

    public function find(array $criteria)
    {
        $result = [];
        foreach (array_reverse($this->contents) as $content) {
            $result = array_merge($result, $content->find($criteria));
        }
        return $result;
    }
}


text:
Rails.application.routes.draw do
  resources :incomes
  resources :sources
  resources :expenses
  devise_for :users
end


text:
package blang.core;

import java.util.Random;

public interface RealDistribution
{
  double sample(Random random);
  double logDensity(double point);
}


text:
package com.eternity.reference.json;

import com.eternity.common.SubSystemNames;
import com.eternity.common.message.MessageNames;
import com.eternity.common.message.ParameterNames;
import com.eternity.common.test.SubSystemNamesJsonDeserializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonFactory {
	public static Gson getGson() {
		return singleton.gson;
	}
	private static GsonFactory singleton = new GsonFactory();

	private Gson gson;
	private GsonFactory() {
		gson = new GsonBuilder()
		.registerTypeAdapter(ParameterNames.class, new ParameterNamesJsonDeserializer())
		.registerTypeAdapter(MessageNames.class, new MessageNamesJsonDeserializer())
		.registerTypeAdapter(SubSystemNames.class, new SubSystemNamesJsonDeserializer())
		.create();
	}

}


text:
ENV=${ENV:-pre}
NUM_REPLICAS=$(kubectl get rc -l role=mongo -l environment=${ENV} -o template --template='{{ len .items }}')
NEW_REPLICA_NUM=$((NUM_REPLICAS + 1 ))

echo "Current Number of MongoDB Replicas: ${NUM_REPLICAS}"

echo 'Deleting Replica'
kubectl delete svc ${ENV}-mongo-${NUM_REPLICAS}
kubectl delete rc ${ENV}-mongo-${NUM_REPLICAS}


text:
The NelmioSecurityBundle provides additional security features for your Symfony2 application.

## Installation

Require the `nelmio/security-bundle` package in your composer.json and update your dependencies.

    $ composer require nelmio/security-bundle

Add the NelmioSecurityBundle to your application's kernel:

```php
public function registerBundles()
{
    $bundles = array(
        ...
        new Nelmio\SecurityBundle\NelmioSecurityBundle(),
        ...
    );
    ...
}
```

## Features

* **[Content Security Policy](#content-security-policy)**: Cross site scripting attacks (XSS) can be mitigated
in modern browsers using a policy which instructs the browser never to execute inline scripts, or never to
load content from another domain than the page's domain.

* **[Signed Cookies](#signed-cookies)**: Specify certain cookies to be signed, so that the user cannot modify
  them. Note that they will not be encrypted, but signed only. The contents will still be
  visible to the user.

* **[Encrypted Cookies](#encrypted-cookies)**: Specify certain cookies to be encrypted, so that the value cannot be
  read. When you retrieve the cookie it will be automatically decrypted.

* **[Clickjacking Protection](#clickjacking-protection)**: X-Frame-Options header is added to all responses to prevent your
  site from being put in a frame/iframe. This can have serious security implications as it has
  been demonstrated time and time again with Facebook and others. You can allow framing of your
  site from itself or from anywhere on a per-URL basis.

* **[External Redirects Detection](#external-redirects-detection)**: Redirecting from your site to arbitrary URLs based on user
  input can be exploited to confuse users into clicking links that seemingly point to valid
  sites while they in fact lead to malicious content. It also may be possible to gain PageRank
  that way.

* **[Forced HTTPS/SSL Handling](#forced-httpsssl-handling)**: This forces by all requests to go through SSL. It will also
  send [HSTS](http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02) headers so that
  modern browsers supporting it can make users use HTTPS even if they enter URLs without https,
  avoiding attacks on public Wi-Fi.

* **[Flexible HTTPS/SSL Handling](#flexible-httpsssl-handling)**: If you don't want to force all users to use HTTPS, you should
  at least use secure session cookies and force SSL for logged-in users. But then logged-in users
  appear logged-out when they access a non-HTTPS resource. This is not really a good solution.
  This will make the application detect logged-in users and redirect them to a secure URL,
  without making the session cookie insecure.

* **[Cookie Session Handler](#cookie-session-handler)**: You can configure the session handler to use a cookie based storage.
  **WARNING**: by default the session is not encrypted, it is your responsibility to properly configure the Encrypted Cookies
  section to include the session cookie (default name: session). The size limit of a cookie is 4KB, so make sure you are not
  storing object or long text into session.

* **[Disable Content Type Sniffing](#content-type-sniffing)**: Require that scripts are loaded using the correct mime type.
  This disables the feature that some browsers have which uses content sniffing to determine if the response is a valid
  script file or not.

## Maximum Security Configuration (Read on for detailed recommendations!)

```yaml
nelmio_security:
    # signs/verifies all cookies
    signed_cookie:
        names: ['*']
    # encrypt all cookies
    encrypted_cookie:
        names: ['*']
    # prevents framing of the entire site
    clickjacking:
        paths:
            '^/.*': DENY
    # prevents redirections outside the website's domain
    external_redirects:
        abort: true
        log: true

    # prevents inline scripts, unsafe eval, external scripts/images/styles/frames, etc
    csp:
        report:
            report-uri: [/nelmio/csp/report]
            default-src: [ 'self' ]
            # There's no flash on our site
            object-src:
                - 'none'
            script-src:
                - 'unsafe-inline'
                - 'unsafe-eval'
                - 'self'
        enforce:
            # see https://github.com/nelmio/NelmioSecurityBundle/issues/32
            report-uri: [/nelmio/csp/report]
            script-src:
                - 'self'

    # disables content type sniffing for script resources
    content_type:
        nosniff: true

    # forced HTTPS handling, don't combine with flexible mode
    # and make sure you have SSL working on your site before enabling this
#    forced_ssl:
#        hsts_max_age: 2592000 # 30 days
#        hsts_subdomains: true

    # flexible HTTPS handling, read the detailed config info
    # and make sure you have SSL working on your site before enabling this
#    flexible_ssl:
#        cookie_name: auth
#        unsecured_logout: false
```

## Configuration Detail

### Content Security Policy:

Using CSP you can set a policy which modern browsers understand and will honor. The policy contains nine different
directives; `default-src`, `script-src`, `object-src`, `style-src`, `img-src`, `media-src`, `frame-src`,
`font-src`, `connect-src`, `report-uri`. You can provide an array of directives per content type. Empty content
types will inherit from `default-src`, specified content types will never inherit from `default-src`. Please see
the [Content Security Policy 1.0](http://www.w3.org/TR/CSP) specification for details.

Each directive should be a domain, URI or keyword. The keyword `'self'` will allow content from the same origin as
the page. If you need to allow inline scripts or `eval()` you can use `'unsafe-inline'` and `'unsafe-eval'`.

**WARNING:** By using `'unsafe-inline'` or `'unsafe-eval'` you're effectively disabling the XSS protection
mechanism of CSP.

Apart from content types, the policy also accepts `report-uri` which should be a URI where a browser can POST a
[JSON payload](https://developer.mozilla.org/en-US/docs/Security/CSP/Using_CSP_violation_reports#Sample_violation_report)
to whenever a policy directive is violated.

```yaml
nelmio_security:
    csp:
        report_logger_service: logger
        enforce:
            report-uri: /nelmio/csp/report
            default-src: [ 'self' ]
            frame-src: [ 'https://www.youtube.com' ]
            script-src:
                - 'self'
                - 'unsafe-inline'
            img-src:
                - 'self'
                - facebook.com
                - flickr.com
        report:
            report-uri: /nelmio/csp/report
            script-src:
                - 'self'
```

The above configuration would enforce the following policy:

* Default is to allow from same origin as the page
* Frames only from secure youtube connections
* JavaScript from same origin and from inline `<script>` tags
* Images from same origin, `facebook.com` and `flickr.com`

Any violation of the enforced policy would be posted to /nelmio/csp/report.

In addition, the configuration only reports but doesn't enforce the policy that JavaScript may only be executed
when it comes from the same server.

The bundle provides a default reporting implementation that logs violations as notices
to the default logger, to enable add the following to your routing.yml:

```yaml
nelmio_security:
    path:     /nelmio/csp/report
    defaults: { _controller: nelmio_security.csp_reporter_controller:indexAction }
    methods:  [POST]
```

(Optional) Use *report_logger_id* to log to the 'security' channel:

```yaml
nelmio_security:
    csp:
        report_logger_service: monolog.logger.security
```

(Optional) Disable *compat_headers* to avoid sending X-Content-Security-Policy
(IE10, IE11, Firefox < 23). This will mean those browsers get no CSP instructions.

```yaml
nelmio_security:
    csp:
        compat_headers: false
```

### **Signed Cookies**:

Ideally you should explicitly specify which cookies to sign. The reason for this is simple.
Cookies are sent with each request. Signatures are often longer than the cookie values themselves,
so signing everything would just needlessly slow down your app and increase bandwidth usage for
your users.

```yaml
nelmio_security:
    signed_cookie:
        names: [test1, test2]
```

However, for simplicity reasons, and to start with a high security and optimize later, you can
specify '*' as a cookie name to have all cookies signed automatically.

```
nelmio_security:
    signed_cookie:
        names: ['*']
```

Additional, optional configuration settings:

```yaml
nelmio_security:
    signed_cookie:
        secret: this_is_very_secret # defaults to global %secret% parameter
        hash_algo: sha512 # defaults to sha256, see `hash_algos()` for available algorithms
```

### **Encrypted Cookies**:

Encrypts the cookie values using `nelmio_security.encrypted_cookie.secret`. It works the same as
Signed Cookies:

```yaml
nelmio_security:
    encrypted_cookie:
        names: [test1, test2]
```

Additional, optional configuration settings:

```yaml
nelmio_security:
    encrypted_cookie:
        secret: this_is_very_secret # defaults to global %secret% parameter
        algorithm: rijndael-256 # defaults to rijndael-128, see `mcrypt_list_algorithms()` for available algorithms
```

### **Clickjacking Protection**:

Most websites do not use frames and do not need to be frame-able. This is a common attack vector
for which all current browsers (IE8+, Opera10.5+, Safari4+, Chrome4+ and Firefox3.7+) have a
solution. An extra header sent by your site will tell the browser that it can not be displayed in
an frame. Browsers react by showing a short explanation instead of the content, or a blank page.

The valid values for the `X-Frame-Options` header are `DENY` (prevent framing from all pages) and
`SAMEORIGIN` (prevent framing from all pages not on the same domain). Additionally this bundle
supports the `ALLOW` option which skips the creation of the header for the matched URLs, if you
want to whitelist a few URLs and then DENY everything else.

One more option, as of yet [not well supported](https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options),
is to use `ALLOW FROM uri` where `uri` can be any origin URL, from
`example.org` to `https://example.org:123/sub/path`. This lets you specify
exactly which domain can embed your site, in case you have a multi-domain setup.

Default configuration (deny everything):

```yaml
nelmio_security:
    clickjacking:
        paths:
            '^/.*': DENY
```

Whitelist configuration (deny all but a few URLs):

```yaml
nelmio_security:
    clickjacking:
        paths:
            '^/iframes/': ALLOW
            '^/business/': 'ALLOW FROM https://biz.example.org'
            '^/local/': SAMEORIGIN
            '^/.*': DENY
```

You can also of course only deny a few critical URLs, while leaving the rest alone:

```yaml
nelmio_security:
    clickjacking:
        paths:
            '^/message/write': DENY
```

### **External Redirects Detection**:

This feature helps you detect and prevent redirects to external sites. This can easily happen
by accident if you carelessly take query parameters as redirection target.

You can log those (it's logged at warning level) by turning on logging:

```yaml
nelmio_security:
    external_redirects:
        log: true
```

You can abort (they are replaced by a 403 response) the redirects:

```yaml
nelmio_security:
    external_redirects:
        abort: true
```

Or you can override them, replacing the redirect's `Location` header by a route name or
another URL:

```yaml
# redirect to the 'home' route
nelmio_security:
    external_redirects:
        override: home

# redirect to another URL
nelmio_security:
    external_redirects:
        override: /foo
```

If you want to display the URL that was blocked on the overriding page you can
specify the `forward_as` parameter, which defines which query parameter will
receive the URL. For example using the config below, doing a redirect to
`http://example.org/` will be overridden to `/external-redirect?redirUrl=http://example.org/`.

```yaml
# redirect and forward the overridden URL
nelmio_security:
    external_redirects:
        override: /external-redirect
        forward_as: redirUrl
```

Since it's quite common to have to redirect outside the website for legit reasons,
typically OAuth logins and such, you can whitelist a few domain names. All their subdomains
will be whitelisted as well, so that allows you to whitelist your own website's subdomains
if needed.

```yaml
nelmio_security:
    external_redirects:
        abort: true
        whitelist:
            - twitter.com
            - facebook.com
```

### **Forced HTTPS/SSL Handling**:

By default, this option forces your entire site to use SSL, always. It redirect all users
reaching the site with a http:// URL to a https:// URL.

The base configuration for this is the following:

```yaml
nelmio_security:
    forced_ssl: ~
```

If you turn this option on, it's recommended to also set your session cookie to be secure,
and all other cookies your send for that matter. You can do the former using:

```yaml
framework:
    session:
        cookie_secure: true
```

To keep a few URLs from being force-redirected to SSL you can define a whitelist of regular
expressions:

```yaml
nelmio_security:
    forced_ssl:
        enabled: true
        whitelist:
            - ^/unsecure/
```

Then if you want to push it further, you can enable
[HTTP Strict Transport Security (HSTS)](http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02).
This is basically sending a header to tell the browser that your site must always be
accessed using SSL. If a user enters a http:// URL, the browser will convert it to https://
automatically, and will do so before making any request, which prevents man-in-the-middle
attacks.

The browser will cache the value for as long as the specified `hsts_max_age` (in seconds), and if
you turn on the `hsts_subdomains` option, the behavior will be applied to all subdomains as well.

```yaml
nelmio_security:
    forced_ssl:
        hsts_max_age: 2592000 # 30 days
        hsts_subdomains: true
```

You can also tell the browser to add your site to the list of known HSTS sites, by enabling
`hsts_preload`. Once your site has appeared in the Chrome and Firefox preload lists, then new
users who come to your site will already be redirected to https urls.

```yaml
nelmio_security:
    forced_ssl:
        hsts_max_age: 10886400 # 18 weeks
        hsts_preload: true
```

> **Note:** A value of at least 18 weeks is currently required by [Chrome](https://hstspreload.appspot.com)
> and [Firefox](https://blog.mozilla.org/security/2012/11/01/preloading-hsts/). It seems
> `hsts_subdomains` must also be enabled for preloading to work.

You can speed up the inclusion process by submitting your site to the [HSTS Preload List](https://hstspreload.appspot.com).

A small word of caution: While HSTS is great for security, it means that if the browser
can not establish your SSL certificate is valid, it will not allow the user to query your site.
That just means you should be careful and renew your certificate in due time.

Note: HSTS presently (Jan. 2015) works in Firefox 4+, Chrome 4+ and Opera 12+.
      Check [caniuse](http://caniuse.com/#feat=stricttransportsecurity) for HSTS support in other browsers.

### **Flexible HTTPS/SSL Handling**:

The best way to handle SSL securely is to enable it for your entire site.

However in some cases this is not desirable, be it for caching or performance reasons,
or simply because most visitors of your site are anonymous and don't benefit much from the
added privacy and security of SSL.

If you don't want to enable SSL across the board, you need to avoid that people on insecure
networks (typically open Wi-Fi) get their session cookie stolen by sending it non-encrypted.
The way to achieve this is to set your session cookie to be secure as such - but don't do
it just yet, keep reading to the end.

```yaml
framework:
    session:
        cookie_secure: true
```

If you use the remember-me functionality, you would also mark that one as secure:

```yaml
security:
    firewalls:
        somename:
            remember_me:
                secure: true
```

Now if you do this, you have two problems. First, insecure pages will not be able to use
the session anymore, which can be inconvenient. Second, if a logged in user gets to a
non-https page of your site, it is seen as anonymous since his browser will not send the
session cookie. To fix this, this bundle sets a new insecure cookie
(`flexible_ssl.cookie_name`, defaults to `auth`) once a user logs in. That way, if any page
is accessed insecurely by a logged in user, he is redirected to the secure version of the
page, and his session is then visible to the framework.

Enabling the `flexible_ssl` option of the NelmioSecurityBundle will make sure that
logged-in users are always seeing secure pages, and it will make sure their session cookie
is secure, but anonymous users will still be able to have an insecure session, if you need
to use it to store non critical data like language settings and whatnot. The remember-me
cookie will also be made always secure, even if you leave the setting to false.

```yaml
nelmio_security:
    flexible_ssl:
        cookie_name: auth
        unsecured_logout: false
```

You have to configure one more thing in your security configuration though, every firewall
should have our logout listener added, so that the special `auth` cookie can be cleared when
users log out. You can do it as such:

```yaml
security:
    firewalls:
        somename:
            # ...
            logout:
                handlers:
                    - nelmio_security.flexible_ssl_listener
```

On logout, if you would like users to be redirected to an unsecure page set ``unsecured_logout``
to true.

### Cookie Session Handler:

You can configure the session handler to use a cookie based storage. There are various reasons to do this, but generally speaking unless you have a very good one [you should avoid it](http://wonko.com/post/why-you-probably-shouldnt-use-cookies-to-store-session-data).

**WARNING**: by default the session is not encrypted, it is your responsibility to properly
configure the Encrypted Cookies section to include the session cookie (default name: session).
The size limit of a cookie is 4KB, so make sure you are not storing objects or long
strings in the session.

```yaml
framework:
    session:
        handler_id: nelmio_security.session.handler

nelmio_security:
    cookie_session:
        enabled: true
        name: session

    encrypted_cookie:
        names: [session]
```

### Content Type Sniffing

Disables the content type sniffing for script resources. Forces the browser to only execute script files with valid
content type headers. This is a non-standard header from Microsoft, more information can be found in
[their documentation at MSDN](http://msdn.microsoft.com/en-us/library/ie/gg622941.aspx).

```yaml
nelmio_security:
    content_type:
        nosniff: true
```

## License

Released under the MIT License, see LICENSE.


text:
!function() {

    var   Class         = require('ee-class')
        , log           = require('ee-log')
        , type          = require('ee-types')
        , BaseValidator = require('../lib/BaseValidator');

    module.exports = new Class({
        inherits: BaseValidator

        /**
         * check the input type
         */
        , isValid: function(input) {
            return (this._validType(input) && input.length <= this.value) ? this.VALID : this.INVALID;
        }

        /**
         *
         */
        , _validType: function(input) {
            return (type.string(input) ||  type.array(input) || type.buffer(input));
        }

         /**
         * returns meaningful error message data
         */
        , getData: function(input) {
            return {
                  expected  : this.value
                , got       : this._validType(input) ? input.length : 'invalid type: '+type(input)
            };
        }
    });
}();


text:
#pragma once
#include <aws/dynamodb/DynamoDB_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/dynamodb/model/Projection.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/KeySchemaElement.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace DynamoDB
{
namespace Model
{
  /*

Represents the properties of a global secondary index.

  */
  class AWS_DYNAMODB_API GlobalSecondaryIndex
  {
  public:
    GlobalSecondaryIndex();
    GlobalSecondaryIndex(const Aws::Utils::Json::JsonValue& jsonValue);
    GlobalSecondaryIndex& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline const Aws::String& GetIndexName() const{ return m_indexName; }

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline void SetIndexName(const Aws::String& value) { m_indexNameHasBeenSet = true; m_indexName = value; }

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline void SetIndexName(Aws::String&& value) { m_indexNameHasBeenSet = true; m_indexName = value; }

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline void SetIndexName(const char* value) { m_indexNameHasBeenSet = true; m_indexName.assign(value); }

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline GlobalSecondaryIndex& WithIndexName(const Aws::String& value) { SetIndexName(value); return *this;}

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline GlobalSecondaryIndex& WithIndexName(Aws::String&& value) { SetIndexName(value); return *this;}

    /*

The name of the global secondary index. The name must be unique among all other indexes on this table.

    */
    inline GlobalSecondaryIndex& WithIndexName(const char* value) { SetIndexName(value); return *this;}

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline const Aws::Vector<KeySchemaElement>& GetKeySchema() const{ return m_keySchema; }

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline void SetKeySchema(const Aws::Vector<KeySchemaElement>& value) { m_keySchemaHasBeenSet = true; m_keySchema = value; }

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline void SetKeySchema(Aws::Vector<KeySchemaElement>&& value) { m_keySchemaHasBeenSet = true; m_keySchema = value; }

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline GlobalSecondaryIndex& WithKeySchema(const Aws::Vector<KeySchemaElement>& value) { SetKeySchema(value); return *this;}

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline GlobalSecondaryIndex& WithKeySchema(Aws::Vector<KeySchemaElement>&& value) { SetKeySchema(value); return *this;}

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline GlobalSecondaryIndex& AddKeySchema(const KeySchemaElement& value) { m_keySchemaHasBeenSet = true; m_keySchema.push_back(value); return *this; }

    /*

The complete key schema for a global secondary index, which consists of one or more pairs of attribute names and key types (HASH or RANGE).

    */
    inline GlobalSecondaryIndex& AddKeySchema(KeySchemaElement&& value) { m_keySchemaHasBeenSet = true; m_keySchema.push_back(value); return *this; }

    inline const Projection& GetProjection() const{ return m_projection; }

    inline void SetProjection(const Projection& value) { m_projectionHasBeenSet = true; m_projection = value; }

    inline void SetProjection(Projection&& value) { m_projectionHasBeenSet = true; m_projection = value; }

    inline GlobalSecondaryIndex& WithProjection(const Projection& value) { SetProjection(value); return *this;}

    inline GlobalSecondaryIndex& WithProjection(Projection&& value) { SetProjection(value); return *this;}

    inline const ProvisionedThroughput& GetProvisionedThroughput() const{ return m_provisionedThroughput; }

    inline void SetProvisionedThroughput(const ProvisionedThroughput& value) { m_provisionedThroughputHasBeenSet = true; m_provisionedThroughput = value; }

    inline void SetProvisionedThroughput(ProvisionedThroughput&& value) { m_provisionedThroughputHasBeenSet = true; m_provisionedThroughput = value; }

    inline GlobalSecondaryIndex& WithProvisionedThroughput(const ProvisionedThroughput& value) { SetProvisionedThroughput(value); return *this;}

    inline GlobalSecondaryIndex& WithProvisionedThroughput(ProvisionedThroughput&& value) { SetProvisionedThroughput(value); return *this;}

  private:
    Aws::String m_indexName;
    bool m_indexNameHasBeenSet;
    Aws::Vector<KeySchemaElement> m_keySchema;
    bool m_keySchemaHasBeenSet;
    Projection m_projection;
    bool m_projectionHasBeenSet;
    ProvisionedThroughput m_provisionedThroughput;
    bool m_provisionedThroughputHasBeenSet;
  };

} // namespace Model
} // namespace DynamoDB
} // namespace Aws


text:
"""The project tab widget to hold the canvas"""

from PyQt4 import QtCore, QtGui

class TabWidget(QtGui.QTabWidget):
    def __init__(self, parent = None):
        """
        Create a project tab widget.
        """
        QtGui.QTabWidget.__init__(self, parent)
        self.chosenSize = None
        self.setMinimumSize(400, 300)
        self.timer = QtCore.QTimer()

        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.resetMinsize)

    def resetMinsize(self):
        """
        Unlock the minimum size.
        """
        self.timer.stop()
        self.setMinimumSize(400, 300)

    def setGeometry(self, rect):
        """
        Set the widget geometry.
        """
        self.chosenSize = QtCore.QSize(rect.width(), rect.height())
        self.setMinimumSize(self.chosenSize)
        self.timer.start(1000)
        QtGui.QTabWidget.setGeometry(self, rect)

    def sizeHint(self):
        """
        Provide a size hint.
        """
        if self.chosenSize:
            return self.chosenSize
        else:
            return QtGui.QTabWidget.sizeHint(self)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2015 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<name>midPoint Provisioning</name>
	<artifactId>provisioning</artifactId>
	<packaging>pom</packaging>
	<parent>
		<artifactId>parent</artifactId>
		<groupId>com.evolveum.midpoint</groupId>
		<version>3.5-SNAPSHOT</version>
		<relativePath>../build-system/pom.xml</relativePath>
	</parent>
	<organization>
		<name>Evolveum</name>
		<url>http://www.evolveum.com</url>
	</organization>
	<licenses>
		<license>
			<name>Apache License v2.0</name>
            		<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<issueManagement>
		<system>Atlassian JIRA</system>
		<url>http://jira.evolveum.com/</url>
	</issueManagement>
	<scm>
		<connection>https://github.com/Evolveum/midpoint.git</connection>
		<developerConnection>git@github.com:Evolveum/midpoint.git</developerConnection>
		<url>https://fisheye.evolveum.com/browse/midPoint</url>
	</scm>
	<modules>
		<module>provisioning-api</module>
		<module>provisioning-impl</module>
	</modules>
	<dependencies>
    	<dependency> <!-- Not used, but required for surefire plugin not to complain -->
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
namespace Microsoft.Azure.Management.Media.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Describes the settings to be used when encoding the input video into a
    /// desired output bitrate layer with the H.264 video codec.
    /// </summary>
    [Newtonsoft.Json.JsonObject("#Microsoft.Media.H264Layer")]
    public partial class H264Layer : VideoLayer
    {
        /// <summary>
        /// Initializes a new instance of the H264Layer class.
        /// </summary>
        public H264Layer()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the H264Layer class.
        /// </summary>
        /// <param name="width">The width of the output video for this layer.
        /// The value can be absolute (in pixels) or relative (in percentage).
        /// For example 50% means the output video has half as many pixels in
        /// width as the input.</param>
        /// <param name="height">The height of the output video for this layer.
        /// The value can be absolute (in pixels) or relative (in percentage).
        /// For example 50% means the output video has half as many pixels in
        /// height as the input.</param>
        /// <param name="label">The alphanumeric label for this layer, which
        /// can be used in multiplexing different video and audio layers, or in
        /// naming the output file.</param>
        /// <param name="bitrate">The average bitrate in bits per second at
        /// which to encode the input video when generating this layer. This is
        /// a required field.</param>
        /// <param name="maxBitrate">The maximum bitrate (in bits per second),
        /// at which the VBV buffer should be assumed to refill. If not
        /// specified, defaults to the same value as bitrate.</param>
        /// <param name="bFrames">The number of B-frames to be used when
        /// encoding this layer.  If not specified, the encoder chooses an
        /// appropriate number based on the video profile and level.</param>
        /// <param name="frameRate">The frame rate (in frames per second) at
        /// which to encode this layer. The value can be in the form of M/N
        /// where M and N are integers (For example, 30000/1001), or in the
        /// form of a number (For example, 30, or 29.97). The encoder enforces
        /// constraints on allowed frame rates based on the profile and level.
        /// If it is not specified, the encoder will use the same frame rate as
        /// the input video.</param>
        /// <param name="slices">The number of slices to be used when encoding
        /// this layer. If not specified, default is zero, which means that
        /// encoder will use a single slice for each frame.</param>
        /// <param name="adaptiveBFrame">Whether or not adaptive B-frames are
        /// to be used when encoding this layer. If not specified, the encoder
        /// will turn it on whenever the video profile permits its use.</param>
        /// <param name="profile">Which profile of the H.264 standard should be
        /// used when encoding this layer. Default is Auto. Possible values
        /// include: 'Auto', 'Baseline', 'Main', 'High', 'High422',
        /// 'High444'</param>
        /// <param name="level">Which level of the H.264 standard should be
        /// used when encoding this layer. The value can be Auto, or a number
        /// that matches the H.264 profile. If not specified, the default is
        /// Auto, which lets the encoder choose the Level that is appropriate
        /// for this layer.</param>
        /// <param name="bufferWindow">The VBV buffer window length. The value
        /// should be in ISO 8601 format. The value should be in the range
        /// [0.1-100] seconds. The default is 5 seconds (for example,
        /// PT5S).</param>
        /// <param name="referenceFrames">The number of reference frames to be
        /// used when encoding this layer. If not specified, the encoder
        /// determines an appropriate number based on the encoder complexity
        /// setting.</param>
        /// <param name="entropyMode">The entropy mode to be used for this
        /// layer. If not specified, the encoder chooses the mode that is
        /// appropriate for the profile and level. Possible values include:
        /// 'Cabac', 'Cavlc'</param>
        public H264Layer(string width = default(string), string height = default(string), string label = default(string), int? bitrate = default(int?), int? maxBitrate = default(int?), int? bFrames = default(int?), string frameRate = default(string), int? slices = default(int?), bool? adaptiveBFrame = default(bool?), H264VideoProfile? profile = default(H264VideoProfile?), string level = default(string), System.TimeSpan? bufferWindow = default(System.TimeSpan?), int? referenceFrames = default(int?), EntropyMode? entropyMode = default(EntropyMode?))
            : base(width, height, label, bitrate, maxBitrate, bFrames, frameRate, slices, adaptiveBFrame)
        {
            Profile = profile;
            Level = level;
            BufferWindow = bufferWindow;
            ReferenceFrames = referenceFrames;
            EntropyMode = entropyMode;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets which profile of the H.264 standard should be used
        /// when encoding this layer. Default is Auto. Possible values include:
        /// 'Auto', 'Baseline', 'Main', 'High', 'High422', 'High444'
        /// </summary>
        [JsonProperty(PropertyName = "profile")]
        public H264VideoProfile? Profile { get; set; }

        /// <summary>
        /// Gets or sets which level of the H.264 standard should be used when
        /// encoding this layer. The value can be Auto, or a number that
        /// matches the H.264 profile. If not specified, the default is Auto,
        /// which lets the encoder choose the Level that is appropriate for
        /// this layer.
        /// </summary>
        [JsonProperty(PropertyName = "level")]
        public string Level { get; set; }

        /// <summary>
        /// Gets or sets the VBV buffer window length. The value should be in
        /// ISO 8601 format. The value should be in the range [0.1-100]
        /// seconds. The default is 5 seconds (for example, PT5S).
        /// </summary>
        [JsonProperty(PropertyName = "bufferWindow")]
        public System.TimeSpan? BufferWindow { get; set; }

        /// <summary>
        /// Gets or sets the number of reference frames to be used when
        /// encoding this layer. If not specified, the encoder determines an
        /// appropriate number based on the encoder complexity setting.
        /// </summary>
        [JsonProperty(PropertyName = "referenceFrames")]
        public int? ReferenceFrames { get; set; }

        /// <summary>
        /// Gets or sets the entropy mode to be used for this layer. If not
        /// specified, the encoder chooses the mode that is appropriate for the
        /// profile and level. Possible values include: 'Cabac', 'Cavlc'
        /// </summary>
        [JsonProperty(PropertyName = "entropyMode")]
        public EntropyMode? EntropyMode { get; set; }

    }
}