text:
<?php

namespace Ft\CoreBundle\CoreTest;

use Ft\CoreBundle\CoreTest\Helper;
use Ft\HomeBundle\FtRequest\FtHelper;

class HTML
{

	public $poorly_designed_recursive_search_output = array('');

	public function DuplicateId() {
		global $poorly_designed_catchall;
		global $poorly_designed_catchall_element_array;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$poorly_designed_catchall = array();
		$poorly_designed_catchall_element_array = array();

		global $ft_dom;
		$elements = $ft_dom->getElementsByTagName('html');

		foreach($elements as $element) {
			Helper::recursivelyGetDuplicateAttributeValue($element,'id');
		}

		if(!empty($poorly_designed_catchall_element_array)) {
			foreach($poorly_designed_catchall_element_array as $element) {
				$code[0] .= ' - ' . $element . "\n";
				$code[1]++;
			}
			if(count($poorly_designed_catchall_element_array) > 1) { $code[2] = 's'; } else { $code[1] = ''; }
			return $code;
		}

		return false;
	}

	public function HasNestedTables()
	{
		global $ft_dom;
		$elements = $ft_dom->getElementsByTagName('table');
        foreach ($elements as $element) {
			$nested_tables = $element->getElementsByTagName('table');
	        foreach ($nested_tables as $nested) {
				return true;
	        }
		}
		return false;
	}

	public function HasDeeplyNestedTables()
	{
		global $ft_dom;
		$elements = $ft_dom->getElementsByTagName('table');
        foreach ($elements as $element) {
			$nested_tables = $element->getElementsByTagName('table');
	        foreach ($nested_tables as $nested) {
				$deeply_nested_tables = $nested->getElementsByTagName('table');
		        foreach ($deeply_nested_tables as $deeply_nested) {
					return true;
		        }
	        }
		}
		return false;
	}

	//we just check to see if they have a favicon set in the HTML. If the file is missing, it will show up in brokenlink.
	public function FaviconMissing()
	{
		global $ft_dom;
	    global $ft_web_root;

		//$pattern = '/.*<link.*href=.*favicon\.ico.*>/';
		//preg_match($pattern,$ft_data,$match);

		//if(!isset($match[0])) { return true; }

		//unfortunately is does not need to be called favicon. re-do test.
		$head = $ft_dom->getElementsByTagName('head');
		$elements = $head->item(0)->getElementsByTagName('link');

		if(Helper::http200Test($ft_web_root . 'favicon.ico')) { return false; }

		$found_favicon = false;
        foreach ($elements as $element) {
			//rel must be "icon" or "shortcut icon".
			if($element->hasAttribute('rel') && ($element->getAttribute('rel') == 'icon' || $element->getAttribute('rel') == 'shortcut icon')) {
				$found_favicon = true;
			}
		}

		if($found_favicon) {
			return false;
		}
		return true;
	}

	//this new function does not loop,
	//but the retired version had issues.
    public function ScriptBeforeCss()
    {
		global $ft_dom;
		global $ft_run_log;

		$elements = $ft_dom->getElementsByTagName('head');

		$code = array('');
		$print_once = false;
		$code[1] = 0; //number of scripts before css.
		$plural_str = 's';
		$conjugate_str = '';

    	if ( $elements->item(0)->hasChildNodes() ) {
		    $children = $elements->item(0)->childNodes;
		    foreach( $children as $kid ) {
		    	if ( $kid->nodeType == XML_ELEMENT_NODE ) {
			        if($kid->tagName == 'script' && $kid->hasAttribute('src')) {
						$code[1]++;
					} elseif ($kid->tagName == 'link') {
						if($kid->hasAttribute('href') && (strpos(strtolower($kid->getAttribute('href')),'.css') !== false)) {
							if($code[1] > 0) {
								if($code[1] == 1) {$plural_str = ''; $conjugate_str = 's';}
								//$code[0] .= Helper::printCodeWithLineNumber($prev_script);
								$code[0] .= $code[1] . " script" . $plural_str . " appear" .$conjugate_str. " before\n\n";
								$code[0] .= Helper::printCodeWithLineNumber($kid);
								$ft_run_log .= ',"Number scripts before stylesheets":'. $code[1];
								$code[1] = $plural_str;
								return $code;
							}
						}
					}

			    }
		    }
	    }

		return false;
    }

    public function ScriptBeforeCssRetired()
    {
		global $ft_dom;
		global $ft_run_log;

		$elements = $ft_dom->getElementsByTagName('head');

		$code = array('');
		$prev_script = null;
		$print_once = false;
		$code[1] = 0; //number of css after scripts.
		$code[2] = 0; //number of scripts before css.

    	if ( $elements->item(0)->hasChildNodes() ) {
		    $children = $elements->item(0)->childNodes;
		    foreach( $children as $kid ) {
		    	if ( $kid->nodeType == XML_ELEMENT_NODE ) {
			        if($kid->tagName == 'script' && $kid->hasAttribute('src')) {
						$prev_script = $kid;
						$print_once = false;
						$code[2]++;
					} elseif ($kid->tagName == 'link') {
						if($kid->hasAttribute('href') && (strpos(strtolower($kid->getAttribute('href')),'.css') !== false)) {
							if(isset($prev_script)) {
								if(!$print_once) {
									$code[1]++;
									$code[0] .= Helper::printCodeWithLineNumber($prev_script);
									$code[0] .= "\nappears before\n\n";
									$code[0] .= Helper::printCodeWithLineNumber($kid);
								} else {
									$code[1]++;
									$code[0] .= "\nand\n\n";
									$code[0] .= Helper::printCodeWithLineNumber($kid);
								}
								$print_once = true;
							}
						}
					}
					if($print_once) { $code[0] .= "\n"; }

			    }
		    }
	    }

		$ft_run_log .= ',"Number stylesheets after scripts":'. $code[1] . ',"Number scripts before stylesheets":'. $code[2];

		if($code[1] > 1) { $code[1] = 's'; } else { $code[1] = ''; }
		if($code[2] > 1) { $code[2] = 's'; } else { $code[2] = ''; }

		//if code is too long, empty and return.
 		if($code[0] != '') {
			if(strlen($code[0]) > 300) { $code[0] = ''; }
			return $code;
		}

		return false;
    }

    public function ManyInlineStylesFlag()
    {
		global $poorly_designed_catchall;
		$poorly_designed_catchall = 0;
		global $ft_dom;
		$too_many_threshold = 20;
		$result_array = array();

		$elements = $ft_dom->getElementsByTagName('html');

		foreach($elements as $element) {
			Helper::recursivelySearchAttribute($element,'style');
		}

		if($poorly_designed_catchall > $too_many_threshold) {
			$result_array[0] = $poorly_designed_catchall;
			$result_array[1] = $too_many_threshold;
			return $result_array;
		}

		return false;
    }

    public function TitleElementMissing()
    {
		global $ft_dom;
		$elements = $ft_dom->getElementsByTagName('title');
        foreach ($elements as $element) {
	        return false;
		}
		return true;
    }

    public function NoDoctype()
    {
        return false;
    }

    public function DoctypeNotFirstElement()
    {
		if(!Helper::DoctypeFirstElementCheck()) {
			return true;
		}
        return false;
    }

    public function BrokenLinkDiagnostics()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$passed_elem_array = array();
		$url_array = array();

		$elements = $ft_dom->getElementsByTagName('link');
        foreach ($elements as $element) {
			if($element->hasAttribute('href')) {
				if(!in_array($element->getAttribute('href'),$url_array))
				{
					$url = Helper::getAbsoluteResourceLink($element->getAttribute('href'));
					$link_time_start = Helper::microtime_float();

					$headers = get_headers($url, 1);
					$header_str = explode(' ',$headers[0]);
					if($header_str[1] == '404') {
						$code[1]++;
						$code[0] .=  Helper::printCodeWithLineNumber($element);
					}

					$link_time_end = Helper::microtime_float();
					$link_time = $link_time_end - $link_time_start;

					$url_array[] = round($link_time,4) . ' :: ' . $element->getAttribute('href') ;
				}
		 	}
		 }

		$elements = $ft_dom->getElementsByTagName('a');
		//if there are > 100 links, let's not do this check for now, or make a trigger to run it manually.
		if($elements->length > 100) { return false; }
        foreach ($elements as $element) {
			if($element->hasAttribute('href')) {
				if(!in_array($element->getAttribute('href'),$url_array))
				{
					$url = Helper::getAbsoluteResourceLink($element->getAttribute('href'));
					$link_time_start = Helper::microtime_float();

					//error_log($url);

					$headers = get_headers($url, 1);
					$header_str = explode(' ',$headers[0]);
					if($header_str[1] == '404') {
						$code[1]++;
						$code[0] .=  Helper::printCodeWithLineNumber($element);
					}

					$link_time_end = Helper::microtime_float();
					$link_time = $link_time_end - $link_time_start;

					$url_array[] = round($link_time,4) . ' :: ' . $element->getAttribute('href') ;
				}
		 	}
		 }

		//var_dump($url_array);
		return false;

	}

    public function BrokenResource()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$code[3] = '';
		$code[4] = 'image';
		$passed_elem_array = array();
		$url_array = array();
		$max_resource_tests = 25;

		//the kinds of tags that a resource can be in are script, a, img, link, object, "input type=image src" iframe.
		//specifically:
		// src: img, input, script, frame, iframe
		// href: a, link, area, base

		//$srcs = array('img','input', 'script', 'frame', 'iframe');
		//$hrefs = array('a','link', 'area', 'base');

		//limited tests:
		$srcs = array('input', 'script', 'frame', 'iframe');
		$hrefs = array('link', 'area', 'base');

        foreach ($srcs as $src) {
			$elements = $ft_dom->getElementsByTagName($src);
	        foreach ($elements as $element) {
				//don't try to do too many.
				if(count($url_array) > $max_resource_tests) {
					$code[3] = "\n_PLEASE NOTE: By default, FrontendTest does not check more than $max_resource_tests non-image, non-link resources. If you would like all of the page's resources tested, please contact [support@frontendtest.com](mailto:support@frontendtest.com?subject=maxResourceTestLimitHit)._";
					continue;
				}

				if($element->hasAttribute('src')) {
					$trimmed_url = 	trim($element->getAttribute('src'));
					if(!in_array($trimmed_url,$url_array))
					{
						$url = Helper::getAbsoluteResourceLink($trimmed_url);
						if(Helper::httpBadStatusCode($url)) {
							$code[1]++;
							$code[0] .=  Helper::printCodeWithLineNumber($element);
							if(Helper::likelyPixel($element)) { $code[4] = 'pixel'; }
						}
						$url_array[] = $trimmed_url;
					}
			 	}
			 }
		}

        foreach ($hrefs as $href) {
			$elements = $ft_dom->getElementsByTagName($href);
	        foreach ($elements as $element) {
				//don't try to do too many.
				if(count($url_array) > $max_resource_tests) {
					$code[3] = "\n_PLEASE NOTE: By default, FrontendTest does not check more than $max_resource_tests non-image, non-link resources. If you would like all of the page's resources tested, please contact [support@frontendtest.com](mailto:support@frontendtest.com?subject=maxResourceTestLimitHit)._";
					continue;
				}

				if($element->hasAttribute('href')) {
					if(strpos($element->getAttribute('href'),'javascript:') !== false || strpos($element->getAttribute('href'),'mailto:') !== false){
						continue;
					}
					if(!in_array($element->getAttribute('href'),$url_array))
					{
						$url = Helper::getAbsoluteResourceLink($element->getAttribute('href'));
						if(Helper::httpBadStatusCode($url)) {
							$code[1]++;
							$code[0] .=  Helper::printCodeWithLineNumber($element);
						}
						$url_array[] = $element->getAttribute('href');
					}
			 	}
			 }
		}

		if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			return $code;
		}

		return false;
	}

    public function BrokenLink()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$code[3] = '';
		$passed_elem_array = array();
		$url_array = array();
		$max_resource_tests = 30;

		$elements = $ft_dom->getElementsByTagName('a');
		//only make this test if there is a reasonable number of links.
        foreach ($elements as $element) {
			//don't try to do too many.
			if(count($url_array) > $max_resource_tests) {
				$code[3] = "\n_PLEASE NOTE: By default, FrontendTest does not check more than $max_resource_tests links. If you would like all of the page's links tested, please contact [support@frontendtest.com](mailto:support@frontendtest.com?subject=maxResourceTestLimitHit)._";
				continue;
			}
			if($element->hasAttribute('href')) {
				if(strpos($element->getAttribute('href'),'javascript:') !== false || strpos($element->getAttribute('href'),'mailto:') !== false){
					//error_log('returning from mailto or js:');
					continue;
				}
				if(!in_array($element->getAttribute('href'),$url_array))
				{
					$url = Helper::getAbsoluteResourceLink($element->getAttribute('href'));
					if(Helper::httpBadStatusCode($url)) {
						$code[1]++;
						$code[0] .=  Helper::printCodeWithLineNumber($element);
					}
					$url_array[] = $element->getAttribute('href');
				}
		 	}
		 }

		 if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			return $code;
		 }

        return false;
    }

    public function BrokenImage()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$code[3] = '';
		$passed_elem_array = array();
		$elements = $ft_dom->getElementsByTagName('img');
		$url_array = array();
		$max_resource_tests = 30;

        foreach ($elements as $element) {
			//don't try to do too many.
			if(count($url_array) > $max_resource_tests) {
				$code[3] = "\n_PLEASE NOTE: By default, FrontendTest does not check more than $max_resource_tests images. If you would like all of the page's images tested, please contact [support@frontendtest.com](mailto:support@frontendtest.com?subject=maxResourceTestLimitHit)._";
				continue;
			}
			if($element->hasAttribute('src')) {
				if(!in_array($element->getAttribute('src'),$url_array))
				{
					$url = Helper::getAbsoluteResourceLink($element->getAttribute('src'));
					if(Helper::httpBadStatusCode($url)) {
						$code[1]++;
						$code[0] .=  Helper::printCodeWithLineNumber($element);
					}
					$url_array[] = $element->getAttribute('src');
				}
		 	}
		 }

		 if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			return $code;
		 }

        return false;
    }
    public function GifsUsed()
    {
		//to fix: if gifs are broken, size returns 0. if all gifs are broken, don't return restults_array
		global $ft_dom;
		$results_array = array();
		$imgs = $ft_dom->getElementsByTagName('img');
		$gifs = 0;
		$min_gifs_trigger = 7;
		$total_files_size = 0;
        foreach ($imgs as $img) {
			if ($img->hasAttribute('src')) {
				if(strripos($img->getAttribute('src'),'.gif') == (strlen($img->getAttribute('src')) - 4)) {
					$gifs++;

					$link = Helper::getAbsoluteResourceLink($img->getAttribute('src'));
					$total_files_size += floatval(Helper::getResourceSizeBytes($link));
				}
			}
		}

		if($gifs >= $min_gifs_trigger) {
			$results_array[0] = $gifs;
			//THERE IS AN ERROR HERE!!!!
			//$results_array[1] = round(13.7548828125, 2, PHP_ROUND_HALF_UP) + 'KB'; //outputs: 13.75 and should be 13.76
			$results_array[1] = round($total_files_size/1024,2, PHP_ROUND_HALF_UP) . 'KB';
			return $results_array;
		}
        return false;
    }

    public function DoubleSlashesInUrl()
    {
		//besides paired with the protocol, are there redundant slashes?
		//in what browser does this not work?
        return false;
    }

    public function ManyImagesFlag()
    {
		global $ft_dom;
		$imgs = $ft_dom->getElementsByTagName('img');
		if($imgs->length > 10) return array($imgs->length);
        return false;
    }

    public function AmpersandUnescapedInLink()
    {
		$links_array = Helper::getAllDomLinks();
	    $code = array('');
		$code[1] = 0;
		$code[2] = '';
		foreach($links_array as $link)
		{
			if(strpos($link,'&') !== false)
			{
				//the next four chars must be amp; (five chars total)
				if(substr_compare($link,'&',strpos($link,'&'),5) !== false)
				{
					if($code[1] <= Helper::$max_disp_threshold) {
						$link = Helper::addWhitespaceForReportFormatting($link);
						$code[0] .= '`'.$link.'` ';
					}
					$code[1]++;
				}
			}

		}
 		if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			if($code[1] > Helper::$max_disp_threshold) { $code[0] .= '...'; }
			return $code;
		}
       return false;
	}

	//assume they only have one for now, and get the first one.
    public function DeprecatedElement()
    {
		global $ft_dom;

	   $return_array = array();
	   $code = array('');
	   $deprecated_elements = array('applet',
									'dir',
									'isindex',
									'menu',
									'basefont',
									'center',
									'font',
									's',
									'strike',
									'u'
									);

		$deprecated_replacements = array();
		$deprecated_replacements['applet'] = 'object';
		$deprecated_replacements['dir'] = 'ul';
		$deprecated_replacements['isindex'] = 'input';
		$deprecated_replacements['menu'] = 'nav';
		$deprecated_replacements['basefont'] = 'css';
		$deprecated_replacements['center'] = 'css';
		$deprecated_replacements['font'] = 'css';
		$deprecated_replacements['s'] = 'css';
		$deprecated_replacements['strike'] = 'css';
		$deprecated_replacements['u'] = 'css';

		foreach($deprecated_elements as $deprecated_element) {
			$code = Helper::testForElement($deprecated_element);
			if($code[0] != '') {
				$return_array[0] = $deprecated_element;
				if($deprecated_replacements[$deprecated_element] =='css') {
					$return_array[1] = 'CSS';
				}
				else
				{
					$return_array[1] = '"'.$deprecated_replacements[$deprecated_element].'"';
				}

				//don't print a bunch of garbage. only if it's a short line, display code. otherwise, show snippet with line no
				if(strlen($code[0]) > 80)
				{
					$return_array[2] = substr($code[0], 0, 80) . '...`';
				}
				else
				{
					$return_array[2] = $code[0];
				}
				return $return_array;
			}
		}

        return false;
    }

	/* 	this cannot be run -- it is far too slow.
    public function DeprecatedAttributeNotAlign()
    {
		global $ft_dom;
		$code = array('');

		$deprecated_attributes['img'] = array('vspace','border','hspace');
		$deprecated_attributes['object'] = array('vspace','border','hspace');
		$deprecated_attributes['body'] = array('alink','background','bgcolor','link','text','vlink');
		$deprecated_attributes['table'] = array('bgcolor');
		$deprecated_attributes['td'] = array('bgcolor','nowrap','width');
		$deprecated_attributes['tr'] = array('bgcolor');
		$deprecated_attributes['th'] = array('bgcolor','nowrap','width');
		$deprecated_attributes['hr'] = array('noshade','size','width');
		$deprecated_attributes['ol'] = array('start');
		$deprecated_attributes['li'] = array('type','value');
		$deprecated_attributes['pre'] = array('width');

		foreach($deprecated_attributes as $key => $values)
		{
			$elements = $ft_dom->getElementsByTagName($key);
	        foreach ($elements as $element) {
				foreach($values as $value)
				{
					if ($element->hasAttribute($value)) {
						echo "<br>found deprecated attribute: " . $key . ":" . $value;
						$code[0] = $value;
						$code[1] = $key;
						$code[2] = Helper::printCodeWithLineNumber($element);
 						return $code;
					}
				}
			}

		}

		return false;
	}
	*/

    //this is the not perfect but optimized version.
    public function DeprecatedAttributeAlt()
    {
		global $ft_data;
		$code = array('');

		$deprecated_attributes = array('nowrap',
										'align',
										'start',
										'vspace',
										'border',
										'hspace',
										'alink',
										'background',
										'bgcolor',
										'link',
										'text',
										'vlink',
										'noshade',
										//'size',
										//'type',
										//'value',
										'width');

/*
		$deprecated_in_tags['img'] = array('vspace','border','hspace','width');
		$deprecated_in_tags['object'] = array('vspace','border','hspace');
		$deprecated_in_tags['body'] = array('alink','background','bgcolor','link','text','vlink');
		$deprecated_in_tags['table'] = array('bgcolor');
		$deprecated_in_tags['td'] = array('bgcolor','nowrap','width');
		$deprecated_in_tags['tr'] = array('bgcolor');
		$deprecated_in_tags['th'] = array('bgcolor','nowrap','width');
		$deprecated_in_tags['hr'] = array('noshade','size','width');
		$deprecated_in_tags['ol'] = array('start');
		$deprecated_in_tags['li'] = array('type','value');
		$deprecated_in_tags['pre'] = array('width');
		$deprecated_in_tags['div'] = array('width');
*/
		//foreach($deprecated_in_tags as $key => $attribute_array)
		//{

			foreach($deprecated_attributes as $attribute)
			{
				//for efficiency, does the attribute even exist?

				//get the array of positions for this!!!
				$strpos = strpos($ft_data,' '.$attribute.'=');
				if($strpos !== false)
				{
					//this is far from a perfect search:
					//find the "<" backwards from strpos
					//echo "start reverse search: " . ($strpos - strlen($ft_data));
					$open_tag_start = strrpos($ft_data,'<',$strpos - strlen($ft_data));
					$tag = substr($ft_data,$open_tag_start+1,(strpos($ft_data,' ',$open_tag_start) - ($open_tag_start+1)));
					if($attribute == 'width' && $tag == 'img') { continue; }

					$code[1] = $tag;
					$code[0] = 	$attribute;
					$code[2] = '`'.substr($ft_data,$open_tag_start,((strpos($ft_data,'>',$open_tag_start)+1) - $open_tag_start)).'`';
					return $code;

					//$open_tag = substr($ft_data, $open_tag_start, strpos($ft_data,' ',$open_tag_start));

					//and then only log if open_tag is $key

					//$pattern = '/<'.$key.'\s+.*'.$attribute.'=.*>/';

					//preg_match($pattern,$ft_data,$match1);
					//the strpos search is not very good. if it wasn't really found, don't return it.
					//the is an issue with content seeming like code to FET.
					//echo print_r($match1);

					/*
					if(isset($match1[0])) {
						$code[0] = $deprecated_attribute;
						//we have an issue with results with nested tags.
						//this is returned:
						//<div class="logomain"> <a href="/"><img src="http://www.ekwity.com/images//logos/ekwity_whitelogo.png" alt="Ekwity.com" width="316" height="120"/></a> </div>
						//therefore let's test the tag from where deprecated element is found.

						$code[1] = substr($match1[0],1,strpos($match1[0],' ')-1);
						if($deprecated_attribute == 'width' && strtolower($code[1]) == 'img') { continue; }
						$code[2] = '`'.$match1[0].'`';
						return $code;
					} else {
						//the previous search was simply not very good.
						continue;
					}
					*/
				}

			//}
		}
		return false;
	}

    //this is the not perfect but optimized version.
    public function DeprecatedAttribute()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = '';
		$code[2] = 0;
		$instance_array = array();
		$deprecated_in_tags['img'] = array('vspace','border','hspace','align');
		$deprecated_in_tags['object'] = array('vspace','border','hspace');
		$deprecated_in_tags['body'] = array('alink','background','bgcolor','link','text','vlink');
		$deprecated_in_tags['table'] = array('bgcolor','align');
		$deprecated_in_tags['td'] = array('bgcolor','nowrap','width');
		$deprecated_in_tags['tr'] = array('bgcolor');
		$deprecated_in_tags['th'] = array('bgcolor','nowrap','width');
		$deprecated_in_tags['hr'] = array('noshade','size','width');
		$deprecated_in_tags['ol'] = array('start');
		$deprecated_in_tags['li'] = array('type','value');
		$deprecated_in_tags['pre'] = array('width');
		$deprecated_in_tags['div'] = array('align');
		$deprecated_in_tags['p'] = array('align');
		$deprecated_in_tags['h1'] = array('align');
		$deprecated_in_tags['h2'] = array('align');
		$deprecated_in_tags['h3'] = array('align');
		$deprecated_in_tags['h4'] = array('align');
		$deprecated_in_tags['h5'] = array('align');
		$deprecated_in_tags['h6'] = array('align');
		$deprecated_in_tags['hr'] = array('align','noshade','size','width');

		foreach($deprecated_in_tags as $key => $attribute_array)
		{
			$elements = $ft_dom->getElementsByTagName($key);
			foreach($elements as $element)
			{
				foreach($attribute_array as $attribute)
				{
					if($element->hasAttribute($attribute)) {
						$code[2]++;
						//don't show too many of these lines.
						if($code[2] < 4 && !in_array("$key-$attribute",$instance_array)) {
							$code[0] .= '"'.$attribute.'" is a deprecated HTML4 attribute for `<'.$key.">`\n\n";
						} elseif ($code[2] == 4) {
							$code[0] .= '...';
						}
						$instance_array[] = "$key-$attribute";
					}
				}

				//this is imperfect because it only finds the first depecated attribute. This is a very common result. Fix ASAP.
				if($code[0] != '') {
					if($code[2] > 1) { $code[1] = 's'; }
					return $code;
				}
			}
		}

		return false;
	}

    public function RequiredTagAttributePairMissing()
    {
		return false;
	}

    public function ImgAltAttributeMissing()
    {
		global $ft_dom;
		$code = array('');
	/*
		$elements = $ft_dom->getElementsByTagName('img');

        foreach ($elements as $element) {
			if ((!$element->hasAttribute('alt') || $element->getAttribute('alt') == '') && !Helper::likelyPixel($element)) {
				$code[0] .=  Helper::printCodeWithLineNumber($element);
			}
		}

		if($code[0] != '') {
			return $code;
		}
        return false;
*/

		$code[1] = 0;
		$code[2] = '';
		$elements = $ft_dom->getElementsByTagName('img');

		foreach ($elements as $element) {
			if ((!$element->hasAttribute('alt') || $element->getAttribute('alt') == '') && !Helper::likelyPixel($element)) {
				$code[1]++;
				if($code[1] <= Helper::$max_disp_threshold) { $code[0] .= Helper::printCodeWithLineNumber($element); }
			}
			if ((!$element->hasAttribute('width') && !Helper::hasInlineStyleAttribute($element,'width')) || (!$element->hasAttribute('height') && !Helper::hasInlineStyleAttribute($element,'width'))) {
			}
		}

		if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			if($code[1] > Helper::$max_disp_threshold) { $code[0] .= '...'; }
			return $code;
		}
		return false;

    }

    public function MissingImgHeightOrWidth()
    {
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$code[2] = '';
		$elements = $ft_dom->getElementsByTagName('img');

        foreach ($elements as $element) {
			//exit if img points to another server (for now). it is likely a pixel.

			//if ($element->hasAttribute('width')) { echo "\nwidth: " . $element->getAttribute('width'); }
			//if ($element->hasAttribute('height')) { echo "\nheight: " . $element->getAttribute('height'); }

			//continue for now if class is applied. they might be setting height and width that way.
			if($element->hasAttribute('class') && $element->getAttribute('class') != '') { continue; }
			if($element->hasAttribute('id') && $element->getAttribute('id') != '') { continue; }
			if($element->hasAttribute('src') && (strpos($element->getAttribute('src'),'pixel') !== false || strpos($element->getAttribute('src'),'doubleclick') !== false || strpos($element->getAttribute('src'),'shareasale') !== false )) { continue; }

			if ((!$element->hasAttribute('width') && !Helper::hasInlineStyleAttribute($element,'width')) || (!$element->hasAttribute('height') && !Helper::hasInlineStyleAttribute($element,'width'))) {
				$code[1]++;
				if($code[1] <= Helper::$max_disp_threshold) { $code[0] .= Helper::printCodeWithLineNumber($element); }
			}
		}

		if($code[0] != '') {
			if($code[1] > 1) { $code[2] = 's'; }
			if($code[1] > Helper::$max_disp_threshold) { $code[0] .= '...'; }
			return $code;
		}
        return false;
    }

    public function MissingActionInForm()
    {
		//usually there are not so many forms on a page. So for now, don't limit results.
		global $ft_dom;
		$code = array('');
		$code[1] = 0;
		$elements = $ft_dom->getElementsByTagName('form');
        foreach ($elements as $element) {
			if (!$element->hasAttribute('action')) {
				$code[1]++;
				$code[0] .=  Helper::printCodeWithLineNumber($element);
			}
		}

		if($code[0] != '') {
			if($code[1] > 1) { $code[1] = 's'; } else { $code[1] = ''; }
			return $code;
		}

        return false;
    }

    public function LoneHashInHref()
    {
		global $ft_dom;
		$code = array('');
		$elements = $ft_dom->getElementsByTagName('a');
        foreach ($elements as $element) {
			if ($element->hasAttribute('href') && $element->getAttribute('href') == '#') {
				$code[0] .=  Helper::printCodeWithLineNumber($element);
			}
		}

		if($code[0] != '') {
			return $code;
		}

        return false;
    }

    public function BoldTags()
    {
		global $ft_dom;

		$code = Helper::testForElement('b');
		if(!empty($code)) {
			return $code;
		}
	    return false;
    }

    public function MetadataContentEmpty()
	{
		global $ft_dom;
		$code = array('');

		$elements = $ft_dom->getElementsByTagName('meta');

        foreach ($elements as $element) {
			if ($element->hasAttribute('content') && $element->getAttribute('content') == '') {
				$code[0] .=  Helper::printCodeWithLineNumber($element);
			}
		}
		if($code[0] != '') {
			return $code;
		}

        return false;
	}

    public function HasDocumentWrite()
    {
		if(Helper::stringFound('document.write(')) {
			return true;
		}
	    return false;
    }

    public function InsignificantOrNoContent()
    {
		global $ft_dom;

		$elements = $ft_dom->getElementsByTagName('body');
		$code_str = '';
		$doc=new \DOMDocument();
		$doc->preserveWhiteSpace = false;

		//even if the html doc does not have a body tag (which is optional), php is going to give it one IF there is ANY content.
		//that is, if it has content like this: <!doctype html><title>hey</title><p>hi ann!</p>
		//php returns <body><p>hi ann!</p></body> when getting a string with saveHTML()
		if($elements->length == 0) {
			return true;
		} else {
			$doc->appendChild($doc->importNode($elements->item(0),true));
			$code_str = trim($doc->saveHTML());
			if(strlen($code_str) < 100) {
				return true;
			}
		}

	    return false;
    }

}


text:
//: annotations/Multiplier.java
// APT-based annotation processing.
package annotations;

@ExtractInterface("IMultiplier")
public class Multiplier {
  public int multiply(int x, int y) {
    int total = 0;
    for(int i = 0; i < x; i++)
      total = add(total, y);
    return total;
  }
  private int add(int x, int y) { return x + y; }
  public static void main(String[] args) {
    Multiplier m = new Multiplier();
    System.out.println("11*16 = " + m.multiply(11, 16));
  }
} /* Output:
11*16 = 176
*///:~

redpajama_set_name: RedPajamaGithub


text:
namespace bp = boost::python;

struct controlui_to_py {
	static PyObject *convert( const PControlUI &s );
	static PyTypeObject const* get_pytype();
};

struct controlui_from_py {
	static void *convertible( PyObject *object );
	static void construct( PyObject *object, boost::python::converter::rvalue_from_python_stage1_data *data );
};

void python_controlui_registration() {
	static bool executed = false;
	if ( !executed ) {
		executed = true;
		using namespace boost::python;

		converter::registry::push_back(
			controlui_from_py::convertible, controlui_from_py::construct,
			type_id< PControlUI >()
			);
		to_python_converter< PControlUI, controlui_to_py, false >();
	}
}

PyObject *controlui_to_py::convert( const PControlUI &s ) {
	return PyLong_FromLong( (long)s);
}
PyTypeObject const *controlui_to_py::get_pytype() {
	return &PyLong_Type;
}

void *controlui_from_py::convertible( PyObject *object ) {
	return object;
}

void controlui_from_py::construct( PyObject *object, boost::python::converter::rvalue_from_python_stage1_data *data ) {
	int pControl = PyLong_AsLong(object);

	void *storage = reinterpret_cast<
		boost::python::converter::rvalue_from_python_storage< PControlUI >*
	>( data )->storage.bytes;
	new (storage) long( pControl );
	data->convertible = storage;
}


text:
package net.q3aiml.config;

import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;

/**
 * Provides configuration in the form of a map of name strings to value strings.
 */
public interface ConfigProvider {
    /**
     * Returns the values of this config (must not change unless implements {@link net.q3aiml.config.DynamicConfig}).
     */
    @Nonnull
    public ImmutableMap<String, String> get();
}


text:
use protocol::Enum;

#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
pub struct Handshake;

#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
pub struct Hello {
    id: i64,
    data: Vec<u8>,
}

#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
pub struct Goodbye {
    id: i64,
    reason: String,
}

#[derive(protocol::Protocol, Clone, Debug, PartialEq)]
#[protocol(discriminant = "integer")]
#[repr(u16)]
pub enum PacketKind {
    #[protocol(discriminator(0x00))]
    Handshake(Handshake),
    #[protocol(discriminator(0xaa))]
    Hello(Hello),
    #[protocol(discriminator(0xaf))]
    Goodbye(Goodbye),
}

fn main() {
    println!("enum discriminant 1: {}", PacketKind::Handshake(Handshake).discriminator());
    println!("enum discriminant 2: {}", PacketKind::Goodbye(Goodbye { id: 22, reason: "hello".to_string() }).discriminator());
}


text:
<?php
	/**
	 * models/BotResource/BotMentionHandler.php
	 * Contains the BotMentionHandler class
	 *
	 * @author Cory Gehr
	 */

namespace GroupMeBot\BotResource;

class BotMentionHandler extends \Thinker\Framework\Model
{
	/**
	 * process_message()
	 * Processes the message
	 *
	 * @access public
	 */
	public function process_message($post)
	{
		// Parse message text
		$breakdown = explode(" ", $post);

		// Look for SameBot references
		$spotted = array();

		for($i=0; $i<count($breakdown); $i++)
		{
			$word = $breakdown($i);

			if(strtolower($word) == "samebot")
			{
				$spotted[] = $i;
			}
		}

		// Continue processing if it was found
		if(!empty($spotted))
		{
			// We're probably sending a message
			$message = new CallbackResponse($post->group_id);

			// Check the context of the word
			// For the first iteration of this, we're just going to use the first reference
			$ind = $spotted[0];

			// Store indices of positive or negative references
			$pos = array();
			$neg = array();

			// Look before the reference
			for($i=0;$i<$ind;$i++)
			{
				$curr_word = $breakdown[$i];
			}

			// Look after the reference
			for($i=$ind+1;$i<count($breakdown);$i++)
			{
				$curr_word = $breakdown[$i];
			}
		}
	}
}


text:
{% extends "base_site.html" %}

{% block title %}Interim Meetings{% endblock %}

{% block extrahead %}{{ block.super }}

{% endblock %}

{% block breadcrumbs %}{{ block.super }}
  » Proceedings
  » Interim Select Group
  » {{ group.acronym }}

{% endblock %}

{% block content %}

Working Group - {{ group_name }}

Scheduled / Completed {{group.acronym}} Interim Meetings:

       {% if meetings %}

         {% for meeting in meetings %}

{{meeting.date}}
           {% if request.user_is_secretariat %}
              - [Delete]
           {% endif %}

         {% endfor %}

       {% else %}

No meetings.

       {% endif %}

New Meeting

Create a new {{ group.acronym }} Interim Meeting:

       <form action="." method="post">
       {{ form.as_p }}

       {% include "includes/buttons_submit_back.html" %}

       </form>

{% endblock %}


text:
/**
 * Created by maoli on 16/10/8.
 */
var mongoose = require('mongoose');
var settings = require('../../settings');
var autoIncrement = require('mongoose-auto-increment');   //自增ID 模块
autoIncrement.initialize(mongoose.connection);   //初始化

//schema
var FollowUpParameterSchema = new mongoose.Schema({
    "id" : String,
    "StudyID" : String,    //研究编号
    "VisitNam" : String,   //访视期
    "VisitDy" : String,   //计划访视日
    "VisitonTrtYN" : String,//是否为仿视期还是停药期
    "VisitWk" : String,//访视周
    "VisitNum" : String,//访视次序
    "ArmCD" : String,//治疗分组代码
    "Arm" : String,//治疗分组标签
    "VisitDyL" : String,//计划访视日下限
    "VisitDyU" : String,//计划访视日上限
    "VisitTrtYN" : String,
    "Date" : Date, //导入时间
});
FollowUpParameterSchema.plugin(autoIncrement.plugin, {
    model: 'Books',
    field: 'id',
    startAt: 0,
    incrementBy: 1
});
//索引
FollowUpParameterSchema.index({ "Date": 1});
FollowUpParameterSchema.index({ "StudyID": 1});

//model
var FollowUpParameter = mongoose.model("FollowUpParameter",FollowUpParameterSchema);

module.exports = FollowUpParameter;


text:
package com.all.facebook.impl;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import com.all.facebook.FacebookService;
import com.all.facebook.FacebookServiceException;
import com.all.facebook.FacebookServiceOAuthException;
import com.all.facebook.FacebookUser;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookException;
import com.restfb.exception.FacebookOAuthException;
import com.restfb.types.FacebookType;
import com.restfb.types.User;

@Service
public class FacebookServiceImpl implements FacebookService {

	private static final String PASSWORD = "225ce6bf7a193870690514db2e0259f5";

	private static final String PIPE = "|";

	// given in the application settings page in Facebook
	private static final String API_KEY = "455cd6bc104968b10e9b4ea1335dc57e";

	// App authentication is handled by verifying that the redirect_uri is in the same domain as
	// the Site URL configured in the Developer App.
	private static final String REDIRECT_URI = "www.facebook.com/connect/login_success.html";

	// for more info: http://developers.facebook.com/docs/authentication/
	// check Client-side Flow, for not exposing the app secret
	// "The app secret is available from the Developer App and should not be shared with anyone or embedded
	// in any code that you will distribute (you should use the client-side flow for these scenarios)."
	private static final String AUTHORIZATION_URL = "https://graph.facebook.com/oauth/authorize?"
			+ "client_id=159880797410187"
			+ "&redirect_uri=http://" + REDIRECT_URI
			+ "&scope=xmpp_login,offline_access,publish_stream" // offline_access == access token expires=0
			+ "&display=popup" + "&response_type=token";// this enables the client-side flow

	private static final String ENCODING_ISO_8859_1 = "ISO-8859-1";

	private static final String EQUALS = "=";

	private static final String AMPERSAND = "&";

	private FacebookClient facebookClient;

	private String accessToken;

	@Override
	public String authorizationUrl() {
		return AUTHORIZATION_URL;
	}

	@Override
	public String redirectUrl() {
		return REDIRECT_URI;
	}

	@Override
	public String authorizeUrl(String responseUrl) throws FacebookServiceException {
		URL url;

		try {
			url = new URL(responseUrl);
		} catch (MalformedURLException e) {
			throw new FacebookServiceException(e);
		}

		if (!responseUrl.contains(REDIRECT_URI)) {
			throw new FacebookServiceException("The url does not correpond with the redirect_uri parameter: " + responseUrl);
		}

		String ref = url.getRef();
		if (ref == null) {
			Map<String, String> error = extractKeyValuePairs(url.getQuery());
			String errorType = error.get("error");
			throw new FacebookServiceException(error.toString(), errorType);
		}

		Map<String, String> keyValuePairs = extractKeyValuePairs(ref);

		if (!keyValuePairs.containsKey("access_token")) {
			throw new FacebookServiceException("Could not find the access token in the responseUrl: " + responseUrl);
		}

		authorize(keyValuePairs.get("access_token"));

		return accessToken;
	}

	private Map<String, String> extractKeyValuePairs(String queryString) throws FacebookServiceException {
		try {

			Map<String, String> keyValuePairs = new HashMap<String, String>();
			StringTokenizer pairs = new StringTokenizer(queryString, AMPERSAND);
			while (pairs.hasMoreTokens()) {
				String pair = pairs.nextToken();
				StringTokenizer parts = new StringTokenizer(pair, EQUALS);
				String key = URLDecoder.decode(parts.nextToken(), ENCODING_ISO_8859_1);
				String value = URLDecoder.decode(parts.nextToken(), ENCODING_ISO_8859_1);
				keyValuePairs.put(key, value);
			}
			return keyValuePairs;

		} catch (UnsupportedEncodingException e) {
			throw new FacebookServiceException(e);
		}
	}

	@Override
	public String getXmppUser(String accessToken) throws FacebookServiceException {
		String[] keyArray = validateAccessTokenFormat(accessToken);
		String sessionKey = keyArray[1];
		return new StringBuilder(API_KEY).append(PIPE).append(sessionKey).toString();
	}

	@Override
	public String getXmppPassword(String accessToken) throws FacebookServiceException {
		return PASSWORD;
	}

	private String[] validateAccessTokenFormat(String accessToken) throws FacebookServiceException {
		String[] keyArray = accessToken.split(Pattern.quote(PIPE));
		;
		if (keyArray.length != 3) {
			throw new FacebookServiceException("Invalid access token format");
		}
		return keyArray;
	}

	@Override
	public void authorize(String accessToken) throws FacebookServiceException {
		try {
			this.accessToken = accessToken;
			// if facebook responses with no error then we have a valid access token
			getFacebookClient().fetchObject("me", User.class);
		} catch(FacebookOAuthException foae){
			this.accessToken = null;
			this.facebookClient = null;
			throw new FacebookServiceOAuthException(foae.getErrorMessage(), foae.getErrorType());
		} catch (FacebookServiceException fse) {
			this.accessToken = null;
			this.facebookClient = null;
			throw fse;
		} catch (FacebookException e) {
			this.accessToken = null;
			this.facebookClient = null;
			throw new FacebookServiceException(e);
		}
	}

	@Override
	public void publishFeed(String connection, String message) throws FacebookServiceException {
		try {
			getFacebookClient().publish(connection + "/feed", FacebookType.class, Parameter.with("message", message));
		} catch(FacebookOAuthException foae){
			throw new FacebookServiceOAuthException(foae.getErrorMessage(), foae.getErrorType());
		} catch (FacebookException e) {
			throw new FacebookServiceException(e);
		}
	}

	@Override
	public List<FacebookUser> getFriends() throws FacebookServiceException {
		List<FacebookUser> friends = new ArrayList<FacebookUser>();
		Connection<User> friendConnections = getFacebookClient().fetchConnection("me/friends", User.class);
		for (User user : friendConnections.getData()) {
			friends.add(adapt(user));
		}
		return friends;
	}

	private FacebookUser adapt(User user) {
		return new FacebookUserImpl(user.getId(), user.getName());
	}

	private FacebookClient getFacebookClient() throws FacebookServiceException {
		if (facebookClient == null) {
			if (accessToken == null) {
				throw new FacebookServiceException("Unable to create facebook client without an access token");
			}
			facebookClient = new DefaultFacebookClient(accessToken);
		}
		return facebookClient;
	}
}


text:
package rocks.xmpp.core.stream;

import rocks.xmpp.core.XmppException;
import rocks.xmpp.core.stream.model.StreamError;
import rocks.xmpp.core.stream.model.errors.Condition;

/**
 * Represents a stream error.
 * This exception is thrown if client receives a stream error.
 *

 * This class is immutable.
 *
 * @author Christian Schudt
 * @see 4.9.  Stream Errors
 */
public final class StreamErrorException extends XmppException {

    private final StreamError streamError;

    /**
     * Constructs a stanza exception.
     *
     * @param streamError The underlying stream error.
     */
    public StreamErrorException(StreamError streamError) {
        super(streamError.toString());
        this.streamError = streamError;
    }

    /**
     * Gets the stream error.
     *
     * @return The stream error.
     */
    public final StreamError getError() {
        return streamError;
    }

    /**
     * Gets the defined error condition. If the condition is unknown, {@link Condition#UNDEFINED_CONDITION} is returned.
     * This is a shortcut for {@code getError().getCondition()}.
     *
     * @return The error condition.
     * @see 4.9.3.  Defined Stream Error Conditions
     */
    public final Condition getCondition() {
        return streamError.getCondition();
    }
}


text:
require 'test_helper'

class GraphsControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:graphs)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create graph" do
    assert_difference('Graph.count') do
      post :create, :graph => { }
    end

    assert_redirected_to graph_path(assigns(:graph))
  end

  test "should show graph" do
    get :show, :id => graphs(:one).to_param
    assert_response :success
  end

  test "should get edit" do
    get :edit, :id => graphs(:one).to_param
    assert_response :success
  end

  test "should update graph" do
    put :update, :id => graphs(:one).to_param, :graph => { }
    assert_redirected_to graph_path(assigns(:graph))
  end

  test "should destroy graph" do
    assert_difference('Graph.count', -1) do
      delete :destroy, :id => graphs(:one).to_param
    end

    assert_redirected_to graphs_path
  end
end


text:
import tests.appserver
from tests.web import *

import random
import string

class TestCase(WebTestCase):
  @classmethod
  def setup_class(cls):
    super(TestCase, cls).setup_class()

    cls._appserver = tests.appserver.AppServer(*tests.appserver.AppServer.fetch_config('default_appserver'))
    cls._appserver.start()

  @classmethod
  def teardown_class(cls):
    if cls._appserver:
      cls._appserver.stop()

    super(TestCase, cls).teardown_class()

  def test_static(self):
    home_url = urlparse.urljoin(self.__class__.get_root_url(), '/static/status/500.html')

    self.__class__.goto(home_url)

    with self.browser as B:
      HAS_TITLE(B, 'Osadnici')


text:
package log

import (
	"errors"
	"fmt"
	"path/filepath"
	"runtime"
	"strings"
	"testing"

	k8sv1 "k8s.io/api/core/v1"
	v12 "k8s.io/apimachinery/pkg/apis/meta/v1"

	v1 "kubevirt.io/api/core/v1"
)

var logCalled bool = false
var logParams []interface{} = make([]interface{}, 0)

type MockLogger struct {
}

func (l MockLogger) Log(params ...interface{}) error {
	logCalled = true
	logParams = append(logParams, params)
	return nil
}

func assert(t *testing.T, condition bool, failMessage string) {
	if !condition {
		_, filePath, lineNumber, _ := runtime.Caller(1)
		fileName := filepath.Base(filePath)
		t.Fatalf("[%s:%d] %s", fileName, lineNumber, failMessage)
	}
}

func setUp() {
	defaultComponent = "test"
	logCalled = false
	logParams = make([]interface{}, 0)
}

func tearDown() {

}

func TestDefaultLogLevels(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.Log("default level message")
	assert(t, logCalled, "default loglevel should have been info")
	tearDown()
}

// Simply a self-check test as most tests will depend on this behavior working
// Enforces that unit tests are run in isolated contexts
func TestMockLogger(t *testing.T) {
	setUp()
	l := MockLogger{}
	assert(t, !logCalled, "Test Case was not correctly initialized")
	assert(t, len(logParams) == 0, "logParams was not reset")
	l.Log("test", "message")
	assert(t, logCalled, "MockLogger was not called")
	tearDown()
}

func TestBadLevel(t *testing.T) {
	setUp()
	l := Logger("test")
	error := l.SetLogLevel(10)
	assert(t, error != nil, "Allowed to set illegal log level")
	assert(t, l.filterLevel != 10, "Allowed to set illegal log level")
	tearDown()
}

func TestGoodLevel(t *testing.T) {
	setUp()
	l := Logger("test")
	error := l.SetLogLevel(INFO)
	assert(t, error == nil, "Unable to set log level")
	tearDown()
}

func TestComponent(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.Log("foo", "bar")

	assert(t, len(logParams) == 1, "Expected 1 log line")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	tearDown()
}

func TestWith(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})

	log.With("arg1", "val1").Log("foo1", "bar1")
	log.With("arg2", "val2").Log("foo2", "bar2")

	assert(t, len(logParams) == 2, "Expected 2 log lines")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[8].(string) == "arg1", "Custom With() field was not logged")
	assert(t, logEntry[9].(string) == "val1", "Custom With() field was not logged")

	logEntry = logParams[1].([]interface{})
	assert(t, logEntry[8].(string) == "arg2", "Custom With() was not logged")
	assert(t, logEntry[9].(string) == "val2", "Custom With() was not logged")

	tearDown()
}

func TestInfoCutoff(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(WARNING)
	assert(t, log.filterLevel == WARNING, "Unable to set log level")

	log = log.Level(INFO)
	log.Log("This is an info message")
	assert(t, !logCalled, "Info log entry should not have been recorded")

	log = log.Level(WARNING)
	log.Log("This is a warning message")
	assert(t, logCalled, "Warning log entry should have been recorded")
	tearDown()
}

func TestVerbosity(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})

	assert(t, log.verbosityLevel == 2, "Default verbosity should be 2")

	if err := log.SetVerbosityLevel(3); err != nil {
		t.Fatal("Unexpected error setting verbosity")
	}
	log.Log("this is a verbosity level 2 message")
	assert(t, logCalled, "Log entry (V=2) should have been recorded")

	logCalled = false
	log = log.V(4)
	log.Log("This is a verbosity level 4 message")
	assert(t, !logCalled, "Log entry (V=4) should not have been recorded")

	// this call should be ignored. repeat last test to prove it
	logCalled = false
	log = log.V(-1)
	log.Log("This is a verbosity level 4 message")
	assert(t, !logCalled, "Log entry (V=4) should not have been recorded")

	logCalled = false
	log.V(3).Log("This is a verbosity level 3 message")
	assert(t, logCalled, "Log entry (V=3) should have been recorded")

	// once again, this call should do nothing.
	logCalled = false
	log = log.V(-1)
	log.Log("This is a verbosity level 4 message")
	assert(t, !logCalled, "Log entry (V=4) should not have been recorded")
	tearDown()
}

func TestNegativeVerbosity(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	err := log.SetVerbosityLevel(-1)
	assert(t, err != nil, "Requesting a negative verbosity should not have been allowed")
	tearDown()
}

func TestCachedLoggers(t *testing.T) {
	setUp()
	logger := MockLogger{}
	log := Logger("test")
	log.SetLogger(logger)

	// set a value on this log class
	log.SetLogLevel(ERROR)
	// obtain a new filtered logger and prove it reflects that same log level

	log2 := Logger("test")

	assert(t, log.filterLevel == ERROR, "Log object was not correctly filtered")
	assert(t, log2.filterLevel == ERROR, "Log object was not cached")
	tearDown()
}

func TestWarningCutoff(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})

	log.Level(WARNING).Log("message", "test warning message")
	assert(t, logCalled, "Warning level message should have been recorded")

	log.Level(ERROR).Log("error", "test error message")
	assert(t, logCalled, "Error level message should have been recorded")
	tearDown()
}

func TestLogConcurrency(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	// create a new log object from the previous one.
	log2 := log.Level(WARNING)
	assert(t, log.currentLogLevel != log2.currentLogLevel, "log and log2 should not have the same log level")
	assert(t, log.currentLogLevel == INFO, "Calling Warning() did not create a new log object")
	tearDown()
}

func TestInfoMessage(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	log.Level(INFO).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[INFO], "Logged line was not infoLevel level")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	tearDown()
}

func TestWarningMessage(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(WARNING)
	log.Level(WARNING).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[WARNING], "Logged line was not warningLevel level")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	tearDown()
}

func TestErrorMessage(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(ERROR)
	log.Level(ERROR).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[ERROR], "Logged line was not errorLevel level")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	tearDown()
}

func TestCriticalMessage(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(FATAL)
	log.Level(FATAL).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[FATAL], "Logged line was not fatalLevel level")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	tearDown()
}

func TestObject(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	vm := v1.VirtualMachineInstance{ObjectMeta: v12.ObjectMeta{Namespace: "test"}}
	log.Object(&vm).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[INFO], "Logged line was not of level infoLevel")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[4].(string) == "pos", "Logged line was not pos")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	assert(t, logEntry[8].(string) == "namespace", "Logged line did not contain object namespace")
	assert(t, logEntry[10].(string) == "name", "Logged line did not contain object name")
	assert(t, logEntry[12].(string) == "kind", "Logged line did not contain object kind")
	assert(t, logEntry[14].(string) == "uid", "Logged line did not contain UUID")
	tearDown()
}

func TestObjectRef(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	vmRef := &k8sv1.ObjectReference{
		Kind:      "test",
		Name:      "test",
		Namespace: "test",
		UID:       "test",
	}
	log.ObjectRef(vmRef).Log("test", "message")
	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[INFO], "Logged line was not of level infoLevel")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[4].(string) == "pos", "Logged line was not pos")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	assert(t, logEntry[8].(string) == "namespace", "Logged line did not contain object namespace")
	assert(t, logEntry[10].(string) == "name", "Logged line did not contain object name")
	assert(t, logEntry[12].(string) == "kind", "Logged line did not contain object kind")
	assert(t, logEntry[14].(string) == "uid", "Logged line did not contain UUID")
	tearDown()
}

func TestError(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	err := errors.New("Test error")
	log.Level(ERROR).Log(err)
	assert(t, logCalled, "Error was not logged via .Log()")

	logCalled = false
	log.msg(err)
	assert(t, logCalled, "Error was not logged via .msg()")

	logCalled = false
	// using more than one parameter in format string
	log.msgf("[%d] %s", 1, err)
	assert(t, logCalled, "Error was not logged via .msgf()")

	logCalled = false
	log.msgf("%s", err)
	assert(t, logCalled, "Error was not logged via .msgf()")
	tearDown()
}

func TestMultipleLevels(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	// change levels more than once
	log.Level(WARNING).Level(INFO).Level(WARNING).msg("test")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[0].(string) == "level", "Logged line did not have level entry")
	assert(t, logEntry[1].(string) == LogLevelNames[WARNING], "Logged line was not of level warningLevel")
	assert(t, logEntry[2].(string) == "timestamp", "Logged line is not expected format")
	assert(t, logEntry[4].(string) == "pos", "Logged line was not pos")
	assert(t, logEntry[6].(string) == "component", "Logged line is not expected format")
	assert(t, logEntry[7].(string) == "test", "Component was not logged")
	assert(t, logEntry[8].(string) == "msg", "Logged line did not contain message header")
	assert(t, logEntry[9].(string) == "test", "Logged line did not contain message")
	tearDown()
}

func TestLogVerbosity(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	log.SetVerbosityLevel(2)
	log.V(2).Log("msg", "test")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[4].(string) == "pos", "Logged line did not contain pos")
	assert(t, strings.HasPrefix(logEntry[5].(string), "log_test.go"), "Logged line referenced wrong module")
	tearDown()
}

func TestMsgVerbosity(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	log.SetVerbosityLevel(2)
	log.V(2).msg("test")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[4].(string) == "pos", "Logged line did not contain pos")
	tearDown()
}

func TestMsgfVerbosity(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.SetLogLevel(INFO)
	log.SetVerbosityLevel(2)
	log.V(2).msgf("%s", "test")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[4].(string) == "pos", "Logged line did not contain pos")
	tearDown()
}

func TestErrWithMsgf(t *testing.T) {
	setUp()
	log := MakeLogger(MockLogger{})
	log.Reason(fmt.Errorf("testerror")).msgf("%s", "test")

	logEntry := logParams[0].([]interface{})
	assert(t, logEntry[8].(string) == "reason", "Logged line did not contain message header")
	assert(t, logEntry[9].(error).Error() == "testerror", "Logged line did not contain message header")
	assert(t, logEntry[10].(string) == "msg", "Logged line did not contain message header")
	assert(t, logEntry[11].(string) == "test", "Logged line did not contain message")
	tearDown()
}


text:
using System.Collections;

namespace ThoughtWorks.TreeSurgeon.Core.Generators.Content
{
	public interface ITransformer
	{
		string Transform(string transformName, Hashtable transformParameters);
	}
}


text:
<?php

namespace Derp\Domain\Model;

use Doctrine\ORM\Mapping as ORM;
use DateTime;
use DateInterval;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Embeddable()
 */
class BirthDate
{
    /**
     * @ORM\Column(type="datetime", name="birthDate")
     * @var DateTime
     */
    private $date;

    private function __construct(DateTime $date)
    {
        $this->date = $date;
    }

    public static function fromYearMonthDayFormat($yearMonthDay)
    {
        return new BirthDate(
            DateTime::createFromFormat('Y-m-d H:i:s', $yearMonthDay .' 00:00:00')
        );
    }

    /**
     * @param integer $age
     * @return BirthDate
     */
    public static function fromEstimatedAge($age)
    {
        return new static(
            (new DateTime('now'))->sub(new \DateInterval("P{$age}Y"))
        );
    }

    /**
     * compromise
     */
    public function setDate(DateTime $date)
    {
        $this->date = $date;
    }

    /**
     * compromise
     */
    public function getDate()
    {
        return $this->date;
    }

    public function getCurrentAge()
    {
        $diff = $this->date->diff(new DateTime('now'));
        return $diff->format('Y');
    }

    public function toDateTime()
    {
        return $this->date;
    }
}


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;

class UserUpdate extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required',
            'uuid' => 'required|exists:users,uuid',
            'admin' => 'required'
        ];
    }
}


text:
LICENSE
	cargBags: An inventory framework addon for World of Warcraft

	Copyright (C) 2010  Constantin "Cargor" Schomburg <xconstruct@gmail.com>

	cargBags is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	cargBags is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cargBags; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

DESCRIPTION:
	A few simple item keys, mostly ones resulting through pattern matching
]]

local parent, ns = ...
local cargBags = ns.cargBags

-- Returns the numeric item id (12345)
cargBags.itemKeys["id"] = function(i)
	return i.link and tonumber(i.link:match("item:(%d+)"))
end

--	Returns the type of the parent bag
cargBags.itemKeys["bagType"] = function(i)
	return select(2, GetContainerNumFreeSlots(i.bagID))
end

-- Returns the item string (12345:0:0:0)
cargBags.itemKeys["string"] = function(i)
	return i.link and i.link:match("item:(%d+:%d+:%d+:%d+)")
end

cargBags.itemKeys["stats"] = function(i)
	if(not i.link or not GetItemStats) then return end
	local stats = GetItemStats(i.link)
	i.stats = stats
	return stats
end


text:
package es.udc.lbd.rie.model;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name = "water_source")
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class WaterSource extends WaterNode {

	@Enumerated(EnumType.STRING)
	public SourceType type;

	@Override
	public String toString() {
		return "WaterSource [id=" + id + ", location=" + location + ", type=" + type + "]";
	}

}


text:
      <button class="pure-button" data-ng-bind="lang.forms.all.inputs.view.label"></button>

      <button class="pure-button" data-ng-show="data.step === 'mobileSignUp' || data.step === 'mobileSignUpAuth'" data-ng-bind="lang.forms.all.inputs.reset.label" data-ng-click="reset()"></button>
      <button class="pure-button" data-ng-show="data.step === 'mobileSignUpAuth'" data-ng-bind="lang.forms.all.inputs.resend.label"></button>


text:
#ifndef MXFPP_GENERICDATAESSENCEDESCRIPTOR_BASE_H_
#define MXFPP_GENERICDATAESSENCEDESCRIPTOR_BASE_H_

#include <libMXF++/metadata/FileDescriptor.h>

namespace mxfpp
{

class GenericDataEssenceDescriptorBase : public FileDescriptor
{
public:
    friend class MetadataSetFactory<GenericDataEssenceDescriptorBase>;
    static const mxfKey setKey;

public:
    GenericDataEssenceDescriptorBase(HeaderMetadata *headerMetadata);
    virtual ~GenericDataEssenceDescriptorBase();

   // getters

   bool haveDataEssenceCoding() const;
   mxfUL getDataEssenceCoding() const;

   // setters

   void setDataEssenceCoding(mxfUL value);

protected:
    GenericDataEssenceDescriptorBase(HeaderMetadata *headerMetadata, ::MXFMetadataSet *cMetadataSet);
};

};

#endif


text:
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace FoxTool.Fox.Types.Values
{
    public class FoxUInt8 : IFoxValue
    {
        public byte Value { get; set; }

        public void Read(Stream input)
        {
            BinaryReader reader = new BinaryReader(input, Encoding.Default, true);
            Value = reader.ReadByte();
        }

        public void Write(Stream output)
        {
            BinaryWriter writer = new BinaryWriter(output, Encoding.Default, true);
            writer.Write(Value);
        }

        public int Size()
        {
            return sizeof (byte);
        }

        public void ResolveStringLiterals(FoxLookupTable lookupTable)
        {
        }

        public void CalculateHashes()
        {
        }

        public void CollectStringLookupLiterals(List<FoxStringLookupLiteral> literals)
        {
        }

        public void ReadXml(XmlReader reader)
        {
            var isEmptyElement = reader.IsEmptyElement;
            reader.ReadStartElement("value");
            if (isEmptyElement == false)
            {
                string value = reader.ReadString();
                Value = value.StartsWith("0x")
                    ? byte.Parse(value.Substring(2, value.Length - 2), NumberStyles.AllowHexSpecifier)
                    : byte.Parse(value);
                reader.ReadEndElement();
            }
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteString(ToString());
        }

        public override string ToString()
        {
            return Value.ToString();
        }
    }
}


text:
import json

from sklearn.linear_model import SGDClassifier, SGDRegressor
from mlstorlets.utils.serialize_model import\
    classifier_to_string, classifier_from_string,\
    regressor_to_string, regressor_from_string,\
    serialize_narray
from mlstorlets.utils.swift_access import parse_config,\
    get_auth, invoke_storlet

class SGDProxyBase(object):
    def __init__(self, estimator, config_file):
        self.estimator = estimator
        if isinstance(estimator, SGDClassifier):
            self.type = 'SGDClassifier'
        if isinstance(estimator, SGDRegressor):
            self.type = 'SGDRegressor'

        self.serialize = classifier_to_string\
            if self.type == 'SGDClassifier' else regressor_to_string

        self.deserialize = classifier_from_string\
            if self.type == 'SGDClassifier' else regressor_from_string

        self.conf = None
        if config_file:
            self.conf = parse_config(config_file)

        self.url = self.token = None

    def _remote_command(self, data_url, command,
                        num_features=None, num_labels=None,
                        sample_weight=None,
                        coef_init=None, intercept_init=None):

        if self.conf is None:
            raise Exception('No access config provided')

        if self.token is None:
            self.url, self.token = get_auth(self.conf)

        sest = self.serialize(self.estimator)

        ssample_weight = scoef_init = sintercept_init = None
        if sample_weight:
            ssample_weight = serialize_narray(sample_weight)
        if coef_init:
            scoef_init = serialize_narray(coef_init)
        if intercept_init:
            sintercept_init = serialize_narray(intercept_init)

        try:
            result = invoke_storlet(self.url, self.token,
                                    data_url,
                                    est_type=self.type,
                                    command=command,
                                    est=sest,
                                    num_features=num_features,
                                    num_labels=num_labels,
                                    sample_weight=ssample_weight,
                                    coef_init=scoef_init,
                                    intercept_init=sintercept_init)
        except Exception:
            # TODO: deal with auth exception to retry.
            pass
        return result

    def remote_fit(self, data_url,
                   num_features=None, num_labels=None,
                   coef_init=None, intercept_init=None,
                   sample_weight=None):
        sest = self._remote_command(data_url, 'fit',
                                    num_features, num_labels,
                                    coef_init, intercept_init,
                                    sample_weight)
        self.estimator = self.deserialize(sest)

    def simulate_remote_fit(self, X, y,
                            coef_init=None, intercept_init=None,
                            sample_weight=None):
        # Simulate storlet call:

        # Serialize internal classifier
        sest = self.serialize(self.estimator)

        # Simulate storlet side invocation
        est = self.deserialize(sest)
        est.fit(X, y)
        sest = self.serialize(est)

        # Update intenal state
        self.estimator = self.deserialize(sest)

    def fit(self, X, y, coef_init=None, intercept_init=None,
            sample_weight=None):
        return self.estimator.fit(X, y,
                                  coef_init,
                                  intercept_init,
                                  sample_weight)

    def remote_score(self, data_url,
                     num_features=None, num_labels=None,
                     sample_weight=None):
        result = self._remote_command(data_url, 'score',
                                      num_features, num_labels,
                                      sample_weight)
        return json.loads(result)['score']

    def simulate_remote_score(self, X, y,
                              sample_weight=None):
        # Simulate storlet call:

        # Serialize internal regressor
        sest = self.serialize(self.estimator)

        # Simulate storlet side invocation
        est = self.deserialize(sest)
        score = est.score(X, y, sample_weight)
        # in case a call to score does not change the internal state
        # the below serialization / de-serialization is redundant
        sest = self.serialize(est)

        # Update intenal state
        return score

    def decision_function(self, X):
        return self.estimator.decision_function(X)

    def densify(self):
        return self.estimator.densify()

    def sparsify(self):
        return self.estimator.sparsify()

    def get_params(self, deep=False):
        return self.estimator.get_params(deep)

    def set_params(self, *args, **kwargs):
        return self.estimator.set_params(args, kwargs)

    def predict(self, X):
        return self.estimator.predict(X)

    def score(self, X, y, sample_weight=None):
        return self.estimator.score(X)

    @property
    def coef_(self):
        return self.estimator.coef_

    @property
    def intercept_(self):
        return self.estimator.intercept_

class SGDRegressorProxy(SGDProxyBase):

    def __init__(self, config_file=None,
                 loss="squared_loss", penalty="l2", alpha=0.0001,
                 l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True,
                 verbose=0, epsilon=0.1, random_state=None,
                 learning_rate="invscaling", eta0=0.01, power_t=0.25,
                 warm_start=False, average=False):

        sgdregressor = SGDRegressor(
            loss=loss, penalty=penalty,
            alpha=alpha, l1_ratio=l1_ratio,
            fit_intercept=fit_intercept,
            n_iter=n_iter, shuffle=shuffle,
            verbose=verbose,
            epsilon=epsilon,
            random_state=random_state,
            learning_rate=learning_rate,
            eta0=eta0, power_t=power_t,
            warm_start=False,
            average=average)

        super(SGDRegressorProxy, self).__init__(sgdregressor, config_file)

class SGDClassifierProxy(SGDProxyBase):

    def __init__(self, config_file=None,
                 loss="hinge", penalty="l2", alpha=0.0001,
                 l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True,
                 verbose=0, epsilon=0.1, n_jobs=1, random_state=None,
                 learning_rate="optimal", eta0=0.0, power_t=0.5,
                 class_weight=None, warm_start=False, average=False):

        sgdclassifier = SGDClassifier(
            loss=loss, penalty=penalty,
            alpha=alpha, l1_ratio=l1_ratio,
            fit_intercept=fit_intercept,
            n_iter=n_iter, shuffle=shuffle,
            verbose=verbose,
            epsilon=epsilon,
            n_jobs=n_jobs,
            random_state=random_state,
            learning_rate=learning_rate,
            eta0=eta0, power_t=power_t,
            class_weight=class_weight,
            warm_start=False,
            average=average)

        super(SGDClassifierProxy, self).__init__(sgdclassifier, config_file)


text:
<?php

namespace zamnuts\EANAPIClient\Common;

use zamnuts\EANAPIClient\Util\ObjectBase;

/**
 * @property-read string $cid
 * @property-read string $cidActual
 * @property-read string $apiKey
 * @property-read string $apiSecret
 * @property boolean $isBeta
 * @see http://developer.ean.com/docs/common/
 */
class EANAccount extends ObjectBase {

	/**
	 * @var int
	 */
	const CID_BETA = 55505;

	/**
	 * @var boolean
	 */
	private $isBeta = false;

	/**
	 * @var int
	 */
	private $cid;

	/**
	 * @var string
	 */
	private $apiKey;

	/**
	 * @var string
	 */
	private $apiSecret;

	/**
	 * @param int $cid
	 * @param string $apiKey
	 * @param string $apiSecret
	 * @param boolean $isBeta
	 */
	public function __construct($cid,$apiKey,$apiSecret,$isBeta=false) {
		$this->cid = (int) $cid;
		$this->apiKey = (string) $apiKey;
		$this->apiSecret = (string) $apiSecret;
		$this->isBeta = (boolean) $isBeta;
	}

	/**
	 * @return int
	 */
	protected function get__cid() {
		if ( $this->isBeta ) {
			return (int) self::CID_BETA;
		} else {
			return $this->cid;
		}
	}

	/**
	 * @return int
	 */
	protected function get__cidActual() {
		return $this->cid;
	}

	/**
	 * @return string
	 */
	protected function get__apiKey() {
		return $this->apiKey;
	}

	/**
	 * @return string
	 */
	protected function get__apiSecret() {
		return $this->apiSecret;
	}

	/**
	 * @return boolean
	 */
	protected function get__isBeta() {
		return $this->isBeta;
	}

	/**
	 * @param boolean $value
	 */
	protected function set__isBeta($value) {
		$this->isBeta = (boolean) $value;
	}

	public function generateSignature($timestamp=null) {
		if ( !$timestamp ) {
			$timestamp = time();
		}
		$gmDate = gmdate('U',$timestamp);
		return md5($this->get__apiKey().$this->get__apiSecret().$gmDate);
	}

}


text:
Select container with autocomplete list and `search` method

### Install

```
npm install react-autocomplete-field
```

### Usage

```javascript
import React from 'react';
import {Select, List, ListItem, TextInput} from 'react-autocomplete-field';
import {getCountrySuggestions} from '../../api/ddata-api';

class CountryAutocomplete extends Select {
    renderInput = TextInput;

    renderAutocomplete = List;

    renderAutocompleteItem = ListItem;

    // This will fill `items` property while typing
    search = text => getCountrySuggestions(text).then(({suggestions}) => suggestions);

    // This is for getting values from each suggestion
    getSuggestionValue = item => item.value;
}
export default CountryAutocomplete;
```

*Props*

* `value` - as in usual input
* `onSelect` - fires when value was chosen from list
* `onChange` - fires while value changes, as you type
* `onError` - fires when error was thrown in `search` method

---

- https://gist.github.com/iegik/a23e38a997706b53e54f16e0d6caf9f4


text: export { default } from './koa';


text:
'use strict'

function firstEntityValue (entities, entity) {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value

  if (!val) {
    return null
  }
  return typeof val === 'object' ? val.value : val
}

function formatSearchDatetime (searchDatetime) {
  const d = new Date(searchDatetime)
  const year = d.getFullYear()
  let month = d.getMonth() + 1
  let day = d.getDate()

  month = month > 9 ? month : `0${month}`
  day = day > 9 ? day : `0${day}`

  return `${year}-${month}-${day}`
}

function sanitizePostcode (searchPostcode) {
  return searchPostcode.replace(/\s/g, '')
}

exports.firstEntityValue = firstEntityValue
exports.formatSearchDatetime = formatSearchDatetime
exports.sanitizePostcode = sanitizePostcode


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/CalculatorSkeleton.iml" filepath="$PROJECT_DIR$/.idea/CalculatorSkeleton.iml" />
    </modules>
  </component>
</project>


text:
using appfactum.core;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace appfactum.ui
{
    public static class ComboBoxEx
    {
        /// <summary>
        /// Fill a ComboBox with Items from an enumeration
        /// </summary>
        /// <param name="cmb">Combobox to fill with items</param>
        /// <param name="enumtype">Type of enumeration</param>
        public static void SetEnumeration(this ComboBox cmb,  Type enumtype)
        {
            if (enumtype.IsEnum == false)
                throw new Exception($"Type {enumtype.ToString()} is not an Enumeration.");

            cmb.Properties.Items.Clear();

            foreach (Enum val in Enum.GetValues(enumtype))
            {
                cmb.Properties.Items.Add(new ListItem() { Value = Convert.ToInt32(val), Caption = val.GetEnumDescription() });
            }

            cmb.ValueMember = nameof(ListItem.Value);
        }

        /// <summary>
        /// Entry to fill Combobox- or Listbox- controls
        /// </summary>
        public class ListItem
        {
            public string Caption { get; set; }

            public int Value { get; set; }

            public override string ToString() { return Caption; }
        }
    }
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Post
 *
 * @ORM\Table(name="post", indexes={@ORM\Index(name="admin_id", columns={"admin_id"}),
 * @ORM\Index(name="category_id", columns={"category_id"})})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
 *
 */
class Post {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @Assert\Length(
     *      min = 2,
     *      max = 50,
     *      minMessage = "Naslov mora imati bar {{ limit }} karaktera",
     *      maxMessage = "Naslov ne moze biti duzi od  {{ limit }} karaktera")
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="title", type="string", length=255, nullable=false)
     */
    private $title;

    /**
     * @Assert\Length(
     *      min = 2,
     *      max = 100,
     *      minMessage = "Ključne reči moraju imati bar {{ limit }} karaktera",
     *      maxMessage = "Ključne reči ne mogu imati vise od {{ limit }} karaktera")
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="seo_title", type="string", length=255, nullable=true)
     */
    private $seoTitle;

    /**
     * @Assert\Length(
     *      min = 2,
     *      max = 50,
     *      minMessage = "Vaše ime  mora imati bar {{ limit }} karaktera",
     *      maxMessage = "Vaše ime ne moze biti duze od  {{ limit }} karaktera")
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="author", type="string", length=100, nullable=true)
     */
    private $author = 'admin';

    /**
     * @var \AppBundle\Entity\Admin
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Admin", inversedBy="posts")
     * @ORM\JoinColumn(name="admin_id", referencedColumnName="id", nullable=true)
     */
    private $adminId;

    /**
     * @ORM\Column(type="string",nullable=true)
     *
     * @Assert\NotBlank(message="Molimo unesite PDF ili Word fajl.")
     * @Assert\File(mimeTypes={ "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
     */
    private $body;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime", nullable=false)
     */
    private $created;

    /**
     * @var \AppBundle\Entity\Category
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Category", inversedBy="posts")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     *
     */
    private $category;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string")
     */
    private $status = '0';

    /**
     * @var string
     *
     * @ORM\Column(name="class", type="string")
     */
    private $class;

    /**
     *
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="postId")
     */
    private $comments;

    public function __construct() {
        $this->comments = new ArrayCollection();
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Post
     */
    public function setTitle($title) {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle() {
        return $this->title;
    }

    /**
     * Set seoTitle
     *
     * @param string $seoTitle
     *
     * @return Post
     */
    public function setSeoTitle($seoTitle) {
        $this->seoTitle = $seoTitle;

        return $this;
    }

    /**
     * Get seoTitle
     *
     * @return string
     */
    public function getSeoTitle() {
        return $this->seoTitle;
    }

    /**
     * Set author
     *
     * @param string $author
     *
     * @return Post
     */
    public function setAuthor($author) {
        $this->author = $author;

        return $this;
    }

    /**
     * Get author
     *
     * @return string
     */
    public function getAuthor() {
        return $this->author;
    }

    /**
     * Set adminId
     *
     * @param integer $adminId
     *
     * @return Post
     */
    public function setAdminId($adminId) {
        $this->adminId = $adminId;

        return $this;
    }

    /**
     * Get adminId
     *
     * @return integer
     */
    public function getAdminId() {
        return $this->adminId;
    }

    /**
     * Set body
     *
     * @param string $body
     *
     * @return Post
     */
    public function setBody($body) {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return string
     */
    public function getBody() {
        return $this->body;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return Post
     */
    public function setCreated($created) {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated() {
        return $this->created;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set category
     *
     * @param \AppBundle\Entity\Category $category
     *
     * @return Post
     */
    public function setCategory($category) {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \AppBundle\Entity\Category
     */
    public function getCategory() {
        return $this->category;
    }

    /**
     * Add comment
     *
     * @param \AppBundle\Entity\Comment $comment
     *
     * @return Post
     */
    public function addComment(\AppBundle\Entity\Comment $comment) {
        $this->comments[] = $comment;

        return $this;
    }

    /**
     * Remove comment
     *
     * @param \AppBundle\Entity\Comment $comment
     */
    public function removeComment(\AppBundle\Entity\Comment $comment) {
        $this->comments->removeElement($comment);
    }

    /**
     * Get comments
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComments() {
        return $this->comments;
    }

    public function setStatus($status) {
        $this->status = $status;
        return $this;
    }

    public function getStatus() {
        return $this->status;
    }

    public function __toString() {
        return $this->title;
    }

    public function getClass() {
        return $this->class;
    }

    public function setClass($class) {
        $this->class = $class;
        return $this;
    }

}


text:
<?php

namespace AppBundle\v2\Registration\Assembler;

use AppBundle\Service\DataNormaliser;
use AppBundle\v2\Registration\DTO\LayDeputyshipDto;

class CasRecToLayDeputyshipDtoAssembler implements LayDeputyshipDtoAssemblerInterface
{
    /** @var DataNormaliser */
    private $normaliser;

    /**
     * @param DataNormaliser $normaliser
     */
    public function __construct(DataNormaliser $normaliser)
    {
        $this->normaliser = $normaliser;
    }

    /**
     * @param array $data
     * @return LayDeputyshipDto
     */
    public function assembleFromArray(array $data)
    {
        if (!$this->canAssemble($data)) {
            throw new \InvalidArgumentException('Cannot assemble LayDeputyshipDto: Missing expected data');
        }

        return
            (new LayDeputyshipDto())
            ->setCaseNumber($this->normaliser->normaliseCaseNumber($data['Case']))
            ->setClientSurname($this->normaliser->normaliseSurname($data['Surname']))
            ->setDeputyNumber($this->normaliser->normaliseDeputyNo($data['Deputy No']))
            ->setDeputySurname($this->normaliser->normaliseSurname($data['Dep Surname']))
            ->setDeputyPostcode($this->normaliser->normalisePostCode($data['Dep Postcode']))
            ->setTypeOfReport($data['Typeofrep'])
            ->setCorref($data['Corref'])
            ->setIsNdrEnabled($this->determineNdrStatus($data['NDR']));
    }

    /**
     * @param array $data
     * @return bool
     */
    private function canAssemble(array $data)
    {
        return
            array_key_exists('Case', $data) &&
            array_key_exists('Surname', $data) &&
            array_key_exists('Deputy No', $data) &&
            array_key_exists('Dep Surname', $data) &&
            array_key_exists('Dep Postcode', $data) &&
            array_key_exists('Typeofrep', $data) &&
            array_key_exists('Corref', $data) &&
            array_key_exists('NDR', $data);
    }

    /**
     * @param $value
     * @return bool
     */
    private function determineNdrStatus($value): bool
    {
        return ($value === 1 || $value === 'Y') ? true : false;
    }
}


text:
package org.gradle.internal.operations;

/**
 * Represents some chunk of work.
 */
public interface BuildOperation {
    /**
     * Returns a description of the build operation for visualization purposes.
     */
    BuildOperationDescriptor.Builder description();
}


text:
import { Component } from '@angular/core'

@Component({
    selector: 'entertainment',
    templateUrl: './entertainment.component.html'
})

export class EntertainmentComponent {
}


text:
class KbCategory < ActiveRecord::Base
  unloadable

  self.table_name = "kb_categories"

  validates_presence_of :title

  has_many :articles, :class_name => "KbArticle", :foreign_key => "category_id"

  acts_as_nested_set :order => 'title'

end


text:
var Field = require('../Field');

module.exports = Field.create({
	displayName: 'UrlField'
});


text:
namespace SharpDebug.Drawing.Interfaces
{
    /// <summary>
    /// Interface that tells visualizer that this object can be visualized as a drawing.
    /// </summary>
    public interface IDrawingVisualizerObject
    {
        /// <summary>
        /// Cheks if data is correct and object can be visualized as a drawing.
        /// </summary>
        /// <returns><c>true</c> if data is correct and object can be visualized as a drawing.</returns>
        bool CanVisualize();

        /// <summary>
        /// Creates drawing that should be visualized.
        /// </summary>
        /// <param name="graphics">Graphics object used to create drawings.</param>
        /// <returns>Drawing object that should be visualized.</returns>
        IDrawing CreateDrawing(IGraphics graphics);
    }
}


text:
<?php
namespace frontend\modules\admin\models;

use app\components\Constants;
use yii\base\Model;
use common\models\User;
use Yii;

class UserUpdateForm extends Model
{
    public $firstname;
    public $lastname;
    public $level_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            ['firstname', 'filter', 'filter' => 'trim'],
            ['firstname', 'required'],
            ['firstname', 'string', 'min' => 2, 'max' => 50],

            ['lastname', 'filter', 'filter' => 'trim'],
            ['lastname', 'string', 'min' => 2, 'max' => 50],

            ['level_user', 'integer'],
            ['level_user', 'required'],
            ['level_user', 'in', 'range' => [Constants::KARYAWAN, Constants::IT_SUPPORT, Constants::ADMINISTRASI_IT, Constants::MANAGER_IT] ]
        ];
    }

    /**
     * Update Pasien.
     *
     * @return user|null the saved model or null if saving fails
    */
    public function update($did)
    {

        if ($this->validate()) {
            $update = User::findOne($did);
            $update->firstname = trim(strip_tags($this->firstname));
            $update->lastname = trim(strip_tags($this->lastname));
            $update->level_user = trim(strip_tags($this->level_user));
            if($update->save(false))
            {
               return  array(
                    'firstname'=>$update->firstname,
                    'lastname'=>$update->lastname,
                    'level_user'=>Yii::$app->mycomponent->roleName($update->level_user),
                );
            }
        }

        return null;
    }

    public function updateOf($did)
    {

            $update = User::findOne($did);
            $_status = $update->status;
            $_label = '';
            if($_status == '10')
            {
                $_status = 0;
                $_label = Yii::$app->mycomponent->statusName(0);
            }
            else
            {
                $_status = 10;
                $_label = Yii::$app->mycomponent->statusName(10);
            }
            $update->status = $_status;
            if($update->save(false))
            {
               return  $_label;
            }
    }

	/**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => 'Username',
            'firstname' => 'Firstname',
            'lastname' => 'Lastname',
            'email' => 'Email',
            'password' => 'Password',
        ];
    }

	/**
     * Finds the UserPost model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return UserPost the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package sanduiche.decorator;

import ingrediente.Ingrediente;
import cardapio.ItemCardapio;

public class SanduicheItemCardapio implements ItemCardapio {

	private SanduicheCompravel sanduiche;

	public SanduicheItemCardapio(SanduicheCompravel sanduiche) {
		this.sanduiche = sanduiche;
	}

	@Override
	public String getTitulo() {
		return this.sanduiche.getNome();
	}

	@Override
	public String getDescricao() {
		String descricao = "Ingredientes: ";

		for (Ingrediente ingrediente : sanduiche.getIngredientes()) {
			descricao += ingrediente.toString() + " ";
		}

		return descricao;
	}

	@Override
	public double getValor() {
		double gasto = sanduiche.custoManufatura() + Configuracao.TAXA;
		return gasto + gasto * Configuracao.LUCRO;
	}
}


text:
#import "CC3Layer.h"

/** A sample application-specific CC3Layer subclass. */
@interface PyramidLayer : CC3Layer {
}

@end


text:
import sublime, sublime_plugin
import webbrowser

class RurimaSearchCommand(sublime_plugin.TextCommand):
	def on_done(self, word):
		url = "http://doc.ruby-lang.org/ja/search/query:" + word + "/"
		webbrowser.open_new(url)

	def run(self, edit):
		self.view.window().show_input_panel('Search Rurema: ', '', self.on_done, None, None)


text:
<?php
class Report_ProductController extends Zend_Controller_Action {
	private $activelist = array('មិនប្រើប្រាស់', 'ប្រើប្រាស់');
    public function init()
    {
     /* Initialize action controller here */
    	header('content-type: text/html; charset=utf8');
    	defined('BASE_URL')	|| define('BASE_URL', Zend_Controller_Front::getInstance()->getBaseUrl());
	}
  function indexAction(){
	  $products=new Report_Model_DbTable_DbProduct();
	  if($this->getRequest()->isPost()){
				$search=$this->getRequest()->getPost();
			}
			else{
				$search = array(
						'adv_search' => '',
						'status' => -1,
						'show_all'=>'',
						'category'=>0,
						'start_date'=> date('Y-m-01'),
						'end_date'=>date('Y-m-d')
				);
			}

		$this->view->products_list= $products->getALLProducts($search);
		$fm = new Product_Form_FrmProduct();
		$frm = new Application_Form_FrmAdvanceSearch();
		$frm = $frm->AdvanceSearch();
		Application_Model_Decorator::removeAllDecorator($frm);
		$this->view->frm_search = $frm;

		$fm = new Product_Form_FrmProduct();
		$frm = $fm->FrmProduct();
		Application_Model_Decorator::removeAllDecorator($frm);
		$this->view->frm = $frm;

  }

}