text:
<?php
/*
* Add-on Name: Swatch Book for Visual Composer
* Add-on URI: http://.brainstormforce.com/demos/ultimate/swatch-book
*/
if(!class_exists('Ultimate_Swatch_Book')){
	class Ultimate_Swatch_Book{
		var $swatch_trans_bg_img;
		var $swatch_width;
		var $swatch_height;
		function __construct(){
			add_action( 'admin_init', array($this, 'swatch_book_init'));
			//add_action( 'wp_enqueue_scripts', array( $this, 'frontend_scripts') );
			if(function_exists('vc_is_inline')){
				if(!vc_is_inline()){
					add_shortcode( 'swatch_container', array($this, 'swatch_container' ) );
					add_shortcode( 'swatch_item', array($this, 'swatch_item' ) );
				}
			} else {
				add_shortcode( 'swatch_container', array($this, 'swatch_container' ) );
				add_shortcode( 'swatch_item', array($this, 'swatch_item' ) );
			}
		}

		/*function frontend_scripts($post){
			global $post;
			$count = 0;
			$content = $post->the_content;
			$shortcodes = array('swatch_container','swatch_item');
			foreach($shortcodes as $shortcode){
				if(has_shortcode($content, $shortcode)) {
					$count++;
				}
			}
			if($count !== 0){
				wp_enqueue_script('modernizr-79639-js',plugins_url('../assets/js/modernizr.custom.js',__FILE__));
				wp_enqueue_script('swatchbook-js',plugins_url('../assets/js/jquery.swatchbook.js',__FILE__));
				wp_enqueue_style('swatchbook-css',plugins_url('../assets/css/swatchbook.css',__FILE__));
			}
		}*/

		function swatch_book_init(){
			if(function_exists('vc_map'))
			{
				vc_map(
					array(
						"name" => __("Swatch Book","smile"),
						"base" => "swatch_container",
						"class" => "vc_swatch_container",
						"icon" => "vc_swatch_container",
						"category" => __("Ultimate VC Addons","smile"),
						"as_parent" => array('only' => 'swatch_item'),
						"description" => __("Interactive swatch strips.","smile"),
						"content_element" => true,
						"show_settings_on_create" => true,
						"js_view" => 'VcColumnView',
						"params" => array(
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Swatch Book Style", "smile"),
								"param_name" => "swatch_style",
								"value" => array(
									"Style 1" => "style-1",
									"Style 2" => "style-2",
									"Style 3" => "style-3",
									"Style 4" => "style-4",
									"Style 5" => "style-5",
									"Custom Style" => "custom",
								),
								"description" => __("","smile"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Index of Center Strip", "smile"),
								"param_name" => "swatch_index_center",
								"value" => 1,
								"min" => 1,
								"max" => 100,
								"suffix" => "",
								"description" => __("The index of the "centered" item, the one that will have an angle of 0 degrees when the swatch book is opened", "smile"),
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Space Between Two Swatches", "smile"),
								"param_name" => "swatch_space_degree",
								"value" => 1,
								"min" => 1,
								"max" => 1000,
								"suffix" => "",
								"description" => __("The space between the items (in degrees)", "smile"),
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Transition Speed", "smile"),
								"param_name" => "swatch_trans_speed",
								"value" => 1,
								"min" => 1,
								"max" => 10000,
								"suffix" => "",
								"description" => __("The speed and transition timing functions", "smile"),
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Distance From Open Item To Its Next Sibling", "smile"),
								"param_name" => "swatch_distance_sibling",
								"value" => 1,
								"min" => 1,
								"max" => 10000,
								"suffix" => "",
								"description" => __("Distance From Opened item's next siblings (neighbor : 4)", "smile"),
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "chk-switch",
								"class" => "",
								"heading" => __("Swatch book will be initially closed", "upb_parallax"),
								"param_name" => "swatch_init_closed",
								"value" => "",
								"options" => array(
										"closed" => array(
											"label" => "",
											"on" => "Yes",
											"off" => "No",
										)
									),
								"description" => "",
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Index of the item that will be opened initially", "smile"),
								"param_name" => "swatch_open_at",
								"value" => 1,
								"min" => 1,
								"max" => 100,
								"suffix" => "",
								"description" => __("", "smile"),
								"dependency" => Array("element" => "swatch_style", "value" => "custom"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Width", "smile"),
								"param_name" => "swatch_width",
								"value" => 130,
								"min" => 100,
								"max" => 1000,
								"suffix" => "",
								"description" => __("", "smile"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Height", "smile"),
								"param_name" => "swatch_height",
								"value" => 400,
								"min" => 100,
								"max" => 1000,
								"suffix" => "",
								"description" => __("", "smile"),
								"group" => "Initial Settings",
							),
							array(
								"type" => "attach_image",
								"class" => "",
								"heading" => __("Background Transparent Pattern", "smile"),
								"param_name" => "swatch_trans_bg_img",
								"value" => "",
								"description" => "",
								"group" => "Initial Settings",
							),
							array(
								"type" => "textfield",
								"class" => "",
								"heading" => __("Main Strip Title Text", "smile"),
								"param_name" => "swatch_main_strip_text",
								"value" => "",
								"description" => "",
								"group" => "Initial Settings",
							),
							array(
								"type" => "textfield",
								"class" => "",
								"heading" => __("Main Strip Highlight Text", "smile"),
								"param_name" => "swatch_main_strip_highlight_text",
								"value" => "",
								"description" => "",
								"group" => "Initial Settings",
							),
							array(
								"type" => "ultimate_google_fonts",
								"heading" => __("Font Family", "smile"),
								"param_name" => "main_strip_font_family",
								"description" => __("Select the font of your choice. You can add new in the collection here.", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" 		=> "ultimate_google_fonts_style",
								"heading" 	 =>	__("Font Style", "smile"),
								"param_name"  =>	"main_strip_font_style",
								"group" => "Advanced Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Main Strip Title Font Size", "smile"),
								"param_name" => "swatch_main_strip_font_size",
								"value" => 16,
								"min" => 1,
								"max" => 72,
								"suffix" => "px",
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Main Strip Title Font Style", "smile"),
								"param_name" => "swatch_main_strip_font_style",
								"value" => array(
									"Normal" => "normal",
									"Bold" => "bold",
									"Italic" => "italic",
								),
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Main Strip Title Color:", "smile"),
								"param_name" => "swatch_main_strip_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Main Strip Title Background Color:", "smile"),
								"param_name" => "swatch_main_strip_bg_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Main Strip Title Highlight Font Size", "smile"),
								"param_name" => "swatch_main_strip_highlight_font_size",
								"value" => 16,
								"min" => 1,
								"max" => 72,
								"suffix" => "px",
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Main Strip Title Highlight Font Weight", "smile"),
								"param_name" => "swatch_main_strip_highlight_font_weight",
								"value" => array(
									"Normal" => "normal",
									"Bold" => "bold",
									"Italic" => "italic",
								),
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Main Strip Title Highlight Color", "smile"),
								"param_name" => "swatch_main_strip_highlight_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
						)
					)
				); // vc_map

				vc_map(
					array(
						"name" => __("Swatch Book Item", "js_composer"),
						"base" => "swatch_item",
						"class" => "vc_swatch_item",
						"icon" => "vc_swatch_item",
						"content_element" => true,
						"as_child" => array('only' => 'swatch_container'),
						"params" => array(
							array(
								"type" => "textfield",
								"class" => "",
								"heading" => __("Strip Title Text", "smile"),
								"param_name" => "swatch_strip_text",
								"value" => "",
								"description" => "",
							),
														array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Icon to display:", "smile"),
								"param_name" => "icon_type",
								"value" => array(
									"Font Icon Manager" => "selector",
									"Custom Image Icon" => "custom",
								),
								"description" => __("Use an existing font icon or upload a custom image.", "smile")
							),
							array(
								"type" => "icon_manager",
								"class" => "",
								"heading" => __("Select Icon ","smile"),
								"param_name" => "icon",
								"value" => "",
								"description" => __("Click and select icon of your choice. If you can't find the one that suits for your purpose, you can add new here.", "smile"),
								"dependency" => Array("element" => "icon_type","value" => array("selector")),
							),
							array(
								"type" => "attach_image",
								"class" => "",
								"heading" => __("Upload Image Icon:", "smile"),
								"param_name" => "icon_img",
								"value" => "",
								"description" => __("Upload the custom image icon.", "smile"),
								"dependency" => Array("element" => "icon_type","value" => array("custom")),
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Image Width", "smile"),
								"param_name" => "img_width",
								"value" => 48,
								"min" => 16,
								"max" => 512,
								"suffix" => "px",
								"description" => __("Provide image width", "smile"),
								"dependency" => Array("element" => "icon_type","value" => array("custom")),
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Size of Icon", "smile"),
								"param_name" => "icon_size",
								"value" => 32,
								"min" => 12,
								"max" => 72,
								"suffix" => "px",
								"description" => __("How big would you like it?", "smile"),
								"dependency" => Array("element" => "icon_type","value" => array("selector")),
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Color", "smile"),
								"param_name" => "icon_color",
								"value" => "#333333",
								"description" => __("Give it a nice paint!", "smile"),
								"dependency" => Array("element" => "icon_type","value" => array("selector")),
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Icon Style", "smile"),
								"param_name" => "icon_style",
								"value" => array(
									"Simple" => "none",
									"Circle Background" => "circle",
									"Square Background" => "square",
									"Design your own" => "advanced",
								),
								"description" => __("We have given three quick preset if you are in a hurry. Otherwise, create your own with various options.", "smile"),
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Background Color", "smile"),
								"param_name" => "icon_color_bg",
								"value" => "#ffffff",
								"description" => __("Select background color for icon.", "smile"),
								"dependency" => Array("element" => "icon_style", "value" => array("circle","square","advanced")),
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Icon Border Style", "smile"),
								"param_name" => "icon_border_style",
								"value" => array(
									"None" => "",
									"Solid"=> "solid",
									"Dashed" => "dashed",
									"Dotted" => "dotted",
									"Double" => "double",
									"Inset" => "inset",
									"Outset" => "outset",
								),
								"description" => __("Select the border style for icon.","smile"),
								"dependency" => Array("element" => "icon_style", "value" => array("advanced")),
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Border Color", "smile"),
								"param_name" => "icon_color_border",
								"value" => "#333333",
								"description" => __("Select border color for icon.", "smile"),
								"dependency" => Array("element" => "icon_border_style", "not_empty" => true),
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Border Width", "smile"),
								"param_name" => "icon_border_size",
								"value" => 1,
								"min" => 1,
								"max" => 10,
								"suffix" => "px",
								"description" => __("Thickness of the border.", "smile"),
								"dependency" => Array("element" => "icon_border_style", "not_empty" => true),
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Border Radius", "smile"),
								"param_name" => "icon_border_radius",
								"value" => 500,
								"min" => 1,
								"max" => 500,
								"suffix" => "px",
								"description" => __("0 pixel value will create a square border. As you increase the value, the shape convert in circle slowly. (e.g 500 pixels).", "smile"),
								"dependency" => Array("element" => "icon_border_style", "not_empty" => true),
							),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Background Size", "smile"),
								"param_name" => "icon_border_spacing",
								"value" => 50,
								"min" => 30,
								"max" => 500,
								"suffix" => "px",
								"description" => __("Spacing from center of the icon till the boundary of border / background", "smile"),
								"dependency" => Array("element" => "icon_style", "value" => array("advanced")),
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Animation","smile"),
								"param_name" => "icon_animation",
								"value" => array(
							 		__("No Animation","smile") => "",
									__("Swing","smile") => "swing",
									__("Pulse","smile") => "pulse",
									__("Fade In","smile") => "fadeIn",
									__("Fade In Up","smile") => "fadeInUp",
									__("Fade In Down","smile") => "fadeInDown",
									__("Fade In Left","smile") => "fadeInLeft",
									__("Fade In Right","smile") => "fadeInRight",
									__("Fade In Up Long","smile") => "fadeInUpBig",
									__("Fade In Down Long","smile") => "fadeInDownBig",
									__("Fade In Left Long","smile") => "fadeInLeftBig",
									__("Fade In Right Long","smile") => "fadeInRightBig",
									__("Slide In Down","smile") => "slideInDown",
									__("Slide In Left","smile") => "slideInLeft",
									__("Slide In Left","smile") => "slideInLeft",
									__("Bounce In","smile") => "bounceIn",
									__("Bounce In Up","smile") => "bounceInUp",
									__("Bounce In Down","smile") => "bounceInDown",
									__("Bounce In Left","smile") => "bounceInLeft",
									__("Bounce In Right","smile") => "bounceInRight",
									__("Rotate In","smile") => "rotateIn",
									__("Light Speed In","smile") => "lightSpeedIn",
									__("Roll In","smile") => "rollIn",
									),
								"description" => __("Like CSS3 Animations? We have several options for you!","smile")
						  	),
							array(
								"type" => "number",
								"class" => "",
								"heading" => __("Strip Title Font Size", "smile"),
								"param_name" => "swatch_strip_font_size",
								"value" => 16,
								"min" => 1,
								"max" => 72,
								"suffix" => "px",
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "dropdown",
								"class" => "",
								"heading" => __("Strip Title Font Weight", "smile"),
								"param_name" => "swatch_strip_font_weight",
								"value" => array(
									"Normal" => "normal",
									"Bold" => "bold",
									"Italic" => "italic",
								),
								"description" => __("", "smile"),
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Strip Title Color:", "smile"),
								"param_name" => "swatch_strip_font_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Strip Title Background Color:", "smile"),
								"param_name" => "swatch_strip_title_bg_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
							array(
								"type" => "colorpicker",
								"class" => "",
								"heading" => __("Strip Background Color:", "smile"),
								"param_name" => "swatch_strip_bg_color",
								"value" => "",
								"description" => "",
								"group" => "Advanced Settings",
							),
						)
					)
				); // vc_map
			}
		}

		function swatch_container($atts,$content=null){
			$swatch_style = $swatch_index_center = $swatch_space_degree = $swatch_trans_speed = $swatch_distance_sibling = $swatch_init_closed = $swatch_open_at
 = $swatch_width = $swatch_height = $swatch_trans_bg_img = $swatch_main_strip_text = $swatch_main_strip_highlight_text = $swatch_main_strip_font_size = $swatch_main_strip_font_style = $swatch_main_strip_color = $swatch_main_strip_highlight_font_size = $swatch_main_strip_highlight_font_weight = $swatch_main_strip_highlight_color = $swatch_main_strip_bg_color = $main_strip_font_family = $main_strip_font_style = '';

 			wp_enqueue_script('modernizr-79639-js',plugins_url('../assets/js/modernizr.custom.js',__FILE__));
			wp_enqueue_script('swatchbook-js',plugins_url('../assets/js/jquery.swatchbook.js',__FILE__));
			wp_enqueue_style('swatchbook-css',plugins_url('../assets/css/swatchbook.css',__FILE__));

			extract(shortcode_atts(array(
				'swatch_style' => '',
				'swatch_index_center' => '',
				'swatch_space_degree' => '',
				'swatch_trans_speed' => '',
				'swatch_distance_sibling' => '',
				'swatch_init_closed' => '',
				'swatch_open_at' => '',
				'swatch_width' => '',
				'swatch_height' => '',
				'swatch_trans_bg_img' => '',
				'swatch_main_strip_text' => '',
				'swatch_main_strip_highlight_text' => '',
				'swatch_main_strip_font_size' => '',
				'swatch_main_strip_font_style' => '',
				'swatch_main_strip_color' => '',
				'swatch_main_strip_highlight_font_size' => '',
				'swatch_main_strip_highlight_font_weight' => '',
				'swatch_main_strip_highlight_color' => '',
				'swatch_main_strip_bg_color' => '',
				'main_strip_font_family' => '',
				'main_strip_font_style' => '',
			),$atts));
			$output = $img = $style = $highlight_style = $main_style = '';
			$uid = uniqid();
			if($swatch_trans_bg_img !== ''){
				$img = wp_get_attachment_image_src( $swatch_trans_bg_img, 'large');
				$img = $img[0];
				$this->swatch_trans_bg_img = $swatch_trans_bg_img;
				$style .= 'background-image: url('.$img.');';
			}
			if($swatch_width !== ''){
				$style .= 'width:'.$swatch_width.'px;';
				$this->swatch_width = $swatch_width;
			}
			if($swatch_height !== ''){
				$style .= 'height:'.$swatch_height.'px;';
				$this->swatch_height = $swatch_height;
			}

			if($swatch_main_strip_highlight_font_size !== ''){
				$highlight_style .= 'font-size:'.$swatch_main_strip_highlight_font_size.'px;';
			}
			if($swatch_main_strip_highlight_font_weight !== ''){
				$highlight_style .= 'font-weight:'.$swatch_main_strip_highlight_font_weight.';';
			}
			if($swatch_main_strip_highlight_color !== ''){
				$highlight_style .= 'color:'.$swatch_main_strip_highlight_color.';';
			}

			if($main_strip_font_family != '')
			{
				$mhfont_family = get_ultimate_font_family($main_strip_font_family);
				$main_style .= 'font-family:\''.$mhfont_family.'\';';
			}
			$main_style .= get_ultimate_font_style($main_strip_font_style);

			if($swatch_main_strip_font_size !== ''){
				$main_style .= 'font-size:'.$swatch_main_strip_font_size.'px;';
			}
			if($swatch_main_strip_font_style !== ''){
				$main_style .= 'font-weight:'.$swatch_main_strip_font_style.';';
			}
			if($swatch_main_strip_color !== ''){
				$main_style .= 'color:'.$swatch_main_strip_color.';';
			}
			if($swatch_main_strip_bg_color !== ''){
				$main_style .= 'background:'.$swatch_main_strip_bg_color.';';
			}

			$output .= '
';
			$output .= do_shortcode($content);
			$output .= '
';
			$output .= '
'.$swatch_main_strip_text.'
';
			$output .= '
'.$swatch_main_strip_highlight_text.'
';
			$output .= '
';
			$output .= '
';
			$output .= '';
			return $output;
		}

		function swatch_item($atts,$content=null){
			$icon_type = $icon_img = $img_width = $icon = $icon_color = $icon_color_bg = $icon_size = $icon_style = $icon_border_style = $icon_border_radius = $icon_color_border = $icon_border_size = $icon_border_spacing = $el_class = $icon_animation = $swatch_strip_font_size = $swatch_strip_font_weight =  $swatch_strip_font_color = $swatch_strip_bg_color = $swatch_strip_title_bg_color = '';
			extract(shortcode_atts(array(
				'swatch_strip_text' => '',
                'icon_type' => '',
				'icon' => '',
				'icon_img' => '',
				'img_width' => '',
				'icon_size' => '',
				'icon_color' => '',
				'icon_style' => '',
				'icon_color_bg' => '',
				'icon_color_border' => '',
				'icon_border_style' => '',
				'icon_border_size' => '',
				'icon_border_radius' => '',
				'icon_border_spacing' => '',
				'icon_animation' => '',
				'swatch_strip_font_size' => '',
				'swatch_strip_font_weight' => '',
				'swatch_strip_font_color' => '',
				'swatch_strip_bg_color' => '',
				'swatch_strip_title_bg_color' => ''
			),$atts));
			$output = '';
			$box_icon = do_shortcode('[just_icon icon_type="'.$icon_type.'" icon="'.$icon.'" icon_img="'.$icon_img.'" img_width="'.$img_width.'" icon_size="'.$icon_size.'" icon_color="'.$icon_color.'" icon_style="'.$icon_style.'" icon_color_bg="'.$icon_color_bg.'" icon_color_border="'.$icon_color_border.'"  icon_border_style="'.$icon_border_style.'" icon_border_size="'.$icon_border_size.'" icon_border_radius="'.$icon_border_radius.'" icon_border_spacing="'.$icon_border_spacing.'" icon_animation="'.$icon_animation.'"]');
			$style = '';
			if($this->swatch_trans_bg_img !== ''){
				$img = wp_get_attachment_image_src( $this->swatch_trans_bg_img, 'large');
				$img = $img[0];
				$style .= 'background-image: url('.$img.');';
			}
			if($swatch_strip_bg_color !== ''){
				$style .= 'background-color: '.$swatch_strip_bg_color.';';
			}
			if($this->swatch_width !== ''){
				$style .= 'width:'.$this->swatch_width.'px;';
			}
			if($this->swatch_height!== ''){
				$style .= 'height:'.$this->swatch_height.'px;';
			}
			$output .= '
';
        	$output .= ''.$box_icon.'';
        	$output .= '
'.$swatch_strip_text.'
';
    		$output .= '
';
			return $output;
		}
	}
	new Ultimate_Swatch_Book;
}
if(class_exists('WPBakeryShortCodesContainer'))
{
	class WPBakeryShortCode_swatch_container extends WPBakeryShortCodesContainer {

	}
	class WPBakeryShortCode_swatch_item extends WPBakeryShortCode {

	}
}


text:
import * as T from '../src/types';

import { ExampleFunctionRequest, ExampleFunctionResponseData } from '../src/example-function-model';

export async function main(context: T.Context<ExampleFunctionResponseData>, request: ExampleFunctionRequest) {

    if (request.query.setup) {
        console.log('Setup was triggered');
    }

    context.done(null, {
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'X-Told-Test-Header': 'test-header',
        },
        body: {
            ok: true,
            data: { text: 'Example Output' },
        }
    });
}

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_05.cpp
Label Definition File: CWE457_Use_of_Uninitialized_Variable__twointsclass_array.label.xml
Template File: sources-sinks-05.tmpl.cpp
*/
/*
 * @description
 * CWE: 457 Use of Uninitialized Variable
 * BadSource: no_init Don't initialize data
 * GoodSource: Initialize data
 * Sinks: use
 *    GoodSink: Initialize then use data
 *    BadSink : Use data
 * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse)
 *
 * */

#include "std_testcase.h"

/* The two variables below are not defined as "const", but are never
   assigned any other value, so a tool should be able to identify that
   reads of these will always return their initialized values. */
static int staticTrue = 1; /* true */
static int staticFalse = 0; /* false */

namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_05
{

#ifndef OMITBAD

void bad()
{
    TwoIntsClass * data;
    data = new TwoIntsClass[10];
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Don't initialize data */
        ; /* empty statement needed for some flow variants */
    }
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Use data without initializing it */
        for(int i=0; i<10; i++)
        {
            printIntLine(data[i].intOne);
            printIntLine(data[i].intTwo);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G1() - use badsource and goodsink by changing the second staticTrue to staticFalse */
static void goodB2G1()
{
    TwoIntsClass * data;
    data = new TwoIntsClass[10];
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Don't initialize data */
        ; /* empty statement needed for some flow variants */
    }
    if(staticFalse)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Ensure data is initialized before use */
        for(int i=0; i<10; i++)
        {
            data[i].intOne = i;
            data[i].intTwo = i;
        }
        for(int i=0; i<10; i++)
        {
            printIntLine(data[i].intOne);
            printIntLine(data[i].intTwo);
        }
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
    TwoIntsClass * data;
    data = new TwoIntsClass[10];
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Don't initialize data */
        ; /* empty statement needed for some flow variants */
    }
    if(staticTrue)
    {
        /* FIX: Ensure data is initialized before use */
        for(int i=0; i<10; i++)
        {
            data[i].intOne = i;
            data[i].intTwo = i;
        }
        for(int i=0; i<10; i++)
        {
            printIntLine(data[i].intOne);
            printIntLine(data[i].intTwo);
        }
    }
}

/* goodG2B1() - use goodsource and badsink by changing the first staticTrue to staticFalse */
static void goodG2B1()
{
    TwoIntsClass * data;
    data = new TwoIntsClass[10];
    if(staticFalse)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Completely initialize data */
        for(int i=0; i<10; i++)
        {
            data[i].intOne = i;
            data[i].intTwo = i;
        }
    }
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Use data without initializing it */
        for(int i=0; i<10; i++)
        {
            printIntLine(data[i].intOne);
            printIntLine(data[i].intTwo);
        }
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
    TwoIntsClass * data;
    data = new TwoIntsClass[10];
    if(staticTrue)
    {
        /* FIX: Completely initialize data */
        for(int i=0; i<10; i++)
        {
            data[i].intOne = i;
            data[i].intTwo = i;
        }
    }
    if(staticTrue)
    {
        /* POTENTIAL FLAW: Use data without initializing it */
        for(int i=0; i<10; i++)
        {
            printIntLine(data[i].intOne);
            printIntLine(data[i].intTwo);
        }
    }
}

void good()
{
    goodB2G1();
    goodB2G2();
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE457_Use_of_Uninitialized_Variable__twointsclass_array_new_no_init_05; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License

#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS

#include "cpul/cpulTestHarness.h"
#include "mx/core/Elements.h"
#include <sstream>

using namespace mx::core;

TEST( Test01, PartName )
{
	std::string indentString( INDENT );
	XsString value1{ "Flute" };
	XsString value2{ "Oboe" };
	PartName object1;
	PartName object2( value2 );
	PartNameAttributesPtr attributes1 = std::make_shared<PartNameAttributes>();
	PartNameAttributesPtr attributesNull;
    attributes1->hasFontStyle = true;
    attributes1->fontStyle = FontStyle::italic;
	/* set some attribute1 values here */
	object2.setAttributes( attributes1 );
	std::stringstream default_constructed;
	object1.toStream( default_constructed, 0 );
	std::stringstream object2_stream;
	object2.toStream( object2_stream, 2 );
	std::string expected = R"(<part-name></part-name>)";
	std::string actual = default_constructed.str();
	CHECK_EQUAL( expected, actual )
	expected = indentString+indentString+R"(<part-name font-style="italic">Oboe</part-name>)";
	actual = object2_stream.str();
	CHECK_EQUAL( expected, actual )
	value1 = object2.getValue();
	object1.setValue( value1 );
	std::stringstream o1;	std::stringstream o2;	bool isOneLineOnly = false;
	object1.streamContents( o1, 0, isOneLineOnly );
	object2.streamContents( o2, 0, isOneLineOnly );
	CHECK( isOneLineOnly )
	CHECK_EQUAL( o1.str(), o2.str() )
}

#endif


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Managing Blocking Operations</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" />
    <link rel="up" href="addfeatures.html" title="Chapter 5. Additional Features" />
    <link rel="prev" href="addfeatures.html" title="Chapter 5. Additional Features" />
    <link rel="next" href="noautoinit.html" title="Stop Auto-Initialization" />

          Managing Blocking Operations

          Prev
          Chapter 5. Additional Features
           Next

Managing Blocking Operations

                    When a replica is in the process of synchronizing with
                    its master, DB operations are blocked at some
                    points during this process until the synchronization is
                    completed.  For replicas with a heavy read load, these
                    blocked operations may represent an unacceptable loss
                    in throughput.

                    You can configure DB so that it will not block when synchronization is in
                    process. Instead, the DB operation will fail,

                            immediately throwing a
                            com.sleepycat.db.ReplicationLockoutException
                            exception.

                    When this happens, it is up to your application to determine
                    what action to take (that is, logging the event, making an appropriate user
                    response, retrying the operation, and so forth).

                To turn off blocking on synchronization, specify

                            ReplicationConfig.NOWAIT and
                            true to
                        Environment.setReplicationConfig().
                        To turn off this feature, specify
                        false for the
                        ReplicationConfig.NOWAIT field.

          Prev

            Up

           Next

          Chapter 5. Additional Features

            Home

           Stop Auto-Initialization


text:
class GbDataReading

  # Represents the start time (local) value from the IntervalReading ->
  # timePeriod structure
  attr_accessor :time_start

  # Represents the duration value from the IntervalReading -> timePeriod
  # structure
  attr_accessor :time_duration

  # Represents the value element in the IntervalReading structure
  attr_accessor :value

  # Represents the cost element in the IntervalReading structure
  attr_accessor :cost

end


text:
package com.thoughtworks.go.config.update;

import com.thoughtworks.go.config.BasicCruiseConfig;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.exceptions.EntityType;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.PackageMaterialConfig;
import com.thoughtworks.go.domain.packagerepository.PackageDefinition;
import com.thoughtworks.go.domain.packagerepository.PackageRepositories;
import com.thoughtworks.go.domain.packagerepository.PackageRepository;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import static com.thoughtworks.go.serverhealth.HealthStateType.forbidden;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class DeletePackageRepositoryCommandTest {
    private Username currentUser;
    private BasicCruiseConfig cruiseConfig;
    private PackageRepository packageRepository;
    private String repoId;
    private HttpLocalizedOperationResult result;

    @Mock
    private GoConfigService goConfigService;

    @Before
    public void setup() throws Exception {
        initMocks(this);
        currentUser = new Username(new CaseInsensitiveString("user"));
        cruiseConfig = new GoConfigMother().defaultCruiseConfig();
        packageRepository = new PackageRepository();
        repoId = "npm";
        packageRepository.setId(repoId);
        result = new HttpLocalizedOperationResult();
        cruiseConfig.setPackageRepositories(new PackageRepositories(packageRepository));
    }

    @Test
    public void shouldDeletePackageRepository() throws Exception {
        assertThat(cruiseConfig.getPackageRepositories().size(), is(1));
        assertThat(cruiseConfig.getPackageRepositories().find(repoId), is(packageRepository));
        DeletePackageRepositoryCommand command = new DeletePackageRepositoryCommand(goConfigService, packageRepository, currentUser, result);
        command.update(cruiseConfig);
        assertThat(cruiseConfig.getPackageRepositories().size(), is(0));
        assertNull(cruiseConfig.getPackageRepositories().find(repoId));
    }

    @Test
    public void shouldNotDeletePackageRepositoryIfItIsUsedAsAMaterialInPipeline() throws Exception {
        PackageDefinition pkg = new PackageDefinition();
        pkg.setId("pkg");
        packageRepository.addPackage(pkg);
        PackageMaterialConfig packageMaterial = new PackageMaterialConfig("pkg");
        PipelineConfig pipeline = new PipelineConfig();
        pipeline.setMaterialConfigs(new MaterialConfigs(packageMaterial));
        cruiseConfig.addPipeline("first", pipeline);

        assertThat(cruiseConfig.getPackageRepositories().size(), is(1));
        assertThat(cruiseConfig.getPackageRepositories().find(repoId), is(packageRepository));
        DeletePackageRepositoryCommand command = new DeletePackageRepositoryCommand(goConfigService, packageRepository, currentUser, result);
        command.update(cruiseConfig);
        assertFalse(command.isValid(cruiseConfig));
    }

    @Test
    public void shouldNotContinueIfTheUserIsNotAdmin() throws Exception {
        HttpLocalizedOperationResult expectedResult = new HttpLocalizedOperationResult();
        expectedResult.forbidden(EntityType.PackageRepository.forbiddenToDelete(packageRepository.getId(), currentUser.getUsername()), forbidden());
        when(goConfigService.isUserAdmin(currentUser)).thenReturn(false);
        DeletePackageRepositoryCommand command = new DeletePackageRepositoryCommand(goConfigService, packageRepository, currentUser, result);

        assertFalse(command.canContinue(cruiseConfig));
        assertThat(result, is(expectedResult));
    }

    @Test
    public void shouldContinueWithConfigSaveIfUserIsAdmin() {
        when(goConfigService.isUserAdmin(currentUser)).thenReturn(true);
        when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false);

        DeletePackageRepositoryCommand command = new DeletePackageRepositoryCommand(goConfigService, packageRepository, currentUser, result);

        assertThat(command.canContinue(cruiseConfig), is(true));
    }

    @Test
    public void shouldContinueWithConfigSaveIfUserIsGroupAdmin() {
        when(goConfigService.isUserAdmin(currentUser)).thenReturn(false);
        when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(true);

        DeletePackageRepositoryCommand command = new DeletePackageRepositoryCommand(goConfigService, packageRepository, currentUser, result);

        assertThat(command.canContinue(cruiseConfig), is(true));
    }
}


text:
{{note.content}} [EDIT]

<form ng-show="createNote" ng-submit="addNote()">

	<textarea rows="10" placeholder="Create a new note..." ng-model="note.content"></textarea>
	<input type="submit" value="Create" />
</form>


text:
package org.apache.cassandra.cql3;

import java.util.Random;

import org.junit.Test;

import org.apache.cassandra.Util;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.util.FileDataInput;
import org.apache.cassandra.utils.ByteBufferUtil;

public class TombstonesWithIndexedSSTableTest extends CQLTester
{
    @Test
    public void testTombstoneBoundariesInIndexCached() throws Throwable
    {
        testTombstoneBoundariesInIndex("ALL");
    }

    @Test
    public void testTombstoneBoundariesInIndexNotCached() throws Throwable
    {
        testTombstoneBoundariesInIndex("NONE");
    }

    public void testTombstoneBoundariesInIndex(String cacheKeys) throws Throwable
    {
        // That test reproduces the bug from CASSANDRA-11158 where a range tombstone boundary in the column index would
        // cause an assertion failure.

        int ROWS = 1000;
        int VALUE_LENGTH = 100;

        createTable("CREATE TABLE %s (k int, t int, s text static, v text, PRIMARY KEY (k, t)) WITH caching = { 'keys' : '" + cacheKeys + "' }");

        // We create a partition that is big enough that the underlying sstable will be indexed
        // For that, we use a large-ish number of row, and a value that isn't too small.
        String text = makeRandomString(VALUE_LENGTH);
        for (int i = 0; i < ROWS; i++)
            execute("INSERT INTO %s(k, t, v) VALUES (?, ?, ?)", 0, i, text + i);

        DecoratedKey dk = Util.dk(ByteBufferUtil.bytes(0));
        int minDeleted = ROWS;
        int maxDeleted = 0;

        // Place some range deletions around an indexed location to get a tombstone boundary as the index's firstName.
        // Because we insert a tombstone before it, the index position may move, so repeat procedure until the index
        // boundary hits a tombstone boundary.
        deletionLoop:
        while (true)
        {
            flush();
            compact();

            int indexedRow = -1;
            for (SSTableReader sstable : getCurrentColumnFamilyStore().getLiveSSTables())
            {
                // The line below failed with key caching off (CASSANDRA-11158)
                @SuppressWarnings("unchecked")
                RowIndexEntry indexEntry = sstable.getPosition(dk, SSTableReader.Operator.EQ);
                if (indexEntry != null && indexEntry.isIndexed())
                {
                    try (FileDataInput reader = sstable.openIndexReader())
                    {
                        RowIndexEntry.IndexInfoRetriever infoRetriever = indexEntry.openWithIndex(sstable.getIndexFile());
                        ClusteringPrefix firstName = infoRetriever.columnsIndex(1).firstName;
                        if (firstName.kind().isBoundary())
                            break deletionLoop;
                        indexedRow = Int32Type.instance.compose(firstName.get(0));
                    }
                }
            }
            assert indexedRow >= 0;
            minDeleted = Math.min(minDeleted, indexedRow - 2);
            maxDeleted = Math.max(maxDeleted, indexedRow + 5);

            execute("DELETE FROM %s WHERE k = 0 AND t >= ? AND t < ?", indexedRow - 2, indexedRow + 3);
            execute("DELETE FROM %s WHERE k = 0 AND t >= ? AND t < ?", indexedRow, indexedRow + 5);
        }

        flush();
        // The line below failed with key caching on (CASSANDRA-11158)
        compact();

        assertRowCount(execute("SELECT s FROM %s WHERE k = ?", 0), ROWS - (maxDeleted - minDeleted));
        assertRowCount(execute("SELECT s FROM %s WHERE k = ? ORDER BY t DESC", 0), ROWS - (maxDeleted - minDeleted));

        assertRowCount(execute("SELECT DISTINCT s FROM %s WHERE k = ?", 0), 1);
        assertRowCount(execute("SELECT DISTINCT s FROM %s WHERE k = ? ORDER BY t DESC", 0), 1);
    }

    public static String makeRandomString(int length)
    {
        Random random = new Random();
        char[] chars = new char[length];
        for (int i = 0; i < length; ++i)
            chars[i++] = (char) ('a' + random.nextInt('z' - 'a' + 1));
        return new String(chars);
    }
}


text:
namespace {

class MaybeTestDisabler : public testing::EmptyTestEventListener {
 public:
  virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
    ASSERT_FALSE(TestSuite::IsMarkedMaybe(test_info))
        << "Probably the OS #ifdefs don't include all of the necessary "
           "platforms.\nPlease ensure that no tests have the MAYBE_ prefix "
           "after the code is preprocessed.";
  }
};

class TestClientInitializer : public testing::EmptyTestEventListener {
 public:
  TestClientInitializer()
      : old_command_line_(CommandLine::NO_PROGRAM) {
  }

  virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
    old_command_line_ = *CommandLine::ForCurrentProcess();
  }

  virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE {
    *CommandLine::ForCurrentProcess() = old_command_line_;
  }

 private:
  CommandLine old_command_line_;

  DISALLOW_COPY_AND_ASSIGN(TestClientInitializer);
};

}  // namespace

TestSuite::TestSuite(int argc, char** argv) : initialized_command_line_(false) {
  PreInitialize(argc, argv, true);
}

TestSuite::TestSuite(int argc, char** argv, bool create_at_exit_manager)
    : initialized_command_line_(false) {
  PreInitialize(argc, argv, create_at_exit_manager);
}

TestSuite::~TestSuite() {
  if (initialized_command_line_)
    CommandLine::Reset();
}

void TestSuite::PreInitialize(int argc, char** argv,
                              bool create_at_exit_manager) {
#if defined(OS_WIN)
  testing::GTEST_FLAG(catch_exceptions) = false;
#endif
  base::EnableTerminationOnHeapCorruption();
  initialized_command_line_ = CommandLine::Init(argc, argv);
  testing::InitGoogleTest(&argc, argv);
#if defined(OS_LINUX) && defined(USE_AURA)
  // When calling native char conversion functions (e.g wrctomb) we need to
  // have the locale set. In the absence of such a call the "C" locale is the
  // default. In the gtk code (below) gtk_init() implicitly sets a locale.
  setlocale(LC_ALL, "");
#elif defined(TOOLKIT_GTK)
  gtk_init_check(&argc, &argv);
#endif  // defined(TOOLKIT_GTK)

  // On Android, AtExitManager is created in
  // testing/android/native_test_wrapper.cc before main() is called.
#if !defined(OS_ANDROID)
  if (create_at_exit_manager)
    at_exit_manager_.reset(new base::AtExitManager);
#endif

#if defined(OS_IOS)
  InitIOSRunHook(this, argc, argv);
#endif

  // Don't add additional code to this function.  Instead add it to
  // Initialize().  See bug 6436.
}

// static
bool TestSuite::IsMarkedMaybe(const testing::TestInfo& test) {
  return strncmp(test.name(), "MAYBE_", 6) == 0;
}

void TestSuite::CatchMaybeTests() {
  testing::TestEventListeners& listeners =
      testing::UnitTest::GetInstance()->listeners();
  listeners.Append(new MaybeTestDisabler);
}

void TestSuite::ResetCommandLine() {
  testing::TestEventListeners& listeners =
      testing::UnitTest::GetInstance()->listeners();
  listeners.Append(new TestClientInitializer);
}

// Don't add additional code to this method.  Instead add it to
// Initialize().  See bug 6436.
int TestSuite::Run() {
#if defined(OS_IOS)
  RunTestsFromIOSApp();
#endif

#if defined(OS_MACOSX)
  base::mac::ScopedNSAutoreleasePool scoped_pool;
#endif

  Initialize();
  std::string client_func =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kTestChildProcess);

  // Check to see if we are being run as a client process.
  if (!client_func.empty())
    return multi_process_function_list::InvokeChildProcessTest(client_func);
#if defined(OS_IOS)
  base::test_listener_ios::RegisterTestEndListener();
#endif
  int result = RUN_ALL_TESTS();

#if defined(OS_MACOSX)
  // This MUST happen before Shutdown() since Shutdown() tears down
  // objects (such as NotificationService::current()) that Cocoa
  // objects use to remove themselves as observers.
  scoped_pool.Recycle();
#endif

  Shutdown();

  return result;
}

// static
void TestSuite::UnitTestAssertHandler(const std::string& str) {
  RAW_LOG(FATAL, str.c_str());
}

void TestSuite::SuppressErrorDialogs() {
#if defined(OS_WIN)
  UINT new_flags = SEM_FAILCRITICALERRORS |
                   SEM_NOGPFAULTERRORBOX |
                   SEM_NOOPENFILEERRORBOX;

  // Preserve existing error mode, as discussed at
  // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
  UINT existing_flags = SetErrorMode(new_flags);
  SetErrorMode(existing_flags | new_flags);

#if defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
  // Suppress the "Debug Assertion Failed" dialog.
  // TODO(hbono): remove this code when gtest has it.
  // http://groups.google.com/d/topic/googletestframework/OjuwNlXy5ac/discussion
  _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif  // defined(_DEBUG) && defined(_HAS_EXCEPTIONS) && (_HAS_EXCEPTIONS == 1)
#endif  // defined(OS_WIN)
}

void TestSuite::Initialize() {
#if defined(OS_MACOSX) && !defined(OS_IOS)
  // Some of the app unit tests spin runloops.
  mock_cr_app::RegisterMockCrApp();
#endif

#if defined(OS_IOS)
  InitIOSTestMessageLoop();
#endif  // OS_IOS

#if defined(OS_ANDROID)
  InitAndroidTest();
#else
  // Initialize logging.
  base::FilePath exe;
  PathService::Get(base::FILE_EXE, &exe);
  base::FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL("log"));
  logging::LoggingSettings settings;
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = log_filename.value().c_str();
  settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  logging::InitLogging(settings);
  // We want process and thread IDs because we may have multiple processes.
  // Note: temporarily enabled timestamps in an effort to catch bug 6361.
  logging::SetLogItems(true, true, true, true);
#endif  // else defined(OS_ANDROID)

  CHECK(base::debug::EnableInProcessStackDumping());
#if defined(OS_WIN)
  // Make sure we run with high resolution timer to minimize differences
  // between production code and test code.
  base::Time::EnableHighResolutionTimer(true);
#endif  // defined(OS_WIN)

  // In some cases, we do not want to see standard error dialogs.
  if (!base::debug::BeingDebugged() &&
      !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
    SuppressErrorDialogs();
    base::debug::SetSuppressDebugUI(true);
    logging::SetLogAssertHandler(UnitTestAssertHandler);
  }

  icu_util::Initialize();

  CatchMaybeTests();
  ResetCommandLine();

  TestTimeouts::Initialize();
}

void TestSuite::Shutdown() {
}


text:
<resources>
    <string name="app_name">GGProgressBar</string>
</resources>


text:
<?php

namespace Shoko\TwitchApiBundle\Tests\Factory;

use Shoko\TwitchApiBundle\Factory\UserFactory;
use Shoko\TwitchApiBundle\Model\Entity\User;

/**
 * UserFactoryTest class.
 */
class UserFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test create user method.
     */
    public function testCreateUser()
    {
        $data = [
          'type' => 'user',
          'name' => 'test_user1',
          'created_at' => '2011-06-03T17:49:19Z',
          'updated_at' => '2012-06-18T17:19:57Z',
          '_links' => [
            'self' => 'https://api.twitch.tv/kraken/users/test_user1',
            'another_key' => 'another_value',
          ],
          'logo' => 'http://static-cdn.jtvnw.net/jtv_user_pictures/test_user1-profile_image-62e8318af864d6d7-300x300.jpeg',
          '_id' => 21229404,
          'display_name' => 'test_user1',
          'bio' => 'test bio woo I\'m a test user',
        ];

        $userFactory = new UserFactory();
        $user = $userFactory->createEntity($data);

        $this->assertInstanceOf('Shoko\TwitchApiBundle\Model\Entity\User', $user);
        $this->assertEquals('user', $user->getType());
        $this->assertEquals('test_user1', $user->getName());
        $this->assertEquals(new \DateTime('2011-06-03T17:49:19Z'), $user->getCreatedAt());
        $this->assertEquals(new \DateTime('2012-06-18T17:19:57Z'), $user->getUpdatedAt());
        $this->assertArrayHasKey('self', $user->getLinks());
        $this->assertEquals('https://api.twitch.tv/kraken/users/test_user1', $user->getLinks()['self']);
        $this->assertArrayHasKey('another_key', $user->getLinks());
        $this->assertEquals('another_value', $user->getLinks()['another_key']);
        $this->assertEquals('http://static-cdn.jtvnw.net/jtv_user_pictures/test_user1-profile_image-62e8318af864d6d7-300x300.jpeg', $user->getLogo());
        $this->assertEquals(21229404, $user->getId());
        $this->assertEquals('test_user1', $user->getDisplayName());
        $this->assertEquals('test bio woo I\'m a test user', $user->getBio());
    }
}


text:
class KUploadFile : public QObject
{
    Q_OBJECT
public:
    explicit KUploadFile(QObject *parent = 0);

    ~KUploadFile();
    void uploadFile(QString uploadFilename);
    static KUploadFile * getInstance();
signals:

public slots:

private:
    QNetworkAccessManager *_uploadManager;
    QNetworkReply *_reply;
    char *m_buf;
    QString filename;
    static KUploadFile *d;

private slots:

    void replyFinished(QNetworkReply *reply);

    void upLoadError(QNetworkReply::NetworkError errorCode);

    void OnUploadProgress(qint64 bytesSent, qint64 bytesTotal);
};

#endif // KUPLOADFILE_H


text:
module PufferPages
  module Rspec
    module Matchers

    end
  end
end

require 'puffer_pages/rspec/matchers/render_page'

RSpec::Rails::ControllerExampleGroup.class_eval do
  def puffer_pages_render
    @puffer_pages_render
  end

  def self.included_with_puffer_pages base
    base.class_eval do
      around(:each) do |example|
        @puffer_pages_render = {}
        ActiveSupport::Notifications.subscribe('render_page.puffer_pages') do |name, start, finish, id, payload|
          @puffer_pages_render[payload[:subject]] ||= []
          @puffer_pages_render[payload[:subject]].push payload
        end
        example.run
        ActiveSupport::Notifications.unsubscribe('render_page.puffer_pages')
      end
    end
    included_without_puffer_pages base
  end

  singleton_class.alias_method_chain :included, :puffer_pages
end


text: - find a way to validate the numbers one by one


text:
package com.goodgame.profiling.commons.statistics.storage;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.goodgame.profiling.commons.model.Metric;

public class TrieMetricStorage implements MetricStorage {
    private final String prefix;
    private final ConcurrentLinkedQueue<Metric> theList;

    public TrieMetricStorage() {
        this( "", new ConcurrentLinkedQueue<>() );
    }

    private TrieMetricStorage( String prefix, ConcurrentLinkedQueue<Metric> theList ) {
        this.prefix = replaceSpaces( prefix );
        this.theList = theList;
    }

    private String replaceSpaces( String stringWithSpaces ) {
        return stringWithSpaces.replaceAll( "\\s+", "-" );
    }

    @Override
    public void store( String key, double value ) {
        theList.add( new Metric( prefix + replaceSpaces( key ), System.currentTimeMillis() / 1000, value ) );
    }

    @Override
    public TrieMetricStorage getSubStorageCalled( String subStorageName ) {
        return new TrieMetricStorage( prefix + replaceSpaces( subStorageName ) + ".", theList );
    }

    @Override
    public void finishStoringTheMetrics() throws IOException {
        // Do nothing
    }

    public Collection<Metric> getAll() {
        return Collections.unmodifiableCollection( theList );
    }
}


text:
import hashlib
import json
import base64

from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings

from ..models import Agent, Statement
from ..views import register, statements

class AgentManagerTests(TestCase):
    @classmethod
    def setUpClass(cls):
        print "\n%s" % __name__

    def setUp(self):
        self.username = "tester1"
        self.email = "test1@tester.com"
        self.password = "test"
        self.auth = "Basic %s" % base64.b64encode("%s:%s" % (self.username, self.password))
        form = {"username":self.username, "email":self.email,"password":self.password,"password2":self.password}
        self.client.post(reverse(register),form, X_Experience_API_Version=settings.XAPI_VERSION)

    def test_agent_mbox_create(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "mbox":"mailto:bob@example.com"},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 200)
        st_id = json.loads(response.content)
        st = Statement.objects.get(statement_id=st_id[0])
        bob = st.actor
        self.assertEquals(bob.objectType, "Agent")
        self.assertFalse(bob.name)

    def test_agent_mbox_sha1sum_create(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "mbox_sha1sum":hashlib.sha1("mailto:bob@example.com").hexdigest()},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 200)
        st_id = json.loads(response.content)
        st = Statement.objects.get(statement_id=st_id[0])
        bob = st.actor

        self.assertEquals(bob.mbox_sha1sum, hashlib.sha1("mailto:bob@example.com").hexdigest())
        self.assertEquals(bob.objectType, "Agent")
        self.assertFalse(bob.name)
        self.assertFalse(bob.mbox)

    def test_agent_bogus_mbox_sha1sum_create(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "mbox_sha1sum":"notarealsum"},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, "mbox_sha1sum value [notarealsum] is not a valid sha1sum")

    def test_agent_openID_create(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "openid":"http://bob.openid.com"},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 200)
        st_id = json.loads(response.content)
        st = Statement.objects.get(statement_id=st_id[0])
        bob = st.actor

        self.assertEquals(bob.openid, "http://bob.openid.com")
        self.assertEquals(bob.objectType, "Agent")
        self.assertFalse(bob.name)
        self.assertFalse(bob.mbox)
        self.assertFalse(bob.mbox_sha1sum)

    def test_agent_account_create(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "account":{"homePage": "http://www.adlnet.gov", "name":"freakshow"}},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 200)
        st_id = json.loads(response.content)
        st = Statement.objects.get(statement_id=st_id[0])
        bob = st.actor

        self.assertEquals(bob.account_name, "freakshow")
        self.assertEquals(bob.account_homePage, "http://www.adlnet.gov")
        self.assertFalse(bob.name)
        self.assertFalse(bob.mbox)
        self.assertFalse(bob.mbox_sha1sum)
        self.assertFalse(bob.openid)

    def test_agent_kwargs_basic(self):
        ot = "Agent"
        name = "bob bobson"
        mbox = "mailto:bobbobson@example.com"
        kwargs = {"objectType":ot,"name":name,"mbox":mbox}
        bob, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)
        bob.save()
        self.assertEquals(bob.objectType, ot)
        self.assertEquals(bob.name, name)
        self.assertEquals(bob.mbox, mbox)

        bob2, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertFalse(created)
        self.assertEquals(bob.pk, bob2.pk)
        self.assertEquals(bob, bob2)

        kwargs['mbox'] = "mailto:bob.secret@example.com"
        bob3, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)
        bob3.save()
        self.assertNotEqual(bob.pk, bob3.pk)

    def test_agent_kwargs_basic_account(self):
        ot = "Agent"
        name = "bob bobson"
        account = json.dumps({"homePage":"http://www.adlnet.gov","name":"freakshow"})
        kwargs = {"objectType":ot,"name":name,"account":account}
        bob, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)
        self.assertEquals(bob.objectType, ot)
        self.assertEquals(bob.name, name)
        self.assertEquals(bob.account_homePage, "http://www.adlnet.gov")
        self.assertEquals(bob.account_name, "freakshow")

    def test_group_kwargs(self):
        ot = "Agent"
        name = "bob bobson"
        kwargs = {"objectType":ot,"name":name, "mbox": "mailto:bob@example.com"}
        bob, created = Agent.objects.retrieve_or_create(**kwargs)

        ot = "Agent"
        name = "john johnson"
        kwargs = {"objectType":ot,"name":name, "mbox": "mailto:john@example.com"}
        john, created = Agent.objects.retrieve_or_create(**kwargs)

        ot = "Group"
        members = [{"name":"bob bobson","mbox":"mailto:bob@example.com"},
                    {"name":"john johnson","mbox":"mailto:john@example.com"}]

        kwargs = {"objectType":ot, "member": members}
        gr, created = Agent.objects.retrieve_or_create(**kwargs)
        # Already created from above
        self.assertTrue(created)

        kwargs1 = {"objectType":ot, "member": members, "name": "my group"}
        gr1, created = Agent.objects.retrieve_or_create(**kwargs1)
        # creates another one b/c of adding a name
        self.assertTrue(created)
        self.assertEquals(gr1.name, "my group")
        agents = Agent.objects.all()
        self.assertEquals(len(agents), 4)
        self.assertEquals(len(agents.filter(objectType='Group')), 2)
        self.assertEquals(len(agents.filter(objectType='Agent')), 2)

    def test_agent_update_kwargs(self):
        ot = "Agent"
        name = "bill billson"
        kwargs = {"objectType":ot, "mbox": "mailto:bill@example.com"}
        bill, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        kwargs1 = {"objectType":ot, "mbox": "mailto:bill@example.com", "name": name}
        bill2, created = Agent.objects.retrieve_or_create(**kwargs1)

        self.assertFalse(created)
        self.assertEquals(bill2.name, name)
        self.assertEquals(bill.id, bill2.id)
        self.assertEquals(len(Agent.objects.all()), 1)

    def test_agent_update_kwargs_with_account(self):
        ot = "Agent"
        name = "bill billson"
        account = json.dumps({"homePage":"http://www.adlnet.gov","name":"freakshow"})
        kwargs = {"objectType":ot,"account":account}

        bill, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        kwargs1 = {"objectType":ot, "name": name, "account":account}
        bill2, created = Agent.objects.retrieve_or_create(**kwargs1)

        self.assertFalse(created)
        self.assertEquals(bill2.name, name)
        self.assertEquals(bill.id, bill2.id)
        self.assertEquals(len(Agent.objects.all()), 1)

    def test_group_update_kwargs_with_account(self):
        ot = "Group"
        name = "the group"
        account = json.dumps({"homePage":"http://www.adlnet.gov","name":"freakshow-group"})
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]

        kwargs = {"objectType":ot,"member":members, "account":account}

        g, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        kwargs1 = {"objectType":ot,"member":members, "name": name, "account":account}
        g1, created = Agent.objects.retrieve_or_create(**kwargs1)

        self.assertFalse(created)
        self.assertEquals(g1.name, name)
        self.assertEquals(g.id, g1.id)
        self.assertEquals(len(Agent.objects.all()), 3)
        self.assertEquals(g1.account_name, "freakshow-group")
        self.assertEquals(g.account_name, "freakshow-group")
        self.assertEquals(g1.account_homePage, "http://www.adlnet.gov")
        self.assertEquals(g.account_homePage, "http://www.adlnet.gov")

    def test_group_update_kwargs(self):
        ot = "Group"
        name = "the group"
        mbox = "mailto:the.group@example.com"
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]
        kwargs = {"objectType":ot, "mbox":mbox,"member":members}
        g, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        kwargs1 = {"objectType":ot, "name":name, "mbox":mbox,"member":members}
        g1, created = Agent.objects.retrieve_or_create(**kwargs1)
        self.assertFalse(created)

        self.assertEquals(g1.name, name)
        self.assertEquals(g.id, g1.id)
        # 2 agents 1 group
        self.assertEquals(len(Agent.objects.all()), 3)

    def test_group_update_members(self):
        ot = "Group"
        mbox = "mailto:the.group@example.com"
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]
        kwargs = {"objectType":ot, "mbox":mbox,"member":members}
        g, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"},
                    {"name":"agent3","mbox":"mailto:agent3@example.com"}]

        kwargs1 = {"objectType":ot, "mbox":mbox,"member":members}
        g1, created = Agent.objects.retrieve_or_create(**kwargs1)
        self.assertFalse(created)

        ags = Agent.objects.filter(objectType='Agent')
        mems = g1.member.all()
        self.assertEquals(len(ags), len(mems))
        self.assertTrue(set(ags) == set(mems))
        self.assertEquals(g.id, g1.id)
        # 3 agents 1 group
        self.assertEquals(len(Agent.objects.all()), 4)

    def test_group_update_members_with_account(self):
        ot = "Group"
        name = "the group"
        account = json.dumps({"homePage":"http://www.adlnet.gov","name":"freakshow-group"})
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]

        kwargs = {"objectType":ot,"member":members,"name":name ,"account":account}
        g, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)

        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"},
                    {"name":"agent3","mbox":"mailto:agent3@example.com"}]

        kwargs1 = {"objectType":ot, "account":account,"name":name,"member":members}
        g1, created = Agent.objects.retrieve_or_create(**kwargs1)
        self.assertFalse(created)

        ags = Agent.objects.filter(objectType='Agent')
        mems = g1.member.all()
        self.assertEquals(len(ags), len(mems))
        self.assertTrue(set(ags) == set(mems))
        self.assertEquals(g.id, g1.id)
        # 3 agents 1 group
        self.assertEquals(len(Agent.objects.all()), 4)
        self.assertEquals(g1.account_name, "freakshow-group")
        self.assertEquals(g.account_name, "freakshow-group")
        self.assertEquals(g1.account_homePage, "http://www.adlnet.gov")
        self.assertEquals(g.account_homePage, "http://www.adlnet.gov")
        self.assertEquals(g1.name, "the group")
        self.assertEquals(g.name, "the group")

    def test_agent_json_no_ids(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "name":"freakshow"},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'One and only one of mbox, mbox_sha1sum, openid, account may be supplied with an Agent')

    def test_agent_json_many_ids(self):
        stmt = json.dumps({"actor":{"objectType": "Agent", "mbox":"mailto:bob@example.com", "openid":"bob.bobson.openid.org"},
            "verb":{"id": "http://adlnet.gov/expapi/verbs/passed"},
            "object": {'id': 'act://blah.com'}})

        response = self.client.post(reverse(statements), stmt, content_type="application/json",
            Authorization=self.auth, X_Experience_API_Version=settings.XAPI_VERSION)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'One and only one of mbox, mbox_sha1sum, openid, account may be supplied with an Agent')

    def test_group(self):
        ot = "Group"
        name = "the group"
        mbox = "mailto:the.group@example.com"
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]
        kwargs = {"objectType":ot, "name":name, "mbox":mbox,"member":members}
        g, created = Agent.objects.retrieve_or_create(**kwargs)
        self.assertTrue(created)
        self.assertEquals(g.name, name)
        self.assertEquals(g.mbox, mbox)
        mems = g.member.values_list('name', flat=True)
        self.assertEquals(len(mems), 2)
        self.assertIn('agent1', mems)
        self.assertIn('agent2', mems)
        gr_dict = g.to_dict()
        self.assertEquals(gr_dict['objectType'],'Group')

        for member in gr_dict['member']:
            self.assertEquals(member['objectType'], 'Agent')
            if member['name'] == 'agent1':
                self.assertEquals(member['mbox'], 'mailto:agent1@example.com')
            elif member['name'] == 'agent2':
                self.assertEquals(member['mbox'], 'mailto:agent2@example.com')

    def test_group_from_agent_object(self):
        ot = "Group"
        name = "the group"
        mbox = "mailto:the.group@example.com"
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]
        kwargs = {"objectType":ot, "name":name, "mbox":mbox,"member":members}
        g = Agent.objects.retrieve_or_create(**kwargs)[0]
        self.assertEquals(g.name, name)
        self.assertEquals(g.mbox, mbox)
        mems = g.member.values_list('name', flat=True)
        self.assertEquals(len(mems), 2)
        self.assertIn('agent1', mems)
        self.assertIn('agent2', mems)

    def test_group_from_agent_string(self):
        ot = "Group"
        name = "the group"
        mbox = "mailto:the.group@example.com"
        members = [{"name":"agent1","mbox":"mailto:agent1@example.com"},
                    {"name":"agent2","mbox":"mailto:agent2@example.com"}]
        kwargs = {"objectType":ot, "name":name, "mbox":mbox,"member":members}
        g = Agent.objects.retrieve_or_create(**kwargs)[0]
        self.assertEquals(g.name, name)
        self.assertEquals(g.mbox, mbox)
        mems = g.member.values_list('name', flat=True)
        self.assertEquals(len(mems), 2)
        self.assertIn('agent1', mems)
        self.assertIn('agent2', mems)

    def test_agent_del(self):
        ag = Agent(name="the agent", account_homePage="http://adlnet.gov/agent/1",
            account_name="agent 1 account")
        ag.save()

        self.assertEquals(ag.name, "the agent")
        self.assertEquals(ag.account_name, "agent 1 account")
        self.assertEquals(ag.account_homePage, "http://adlnet.gov/agent/1")
        self.assertEquals(1, len(Agent.objects.all()))

        ag.delete()

        self.assertEquals(0, len(Agent.objects.all()))

    def test_agent_format(self):
        ot_s = "Agent"
        name_s = "superman"
        mbox_s = "mailto:superman@example.com"
        kwargs_s = {"objectType":ot_s,"name":name_s,"mbox":mbox_s}
        clark, created = Agent.objects.retrieve_or_create(**kwargs_s)
        self.assertTrue(created)
        clark.save()
        self.assertEquals(clark.objectType, ot_s)
        self.assertEquals(clark.name, name_s)
        self.assertEquals(clark.mbox, mbox_s)

        clark_exact = clark.to_dict()
        self.assertEquals(clark_exact['objectType'], ot_s)
        self.assertEquals(clark_exact['name'], name_s)
        self.assertEquals(clark_exact['mbox'], mbox_s)

        clark_ids = clark.to_dict(format='ids')
        self.assertFalse('objectType' in str(clark_ids), "object type was found in agent json")
        self.assertFalse('name' in str(clark_ids), "name was found in agent json")
        self.assertEquals(clark_ids['mbox'], mbox_s)

        ot_ww = "Agent"
        name_ww = "wonder woman"
        mbox_sha1sum_ww = hashlib.sha1("mailto:wonderwoman@example.com").hexdigest()
        kwargs_ww = {"objectType":ot_ww,"name":name_ww,"mbox_sha1sum":mbox_sha1sum_ww}
        diana, created = Agent.objects.retrieve_or_create(**kwargs_ww)
        self.assertTrue(created)
        diana.save()
        self.assertEquals(diana.objectType, ot_ww)
        self.assertEquals(diana.name, name_ww)
        self.assertEquals(diana.mbox_sha1sum, mbox_sha1sum_ww)

        diana_exact = diana.to_dict()
        self.assertEquals(diana_exact['objectType'], ot_ww)
        self.assertEquals(diana_exact['name'], name_ww)
        self.assertEquals(diana_exact['mbox_sha1sum'], mbox_sha1sum_ww)

        diana_ids = diana.to_dict(format='ids')
        self.assertFalse('objectType' in str(diana_ids), "object type was found in agent json")
        self.assertFalse('name' in str(diana_ids), "name was found in agent json")
        self.assertFalse('mbox' in diana_ids.items(), "mbox was found in agent json")
        self.assertEquals(diana_ids['mbox_sha1sum'], mbox_sha1sum_ww)

        ot_b = "Agent"
        name_b = "batman"
        openid_b = "id:batman"
        kwargs_b = {"objectType":ot_b,"name":name_b,"openid":openid_b}
        bruce, created = Agent.objects.retrieve_or_create(**kwargs_b)
        self.assertTrue(created)
        bruce.save()
        self.assertEquals(bruce.objectType, ot_b)
        self.assertEquals(bruce.name, name_b)
        self.assertEquals(bruce.openid, openid_b)

        bruce_exact = bruce.to_dict()
        self.assertEquals(bruce_exact['objectType'], ot_b)
        self.assertEquals(bruce_exact['name'], name_b)
        self.assertEquals(bruce_exact['openid'], openid_b)

        bruce_ids = bruce.to_dict(format='ids')
        self.assertFalse('objectType' in str(bruce_ids), "object type was found in agent json")
        self.assertFalse('name' in str(bruce_ids), "name was found in agent json")
        self.assertFalse('mbox' in str(bruce_ids), "mbox was found in agent json")
        self.assertFalse('mbox_sha1sum' in str(bruce_ids), "mbox_sha1sum was found in agent json")
        self.assertEquals(bruce_ids['openid'], openid_b)

        ot_f = "Agent"
        name_f = "the flash"
        account_f = {"homePage":"http://ultrasecret.justiceleague.com/accounts/", "name":"theflash"}
        kwargs_f = {"objectType":ot_f,"name":name_f,"account":account_f}
        barry, created = Agent.objects.retrieve_or_create(**kwargs_f)
        self.assertTrue(created)
        barry.save()
        self.assertEquals(barry.objectType, ot_f)
        self.assertEquals(barry.name, name_f)
        self.assertEquals(barry.account_homePage, account_f['homePage'])
        self.assertEquals(barry.account_name, account_f['name'])

        barry_exact = barry.to_dict()
        self.assertEquals(barry_exact['objectType'], ot_f)
        self.assertEquals(barry_exact['name'], name_f)
        self.assertEquals(barry_exact['account']['homePage'], account_f['homePage'])
        self.assertEquals(barry_exact['account']['name'], account_f['name'])

        barry_ids = barry.to_dict(format='ids')
        self.assertFalse('objectType' in str(barry_ids), "object type was found in agent json")
        self.assertFalse('name' in barry_ids.items(), "name was found in agent json")
        self.assertFalse('mbox' in barry_ids.items(), "mbox was found in agent json")
        self.assertFalse('mbox_sha1sum' in str(barry_ids), "mbox_sha1sum was found in agent json")
        self.assertFalse('openid' in str(barry_ids), "openid was found in agent json")
        self.assertEquals(barry_ids['account']['homePage'], account_f['homePage'])
        self.assertEquals(barry_ids['account']['name'], account_f['name'])

        ot_j = "Group"
        name_j = "Justice League"
        mbox_j = "mailto:justiceleague@example.com"
        kwargs_j = {"objectType":ot_j,"name":name_j,"mbox":mbox_j, "member":[kwargs_s,kwargs_ww,kwargs_f,kwargs_b]}
        justiceleague, created = Agent.objects.retrieve_or_create(**kwargs_j)
        self.assertTrue(created)
        justiceleague.save()
        self.assertEquals(justiceleague.objectType, ot_j)
        self.assertEquals(justiceleague.name, name_j)
        self.assertEquals(justiceleague.mbox, mbox_j)

        justiceleague_exact = justiceleague.to_dict()
        self.assertEquals(justiceleague_exact['objectType'], ot_j)
        self.assertEquals(justiceleague_exact['name'], name_j)
        self.assertEquals(justiceleague_exact['mbox'], mbox_j)

        justiceleague_ids = justiceleague.to_dict(format='ids')
        self.assertTrue('objectType' in str(justiceleague_ids), "object type was not found in group json")
        self.assertFalse('name' in str(justiceleague_ids), "name was found in agent json")
        self.assertEquals(justiceleague_ids['mbox'], mbox_j)

        badguy_ds = {"objectType":"Agent", "mbox":"mailto:darkseid@example.com", "name":"Darkseid"}
        badguy_m = {"objectType":"Agent", "mbox":"mailto:mantis@example.com", "name":"Mantis"}

        ot_bg = "Group"
        members_bg = [badguy_ds, badguy_m]
        kwargs_bg = {"objectType":ot_bg,"member":members_bg}
        badguys, created = Agent.objects.retrieve_or_create(**kwargs_bg)
        self.assertTrue(created)
        badguys.save()
        self.assertEquals(badguys.objectType, ot_bg)
        bg_members = badguys.member.all()
        self.assertEquals(len(bg_members), 2)
        for bg in bg_members:
            self.assertTrue(bg.name in str(kwargs_bg['member']))

        badguys_exact = badguys.to_dict()
        self.assertEquals(badguys_exact['objectType'], ot_bg)
        for m in badguys_exact['member']:
            if m['name'] == badguy_ds['name']:
                self.assertEquals(m['objectType'], badguy_ds['objectType'])
                self.assertEquals(m['mbox'], badguy_ds['mbox'])
            elif m['name'] == badguy_m['name']:
                self.assertEquals(m['objectType'], badguy_m['objectType'])
                self.assertEquals(m['mbox'], badguy_m['mbox'])
            else:
                self.fail("got an unexpected name: " % m['name'])

        badguys_ids = badguys.to_dict(format='ids')
        self.assertTrue('objectType' in str(badguys_ids), "object type was not found in group json")
        for m in badguys_ids['member']:
            self.assertFalse('objectType' in str(m), "object type was found in member agent")
            self.assertFalse('name' in str(m), "name was found in member agent")
            if m['mbox'] == badguy_ds['mbox']:
                self.assertEquals(m['mbox'], badguy_ds['mbox'])
            elif m['mbox'] == badguy_m['mbox']:
                self.assertEquals(m['mbox'], badguy_m['mbox'])
            else:
                self.fail("got an unexpected mbox: " % m['mbox'])


text:
package servicecatalog

import (
	"errors"
	"fmt"
	"strings"

	"github.com/hashicorp/go-multierror"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/runtime"
)

const (
	// FieldExternalPlanName is the jsonpath to a plan's external name.
	FieldExternalPlanName = "spec.externalName"

	// FieldClusterServiceClassRef is the jsonpath to a plan's associated class name.
	FieldClusterServiceClassRef = "spec.clusterServiceClassRef.name"

	// FieldServiceClassRef is the jsonpath to a plan's associated class name.
	FieldServiceClassRef = "spec.serviceClassRef.name"
)

// Plan provides a unifying layer of cluster and namespace scoped plan resources.
type Plan interface {

	// GetName returns the plan's name.
	GetName() string

	// GetShortStatus returns the plan's status.
	GetShortStatus() string

	// GetNamespace returns the plan's namespace, or "" if it's cluster-scoped.
	GetNamespace() string

	// GetExternalName returns the plan's external name.
	GetExternalName() string

	// GetDescription returns the plan description.
	GetDescription() string

	// GetFree returns if the plan is free.
	GetFree() bool

	// GetClassID returns the plan's class name.
	GetClassID() string

	// GetInstanceCreateSchema returns the instance create schema from plan.
	GetInstanceCreateSchema() *runtime.RawExtension

	// GetInstanceUpdateSchema returns the instance update schema from plan.
	GetInstanceUpdateSchema() *runtime.RawExtension

	// GetBindingCreateSchema returns the instance create schema from plan.
	GetBindingCreateSchema() *runtime.RawExtension

	// GetDefaultProvisionParameters returns the default provision parameters from plan.
	GetDefaultProvisionParameters() *runtime.RawExtension
}

// RetrievePlans lists all plans defined in the cluster.
func (sdk *SDK) RetrievePlans(classID string, opts ScopeOptions) ([]Plan, error) {
	plans, err := sdk.retrievePlansByListOptions(opts, metav1.ListOptions{})
	if err != nil {
		return nil, err
	}

	if classID == "" {
		return plans, nil
	}

	var filtered []Plan
	for _, p := range plans {
		if p.GetClassID() == classID {
			filtered = append(filtered, p)
		}
	}

	return filtered, nil
}

func (sdk *SDK) retrievePlansByListOptions(scopeOpts ScopeOptions, listOpts metav1.ListOptions) ([]Plan, error) {
	var plans []Plan

	if scopeOpts.Scope.Matches(ClusterScope) {
		csp, err := sdk.ServiceCatalog().ClusterServicePlans().List(listOpts)
		if err != nil {
			return nil, fmt.Errorf("unable to list cluster-scoped plans (%s)", err)
		}

		for _, p := range csp.Items {
			plan := p
			plans = append(plans, &plan)
		}
	}

	if scopeOpts.Scope.Matches(NamespaceScope) {
		sp, err := sdk.ServiceCatalog().ServicePlans(scopeOpts.Namespace).List(listOpts)
		if err != nil {
			// Gracefully handle when the feature-flag for namespaced broker resources isn't enabled on the server.
			if apierrors.IsNotFound(err) {
				return plans, nil
			}
			return nil, fmt.Errorf("unable to list plans in %q (%s)", scopeOpts.Namespace, err)
		}

		for _, p := range sp.Items {
			plan := p
			plans = append(plans, &plan)
		}
	}

	return plans, nil
}

// RetrievePlanByName gets a plan by its external name.
func (sdk *SDK) RetrievePlanByName(name string, opts ScopeOptions) (Plan, error) {
	if opts.Scope == AllScope {
		return nil, errors.New("invalid scope: all")
	}

	listOpts := metav1.ListOptions{
		FieldSelector: fields.OneTermEqualSelector(FieldExternalPlanName, name).String(),
	}

	return sdk.retrieveSinglePlanByListOptions(name, opts, listOpts)
}

// RetrievePlanByClassAndName gets a plan by its external name and class name combination.
func (sdk *SDK) RetrievePlanByClassAndName(className, planName string, opts ScopeOptions) (Plan, error) {
	if opts.Scope == AllScope {
		return nil, errors.New("invalid scope: all")
	}

	class, err := sdk.RetrieveClassByName(className, opts)
	if err != nil {
		return nil, err
	}

	var classRefSelector fields.Selector
	if opts.Scope.Matches(ClusterScope) {
		classRefSelector = fields.OneTermEqualSelector(FieldClusterServiceClassRef, class.GetName())
	} else {
		classRefSelector = fields.OneTermEqualSelector(FieldServiceClassRef, class.GetName())
	}

	listOpts := metav1.ListOptions{
		FieldSelector: fields.AndSelectors(
			classRefSelector,
			fields.OneTermEqualSelector(FieldExternalPlanName, planName),
		).String(),
	}

	ss := []string{class.GetName(), planName}
	return sdk.retrieveSinglePlanByListOptions(strings.Join(ss, "/"), opts, listOpts)
}

// RetrievePlanByClassIDAndName gets a plan by its external name and class kube name combination.
func (sdk *SDK) RetrievePlanByClassIDAndName(classKubeName, planName string, scopeOpts ScopeOptions) (Plan, error) {
	var classRefSelector fields.Selector
	findError := &multierror.Error{
		ErrorFormat: func(errors []error) string {
			return joinErrors("error:", errors, "\n  ")
		},
	}

	//we run through both of these to support AllScope (i.e. we don't know if its a cluster or namespaced plan)
	if scopeOpts.Scope.Matches(ClusterScope) {
		classRefSelector = fields.OneTermEqualSelector(FieldClusterServiceClassRef, classKubeName)
		listOpts := metav1.ListOptions{
			FieldSelector: fields.AndSelectors(
				classRefSelector,
				fields.OneTermEqualSelector(FieldExternalPlanName, planName),
			).String(),
		}

		ss := []string{classKubeName, planName}
		plan, err := sdk.retrieveSinglePlanByListOptions(strings.Join(ss, "/"), scopeOpts, listOpts)
		if err != nil {
			findError = multierror.Append(findError, err)
		} else if plan != nil {
			return plan, nil
		}
	}
	if scopeOpts.Scope.Matches(NamespaceScope) {
		classRefSelector = fields.OneTermEqualSelector(FieldServiceClassRef, classKubeName)
		listOpts := metav1.ListOptions{
			FieldSelector: fields.AndSelectors(
				classRefSelector,
				fields.OneTermEqualSelector(FieldExternalPlanName, planName),
			).String(),
		}

		ss := []string{classKubeName, planName}
		plan, err := sdk.retrieveSinglePlanByListOptions(strings.Join(ss, "/"), scopeOpts, listOpts)
		if err != nil {
			findError = multierror.Append(findError, err)
		} else if plan != nil {
			return plan, nil
		}
	}
	return nil, fmt.Errorf("plan '%s' not found:%s", planName, findError.Error())
}

func (sdk *SDK) retrieveSinglePlanByListOptions(name string, scopeOpts ScopeOptions, listOpts metav1.ListOptions) (Plan, error) {
	plans, err := sdk.retrievePlansByListOptions(scopeOpts, listOpts)
	if err != nil {
		return nil, err
	}
	if len(plans) == 0 {
		return nil, fmt.Errorf("plan not found '%s'", name)
	}
	if len(plans) > 1 {
		return nil, fmt.Errorf("more than one matching plan found for '%s'", name)
	}
	return plans[0], nil
}

// RetrievePlanByID gets a plan by its Kubernetes name.
func (sdk *SDK) RetrievePlanByID(kubeName string, opts ScopeOptions) (Plan, error) {
	if opts.Scope == AllScope {
		return nil, errors.New("invalid scope: all")
	}

	if opts.Scope.Matches(ClusterScope) {
		p, err := sdk.ServiceCatalog().ClusterServicePlans().Get(kubeName, metav1.GetOptions{})
		if err != nil {
			return nil, fmt.Errorf("unable to get cluster-scoped plan by Kubernetes name'%s' (%s)", kubeName, err)
		}
		return p, nil
	}

	if opts.Scope.Matches(NamespaceScope) {
		p, err := sdk.ServiceCatalog().ServicePlans(opts.Namespace).Get(kubeName, metav1.GetOptions{})
		if err != nil {
			return nil, fmt.Errorf("unable to get plan by Kubernetes name'%s' (%s)", kubeName, err)
		}
		return p, nil
	}

	return nil, fmt.Errorf("unable to get plan by Kubernetes name'%s'", kubeName)
}


text:
CInsertDocumentItemCommand::CInsertDocumentItemCommand(CDocumentItemCollection & collection, CDocumentItemPtr item, boost::optional<size_t> position)
	:m_collection(collection), m_item(item), m_position(position)
{
}

void CInsertDocumentItemCommand::DoExecute()
{
	bool result = m_collection.AddItem(m_item, m_position);
	if (!result)
	{
		throw std::out_of_range("Item does not exist. Position: " + std::to_string(m_position.get()));
	}
}

void CInsertDocumentItemCommand::DoUnexecute()
{
	size_t position = m_position ? m_position.get() : m_collection.GetSize() - 1;
	m_collection.RemoveItem(position);
}


text:
static const int ddLogLevel = LOG_LEVEL_VERBOSE;

@interface DashboardViewController () <XMPPStreamDelegate>

@property (strong, nonatomic) XMPPMUC * xmppMUC;

@property (strong, nonatomic) XMPPJID * conferenceJID;
@property (strong, nonatomic) NSString * roomsDiscoID;

@property (strong, nonatomic) NSArray * devices;
@property (strong, nonatomic) NSMutableDictionary * deviceWindowControllers;

@property (weak, nonatomic) IBOutlet NSTextField * serverAddressLabel;
@property (weak, nonatomic) IBOutlet NSTextField * jidLabel;

@end

@implementation DashboardViewController

#pragma mark - View Controller Life Cycle

- (void)viewWillAppear
{
    [super viewWillAppear];

    if (self.xmppMUC == nil) {
        NSAssert(self.xmppStream != nil, @"An XMPP stream should be ready at this point");
        [self setupStream];
        [self setupUI];
        [self discoverDevices];
    }
}

- (void)dealloc
{
    [self.xmppStream removeDelegate:self];
}

#pragma mark - XMPP Stream and MUC

- (void)setupStream
{
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];

    self.xmppMUC = [[XMPPMUC alloc] init];
    [self.xmppMUC activate:self.xmppStream];

    self.conferenceJID = [XMPPJID jidWithString:[NSString stringWithFormat:@"muc.%@", self.xmppStream.myJID.domain]];
}

- (void)setupUI
{
    NSString *hostname = self.xmppStream.hostName ?: self.xmppStream.myJID.domain;
    NSString *serverAddress = [NSString stringWithFormat:@"%@:%@", hostname, @(self.xmppStream.hostPort)];

    self.serverAddressLabel.stringValue = serverAddress;
    self.jidLabel.stringValue = self.xmppStream.myJID.full;

    self.deviceWindowControllers = [NSMutableDictionary new];
}

- (void)discoverDevices
{
    self.devices = [NSArray array];

    self.roomsDiscoID = [self.xmppStream generateUUID];
    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"];
    XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:self.conferenceJID elementID:self.roomsDiscoID child:query];
    [self.xmppStream sendElement:iq];
}

- (void)handleRoomDiscoResult:(XMPPIQ *)iq
{
    NSMutableArray *mutableDevices = [self mutableArrayValueForKey:@"devices"];

    // Parse conference disco result and connect to all available devices (MUC rooms)
    NSXMLElement *queryElement = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"];
    NSArray *items = [queryElement elementsForName:@"item"];
    for (NSXMLElement *item in items) {
        XMPPJID *roomJID = [XMPPJID jidWithString:[item attributeStringValueForName:@"jid"]];
        EV3Device *device = [EV3Device deviceWithRoomJID:roomJID stream:self.xmppStream];
        [mutableDevices addObject:device];
    }
}

#pragma mark - UI Methods

- (IBAction)signOutButtonPressed:(id)sender
{
    [self.xmppStream disconnect];
    [self.delegate dashboardViewControllerDidDisconnect:self];
}

- (void)showDetailsWindowForDevice:(EV3Device *)device
{
    NSWindowController *windowController = self.deviceWindowControllers[device.roomJID];
    if (windowController == nil) {
        windowController = [DeviceViewController instantiateInWindowControllerWithDevice:device];
        self.deviceWindowControllers[device.roomJID] = windowController;
    }
    [windowController showWindow:self];
}

- (void)dismissDetailsWindowForDevice:(EV3Device *)device
{
    NSWindowController *windowController = self.deviceWindowControllers[device.roomJID];
    [self.deviceWindowControllers removeObjectForKey:device.roomJID];
    [windowController close];
}

#pragma mark - XMPPStream Delegate

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    [self.delegate dashboardViewControllerDidDisconnect:self];
}

//- (void)xmppStream:(XMPPStream *)sender didSendIQ:(XMPPIQ *)iq
//{
//    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
//}
//
//- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
//{
//    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
//}

- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    if ([iq.elementID isEqualToString:self.roomsDiscoID]) {
        [self handleRoomDiscoResult:iq];
        return YES;
    }

    return NO;
}

//- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
//{
//    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
//}

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 13.08.15
 * Time: 16:29
 */

namespace app\modules\user\controllers;

use app\models\Base;
use app\models\SelectionsSearch;
use app\modules\user\models\MetrikaForm;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use Yii;

class MetrikaController extends UserMainController{

    public function behaviors()
    {
        return  [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index','create'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /*
     * информация о выборках из БД - Моаб-Метрика
     */
    public function actionIndex()
    {
        //проверка доступа к выборкам для тек. юзера
        $this->access();

        return $this->render('index');
    }

    /*
     * проверка доступа пользователя к БД
     */
    protected function access()
    {
        if(!\app\modules\user\models\User::isSubscribeMoab()){
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<?php

namespace Ublaboo\DataGrid\Tests\Files;

use Nette\Http,
	Nette;

class XTestingDataGridFactory
{

	public function createXTestingDataGrid($presenterName = 'XTesting')
	{
		$presenterFactory = new Nette\Application\PresenterFactory;
		$presenterFactory->setMapping(['*' => 'Ublaboo\DataGrid\Tests\Files\*Presenter']);

		$presenter = $presenterFactory->createPresenter($presenterName);

		$url = new Http\UrlScript('localhost');
		$request = new Http\Request($url);
		$response = new Http\Response;
		$session = new Http\Session($request, $response);

		$presenter->injectPrimary(NULL, NULL, NULL, $request, $response, $session);

		return $presenter->getComponent('grid');
	}

}


text:
# frozen_string_literal: true

require "cases/helper"
require "models/post"

class SQLite3AnnotateTest < ActiveRecord::SQLite3TestCase
  fixtures :posts

  def test_annotate_wraps_content_in_an_inline_comment
    assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do
      posts = Post.select(:id).annotate("foo")
      assert posts.first
    end
  end

  def test_annotate_is_sanitized
    assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do
      posts = Post.select(:id).annotate("*/foo/*")
      assert posts.first
    end

    assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do
      posts = Post.select(:id).annotate("**//foo//**")
      assert posts.first
    end

    assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/ /\* bar \*/}) do
      posts = Post.select(:id).annotate("*/foo/*").annotate("*/bar")
      assert posts.first
    end

    assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* \+ MAX_EXECUTION_TIME\(1\) \*/}) do
      posts = Post.select(:id).annotate("+ MAX_EXECUTION_TIME(1)")
      assert posts.first
    end
  end
end


text:
class Base {
  public:
    virtual void method1(const char*) {}
};

class Delegate {
  public:
    virtual void didStarted() = 0;
};

class Derived: public Base,
               public Delegate {
  public:
    virtual void method1(const char*) {}
    virtual void didStarted() {}
};

class MoreDerived: public Derived {
  public:
    virtual void method1(const char*) {}
};

void caller(const char *msg)
{
    MoreDerived *m = new MoreDerived;
    m->method1(msg);
}

int main(int, char *[])
{
    Base *b = new Derived;
    b->method1("hello");

    return 0;
}


text:
// <copyright file="Program.cs">
// Copyright (c) 2014 All Right Reserved
//
// This source is subject to the License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Christian Stewart</author>
// <email>kidovate@gmail.com</email>
// <date>2014-05-10</date>
// <summary>Entry point for the d2moddin plugin.</summary>
using System;
using System.IO;
using System.Windows.Forms;
using log4net.Config;

namespace d2mp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            XmlConfigurator.Configure();
            D2MP.main();
        }
    }
}