text:
<?php
/*
+--------------------------------------------------------------------------
|   WeCenter [#RELEASE_VERSION#]
|   ========================================
|   by WeCenter Software
|   © 2011 - 2013 WeCenter. All Rights Reserved
|   http://www.wecenter.com
|   ========================================
|   Support: WeCenter@qq.com
|
+---------------------------------------------------------------------------
*/

class core_upload {

	public $max_size				= 0;
	public $max_width				= 0;
	public $max_height				= 0;
	public $max_filename			= 0;
	public $allowed_types			= '';
	public $file_temp				= '';
	public $file_name				= '';
	public $orig_name				= '';
	public $file_type				= '';
	public $file_size				= '';
	public $file_ext				= '';
	public $upload_path				= '';
	public $overwrite				= FALSE;
	public $encrypt_name			= TRUE;
	public $is_image				= FALSE;
	public $image_width				= '';
	public $image_height			= '';
	public $image_type				= '';
	public $image_size_str			= '';
	public $error_code				= false;
	public $mimes					= array();
	public $remove_spaces			= TRUE;
	public $xss_clean				= FALSE;
	public $temp_prefix				= "temp_file_";
	public $client_name				= '';

	protected $_file_name_override	= '';

	// --------------------------------------------------------------------

	/**
	 * Initialize preferences
	 *
	 * @param	array
	 * @return	void
	 */
	public function initialize($config = array())
	{
		$defaults = array(
			'max_size'			=> 0,
			'max_width'			=> 0,
			'max_height'		=> 0,
			'max_filename'		=> 0,
			'allowed_types'		=> '',
			'file_temp'			=> '',
			'file_name'			=> '',
			'orig_name'			=> '',
			'file_type'			=> '',
			'file_size'			=> '',
			'file_ext'			=> '',
			'upload_path'		=> '',
			'overwrite'			=> FALSE,
			'encrypt_name'		=> TRUE,
			'is_image'			=> FALSE,
			'image_width'		=> '',
			'image_height'		=> '',
			'image_type'		=> '',
			'image_size_str'	=> '',
			'error_code'		=> false,
			'mimes'				=> array(),
			'remove_spaces'		=> TRUE,
			'xss_clean'			=> TRUE,
			'temp_prefix'		=> "temp_file_",
			'client_name'		=> ''
		);

		foreach ($defaults as $key => $val)
		{
			if (isset($config[$key]))
			{
				$method = 'set_'.$key;

				if (method_exists($this, $method))
				{
					$this->$method($config[$key]);
				}
				else
				{
					$this->$key = $config[$key];
				}
			}
			else
			{
				$this->$key = $val;
			}
		}

		// if a file_name was provided in the config, use it instead of the user input
		// supplied file name for all uploads until initialized again
		$this->_file_name_override = $this->file_name;

		return $this;
	}

	// --------------------------------------------------------------------

	/**
	 * Perform the file upload
	 *
	 * @return	bool
	 */
	public function do_upload($field = 'userfile', $xhr_stream = false)
	{
		// Is the upload path valid?
		if ( ! $this->validate_upload_path())
		{
			// errors will already be set by validate_upload_path() so just return FALSE
			return FALSE;
		}

		clearstatcache();

		if ($xhr_stream)
		{
			if (!$stream = fopen('php://input', 'r'))
			{
				$this->set_error('upload_no_file_selected');

				return FALSE;
			}

			$tmp_name = TEMP_PATH . 'xhr_' . md5($field . microtime(TRUE) . rand(1, 999));

			if (!$file_size = stream_copy_to_stream($stream, fopen($tmp_name, 'w')))
			{
				$this->set_error('upload_unable_to_write_file');

				return FALSE;
			}

			fclose($stream);

			// Set the uploaded data as class variables
			$this->file_temp = $tmp_name;
			$this->file_size = $file_size;

			$this->file_mime_type(array(
				'tmp_name' => $tmp_name,
				'type' => 'application/octet-stream'
			));

			$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
			$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));

			$this->file_name = $this->prep_filename($field);

			$this->file_ext	 = $this->get_extension($this->file_name);
			$this->client_name = $this->file_name;
		}
		else
		{
			// Is $_FILES[$field] set? If not, no reason to continue.
			if ( ! isset($_FILES[$field]))
			{
				$this->set_error('upload_no_file_selected');
				return FALSE;
			}

			// Was the file able to be uploaded? If not, determine the reason why.
			if ( ! is_uploaded_file($_FILES[$field]['tmp_name']))
			{
				$error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];

				switch($error)
				{
					case 1:	// UPLOAD_ERR_INI_SIZE
						$this->set_error('upload_file_exceeds_limit');
						break;
					case 2: // UPLOAD_ERR_FORM_SIZE
						$this->set_error('upload_file_exceeds_form_limit');
						break;
					case 3: // UPLOAD_ERR_PARTIAL
						$this->set_error('upload_file_partial');
						break;
					case 4: // UPLOAD_ERR_NO_FILE
						$this->set_error('upload_no_file_selected');
						break;
					case 6: // UPLOAD_ERR_NO_TMP_DIR
						$this->set_error('upload_no_temp_directory');
						break;
					case 7: // UPLOAD_ERR_CANT_WRITE
						$this->set_error('upload_unable_to_write_file');
						break;
					case 8: // UPLOAD_ERR_EXTENSION
						$this->set_error('upload_stopped_by_extension');
						break;
					default :   $this->set_error('upload_no_file_selected');
						break;
				}

				return FALSE;
			}

			// Set the uploaded data as class variables
			$this->file_temp = $_FILES[$field]['tmp_name'];
			$this->file_size = $_FILES[$field]['size'];
			$this->file_mime_type($_FILES[$field]);
			$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
			$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));

			$this->file_name = $this->prep_filename($_FILES[$field]['name']);
			$this->file_ext	 = $this->get_extension($this->file_name);
			$this->client_name = $this->file_name;
		}

		// Is the file type allowed to be uploaded?
		if ( ! $this->is_allowed_filetype())
		{
			$this->set_error('upload_invalid_filetype');
			return FALSE;
		}

		// if we're overriding, let's now make sure the new name and type is allowed
		if ($this->_file_name_override != '')
		{
			$this->file_name = $this->prep_filename($this->_file_name_override);

			// If no extension was provided in the file_name config item, use the uploaded one
			if (strpos($this->_file_name_override, '.') === FALSE)
			{
				$this->file_name .= $this->file_ext;
			}

			// An extension was provided, lets have it!
			else
			{
				$this->file_ext	 = $this->get_extension($this->_file_name_override);
			}

			if ( ! $this->is_allowed_filetype(TRUE))
			{
				$this->set_error('upload_invalid_filetype');
				return FALSE;
			}
		}

		// Convert the file size to kilobytes
		if ($this->file_size > 0)
		{
			$this->file_size = round($this->file_size/1024, 2);
		}

		// Is the file size within the allowed maximum?
		if ( ! $this->is_allowed_filesize())
		{
			$this->set_error('upload_invalid_filesize');
			return FALSE;
		}

		// Are the image dimensions within the allowed size?
		// Note: This can fail if the server has an open_basdir restriction.
		if ( ! $this->is_allowed_dimensions())
		{
			$this->set_error('upload_invalid_dimensions');
			return FALSE;
		}

		// Sanitize the file name for security
		$this->file_name = $this->clean_file_name($this->file_name);

		// Truncate the file name if it's too long
		if ($this->max_filename > 0)
		{
			$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
		}

		// Remove white spaces in the name
		if ($this->remove_spaces == TRUE)
		{
			$this->file_name = preg_replace("/\s+/", "_", $this->file_name);
		}

		/*
		 * Validate the file name
		 * This function appends an number onto the end of
		 * the file if one with the same name already exists.
		 * If it returns false there was a problem.
		 */
		$this->orig_name = $this->file_name;

		if ($this->overwrite == FALSE)
		{
			$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
		}

		/*
		 * Run the file through the XSS hacking filter
		 * This helps prevent malicious code from being
		 * embedded within a file.  Scripts can easily
		 * be disguised as images or other file types.
		 */
		if ($this->xss_clean)
		{
			if ($this->do_xss_clean() === FALSE)
			{
				$this->set_error('upload_unable_to_write_file');
				return FALSE;
			}
		}

		if ($xhr_stream)
		{
			/*if ( ! @rename($this->file_temp, $this->upload_path.$this->file_name))
			{
				$this->set_error('upload_destination_error');
				return FALSE;
			}*/

			$file_temp = fopen($this->file_temp, 'r');

			$target = fopen($this->upload_path.$this->file_name, 'w');

			fseek($file_temp, 0, SEEK_SET);

			if (!stream_copy_to_stream($file_temp, $target))
			{
				$this->set_error('upload_destination_error');
				return FALSE;
			}

        	fclose($target);
        	fclose($file_temp);

        	@unlink($this->file_temp);

        	if (!file_exists($this->upload_path.$this->file_name))
			{
				$this->set_error('upload_unable_to_write_file');
				return FALSE;
			}
		}
		else
		{
			/*
			* Move the file to the final destination
			* To deal with different server configurations
			* we'll attempt to use copy() first.  If that fails
			* we'll use move_uploaded_file().  One of the two should
			* reliably work in most environments
			*/

			if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
			{
				if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name))
				{
					$this->set_error('upload_destination_error');
					return FALSE;
				}
			}
		}

		/*
		 * Set the finalized image dimensions
		 * This sets the image width/height (assuming the
		 * file was an image).  We use this information
		 * in the "data" function.
		 */
		$this->set_image_properties($this->upload_path.$this->file_name);

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Finalized Data Array
	 *
	 * Returns an associative array containing all of the information
	 * related to the upload, allowing the developer easy access in one array.
	 *
	 * @return	array
	 */
	public function data()
	{
		if (!file_exists($this->upload_path . $this->file_name))
		{
			return FALSE;
		}

		return array (
						'file_name'			=> $this->file_name,
						'file_type'			=> $this->file_type,
						'file_path'			=> $this->upload_path,
						'full_path'			=> $this->upload_path.$this->file_name,
						'raw_name'			=> str_replace($this->file_ext, '', $this->file_name),
						'orig_name'			=> $this->orig_name,
						'client_name'		=> $this->client_name,
						'file_ext'			=> $this->file_ext,
						'file_size'			=> $this->file_size,
						'is_image'			=> $this->is_image(),
						'image_width'		=> $this->image_width,
						'image_height'		=> $this->image_height,
						'image_type'		=> $this->image_type,
						'image_size_str'	=> $this->image_size_str,
					);
	}

	// --------------------------------------------------------------------

	/**
	 * Set Upload Path
	 *
	 * @param	string
	 * @return	void
	 */
	public function set_upload_path($path)
	{
		// Make sure it has a trailing slash
		$this->upload_path = rtrim($path, '/').'/';
	}

	// --------------------------------------------------------------------

	/**
	 * Set the file name
	 *
	 * This function takes a filename/path as input and looks for the
	 * existence of a file with the same name. If found, it will append a
	 * number to the end of the filename to avoid overwriting a pre-existing file.
	 *
	 * @param	string
	 * @param	string
	 * @return	string
	 */
	public function set_filename($path, $filename)
	{
		if ($this->encrypt_name == TRUE)
		{
			$filename = md5(rand(1, 99999999) . microtime());

			if ( $this->is_image() )
			{
				$filename .= $this->file_ext;
			}

			if ( ! file_exists($path . $filename))
			{
				return $filename;
			}
			else
			{
				return $this->set_filename($path, $filename);
			}
		}

		return $filename;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Maximum File Size
	 *
	 * @param	integer
	 * @return	void
	 */
	public function set_max_filesize($n)
	{
		$this->max_size = ((int) $n < 0) ? 0: (int) $n;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Maximum File Name Length
	 *
	 * @param	integer
	 * @return	void
	 */
	public function set_max_filename($n)
	{
		$this->max_filename = ((int) $n < 0) ? 0: (int) $n;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Maximum Image Width
	 *
	 * @param	integer
	 * @return	void
	 */
	public function set_max_width($n)
	{
		$this->max_width = ((int) $n < 0) ? 0: (int) $n;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Maximum Image Height
	 *
	 * @param	integer
	 * @return	void
	 */
	public function set_max_height($n)
	{
		$this->max_height = ((int) $n < 0) ? 0: (int) $n;
	}

	// --------------------------------------------------------------------

	/**
	 * Set Allowed File Types
	 *
	 * @param	string
	 * @return	void
	 */
	public function set_allowed_types($types)
	{
		if ( ! is_array($types) && $types == '*')
		{
			$this->allowed_types = '*';
			return;
		}

		if (strstr($types, '|'))
		{
			$this->allowed_types = explode('|', $types);
		}
		else
		{
			$this->allowed_types = explode(',', $types);
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Set Image Properties
	 *
	 * Uses GD to determine the width/height/type of image
	 *
	 * @param	string
	 * @return	void
	 */
	public function set_image_properties($path = '')
	{
		if ( ! $this->is_image())
		{
			return;
		}

		if (function_exists('getimagesize'))
		{
			if (FALSE !== ($D = @getimagesize($path)))
			{
				$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');

				$this->image_width		= $D['0'];
				$this->image_height		= $D['1'];
				$this->image_type		= ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
				$this->image_size_str	= $D['3'];  // string containing height and width
			}
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Set XSS Clean
	 *
	 * Enables the XSS flag so that the file that was uploaded
	 * will be run through the XSS filter.
	 *
	 * @param	bool
	 * @return	void
	 */
	public function set_xss_clean($flag = FALSE)
	{
		$this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Validate the image
	 *
	 * @return	bool
	 */
	public function is_image()
	{
		if (!in_array(strtolower($this->file_ext), array(
			'.jpg',
			'.jpe',
			'.jpeg',
			'.bmp',
			'.gif',
			'.png'
		)))
		{
			return FALSE;
		}

		// IE will sometimes return odd mime-types during upload, so here we just standardize all
		// jpegs or pngs to the same file type.

		$png_mimes  = array('image/x-png');
		$jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg');

		if (in_array($this->file_type, $png_mimes))
		{
			$this->file_type = 'image/png';
		}

		if (in_array($this->file_type, $jpeg_mimes))
		{
			$this->file_type = 'image/jpeg';
		}

		$img_mimes = array(
			'image/gif',
			'image/jpeg',
			'image/png',
		);

		return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Verify that the filetype is allowed
	 *
	 * @return	bool
	 */
	public function is_allowed_filetype($ignore_mime = FALSE)
	{
		if ($this->allowed_types == '*')
		{
			return TRUE;
		}

		if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
		{
			$this->set_error('upload_no_file_types');
			return FALSE;
		}

		$ext = strtolower(ltrim($this->file_ext, '.'));

		if ( ! in_array($ext, $this->allowed_types))
		{
			return FALSE;
		}

		// Images get some additional checks
		$image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');

		if (in_array($ext, $image_types))
		{
			if (getimagesize($this->file_temp) === FALSE)
			{
				return FALSE;
			}
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Verify that the file is within the allowed size
	 *
	 * @return	bool
	 */
	public function is_allowed_filesize()
	{
		if ($this->max_size != 0  AND  $this->file_size > $this->max_size)
		{
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Verify that the image is within the allowed width/height
	 *
	 * @return	bool
	 */
	public function is_allowed_dimensions()
	{
		if ( ! $this->is_image())
		{
			return TRUE;
		}

		if (function_exists('getimagesize'))
		{
			$D = @getimagesize($this->file_temp);

			if ($this->max_width > 0 AND $D['0'] > $this->max_width)
			{
				return FALSE;
			}

			if ($this->max_height > 0 AND $D['1'] > $this->max_height)
			{
				return FALSE;
			}

			return TRUE;
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Validate Upload Path
	 *
	 * Verifies that it is a valid upload path with proper permissions.
	 *
	 *
	 * @return	bool
	 */
	public function validate_upload_path()
	{
		if ($this->upload_path == '')
		{
			$this->set_error('upload_no_filepath');
			return FALSE;
		}

		if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE)
		{
			$this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
		}

		if (!defined('IN_SAE'))
		{
			if ( ! is_dir($this->upload_path))
			{
				if (! make_dir($this->upload_path))
				{
					$this->set_error('upload_not_writable');

					return FALSE;
				}
			}

			if ( ! is_really_writable($this->upload_path))
			{
				$this->set_error('upload_not_writable');

				return FALSE;
			}
		}

		$this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/",  $this->upload_path);
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Extract the file extension
	 *
	 * @param	string
	 * @return	string
	 */
	public function get_extension($filename)
	{
		$x = explode('.', $filename);
		return '.'.end($x);
	}

	// --------------------------------------------------------------------

	/**
	 * Clean the file name for security
	 *
	 * @param	string
	 * @return	string
	 */
	public function clean_file_name($filename)
	{
		$bad = array(
						"<!--",
						"-->",
						"'",
						"<",
						">",
						'"',
						'&',
						'$',
						'=',
						';',
						'?',
						'/',
						"%20",
						"%22",
						"%3c",		// <
						"%253c",	// <
						"%3e",		// >
						"%0e",		// >
						"%28",		// (
						"%29",		// )
						"%2528",	// (
						"%26",		// &
						"%24",		// $
						"%3f",		// ?
						"%3b",		// ;
						"%3d"		// =
					);

		$filename = str_replace($bad, '', $filename);

		return stripslashes($filename);
	}

	// --------------------------------------------------------------------

	/**
	 * Limit the File Name Length
	 *
	 * @param	string
	 * @return	string
	 */
	public function limit_filename_length($filename, $length)
	{
		if (strlen($filename) < $length)
		{
			return $filename;
		}

		$ext = '';
		if (strpos($filename, '.') !== FALSE)
		{
			$parts		= explode('.', $filename);
			$ext		= '.'.array_pop($parts);
			$filename	= implode('.', $parts);
		}

		return substr($filename, 0, ($length - strlen($ext))).$ext;
	}

	// --------------------------------------------------------------------

	/**
	 * Runs the file through the XSS clean function
	 *
	 * This prevents people from embedding malicious code in their files.
	 * I'm not sure that it won't negatively affect certain files in unexpected ways,
	 * but so far I haven't found that it causes trouble.
	 *
	 * @return	void
	 */
	public function do_xss_clean()
	{
		$file = $this->file_temp;

		//	部分 IIS 环境下返回值始终为 0
		//if (filesize($file) == 0)
		if ($this->file_size == 0)
		{
			return FALSE;
		}

		if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '')
		{
			$current = ini_get('memory_limit') * 1024 * 1024;

			// There was a bug/behavioural change in PHP 5.2, where numbers over one million get output
			// into scientific notation.  number_format() ensures this number is an integer
			// http://bugs.php.net/bug.php?id=43053

			$new_memory = number_format(ceil(filesize($file) + $current), 0, '.', '');

			@ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net
		}

		// If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but
		// IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
		// using IE who looks at the image.  It does this by inspecting the first 255 bytes of an image.  To get around this
		// CI will itself look at the first 255 bytes of an image to determine its relative safety.  This can save a lot of
		// processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
		// attempted XSS attack.

		if (function_exists('getimagesize') && @getimagesize($file) !== FALSE)
		{
			if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary
			{
				return FALSE; // Couldn't open the file, return FALSE
			}

			$opening_bytes = fread($file, 256);
			fclose($file);

			// These are known to throw IE into mime-type detection chaos
			// <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title
			// title is basically just in SVG, but we filter it anyhow

			if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes))
			{
				return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good
			}
			else
			{
				return FALSE;
			}
		}

		if (($data = @file_get_contents($file)) === FALSE)
		{
			return FALSE;
		}

		return $data;
	}

	// --------------------------------------------------------------------

	/**
	 * Set an error message
	 *
	 * @param	string
	 * @return	void
	 */
	public function set_error($code)
	{
		$this->error_code = $code;
	}

	/**
	 * Get an error message
	 *
	 * @return	array
	 */
	public function get_error()
	{
		if ($this->error_code)
		{
			@unlink($this->file_temp);
		}

		return $this->error_code;
	}

	// --------------------------------------------------------------------

	/**
	 * Prep Filename
	 *
	 * Prevents possible script execution from Apache's handling of files multiple extensions
	 * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext
	 *
	 * @param	string
	 * @return	string
	 */
	protected function prep_filename($filename)
	{
		if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*')
		{
			return $filename;
		}

		$parts		= explode('.', $filename);
		$ext		= array_pop($parts);
		$filename	= array_shift($parts);

		foreach ($parts as $part)
		{
			if ( ! in_array(strtolower($part), $this->allowed_types))
			{
				$filename .= '.'.$part.'_';
			}
			else
			{
				$filename .= '.'.$part;
			}
		}

		$filename .= '.'.$ext;

		return $filename;
	}

	// --------------------------------------------------------------------

	/**
	 * File MIME type
	 *
	 * Detects the (actual) MIME type of the uploaded file, if possible.
	 * The input array is expected to be $_FILES[$field]
	 *
	 * @param	array
	 * @return	void
	 */
	protected function file_mime_type($file)
	{
		// We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
		$regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';

		/* Fileinfo extension - most reliable method
		 *
		 * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the
		 * more convenient FILEINFO_MIME_TYPE flag doesn't exist.
		 */
		if (function_exists('finfo_file'))
		{
			$finfo = finfo_open(FILEINFO_MIME);
			if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system
			{
				$mime = @finfo_file($finfo, $file['tmp_name']);
				finfo_close($finfo);

				/* According to the comments section of the PHP manual page,
				 * it is possible that this function returns an empty string
				 * for some files (e.g. if they don't exist in the magic MIME database)
				 */
				if (is_string($mime) && preg_match($regexp, $mime, $matches))
				{
					$this->file_type = $matches[1];
					return;
				}
			}
		}

		/* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
		 * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
		 * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
		 * than mime_content_type() as well, hence the attempts to try calling the command line with
		 * three different functions.
		 *
		 * Notes:
		 *	- the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
		 *	- many system admins would disable the exec(), shell_exec(), popen() and similar functions
		 *	  due to security concerns, hence the function_exists() checks
		 */
		if (DIRECTORY_SEPARATOR !== '\\')
		{
			$cmd = 'file --brief --mime ' . @escapeshellarg($file['tmp_name']) . ' 2>&1';

			if (function_exists('exec'))
			{
				/* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
				 * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites
				 * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
				 * value, which is only put to allow us to get the return status code.
				 */
				$mime = @exec($cmd, $mime, $return_status);
				if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
				{
					$this->file_type = $matches[1];
					return;
				}
			}

			if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec'))
			{
				$mime = @shell_exec($cmd);
				if (strlen($mime) > 0)
				{
					$mime = explode("\n", trim($mime));
					if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
					{
						$this->file_type = $matches[1];
						return;
					}
				}
			}

			if (function_exists('popen'))
			{
				$proc = @popen($cmd, 'r');
				if (is_resource($proc))
				{
					$mime = @fread($proc, 512);
					@pclose($proc);
					if ($mime !== FALSE)
					{
						$mime = explode("\n", trim($mime));
						if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
						{
							$this->file_type = $matches[1];
							return;
						}
					}
				}
			}
		}

		// Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type'])
		if (function_exists('mime_content_type'))
		{
			$this->file_type = @mime_content_type($file['tmp_name']);
			if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
			{
				return;
			}
		}

		if (function_exists('getimagesize'))
		{
			$imageinfo = @getimagesize($file['tmp_name']);

			if ($imageinfo['mime'])
			{
				$this->file_type = $imageinfo['mime'];

				return;
			}
		}

		$this->file_type = $file['type'];
	}

	// --------------------------------------------------------------------

}


text:
<?php declare(strict_types=1);

namespace PetrKnap\Doctrine\NamingStrategies\Orm\Mapping;

use PetrKnap\Doctrine\NamingStrategies\Orm\Mapping\Exception\ClassNotSupportedException;

class UnderscoreNamingStrategy extends \Doctrine\ORM\Mapping\UnderscoreNamingStrategy
{
    private $prefix;
    private $allowedRootClasses;

    public function __construct($case = CASE_LOWER, bool $numberAware = false, string $prefix = null, array $allowedRootClasses = [])
    {
        parent::__construct($case, $numberAware);

        $this->prefix = $prefix;
        $this->allowedRootClasses = $allowedRootClasses;
    }

    /**
     * @inheritDoc
     */
    public function classToTableName($className)
    {
        if ($this->prefix) {
            $prefixWithSlash = "{$this->prefix}\\";
            if (strpos($className, $prefixWithSlash) !== 0) {
                if (strpos($className, '\\') === false && in_array($className, $this->allowedRootClasses)) {
                    return parent::classToTableName($className);
                } else {
                    throw ClassNotSupportedException::create(
                        $className,
                        'missing prefix "' . $this->prefix . '" and not listed in allowed root classes [' . implode(', ', $this->allowedRootClasses). ']'
                    );
                }
            }
            $className = substr($className, strlen($prefixWithSlash));
        }

        $partialNames = explode('\\', $className);

        return implode('__', array_map(function (string $partialName) {
            return parent::classToTableName($partialName);
        }, $partialNames));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intel.analytics.bigdl.dllib.feature.dataset

import java.nio.ByteBuffer
import java.nio.file.{Files, Path, Paths}
import java.util.concurrent.atomic.AtomicInteger

import com.intel.analytics.bigdl.DataSet
import com.intel.analytics.bigdl.dllib.feature.dataset.image.{LabeledBGRImage, _}
import com.intel.analytics.bigdl.dllib.feature.dataset.segmentation.{COCODataset, COCODeserializer}
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.feature.transform.vision.image.label.roi.RoiLabel
import com.intel.analytics.bigdl.dllib.feature.transform.vision.image.{DistributedImageFrame, ImageFeature, ImageFrame, LocalImageFrame, RoiImageInfo}
import com.intel.analytics.bigdl.dllib.utils.{Engine, Log4Error, RandomGenerator, T}
import java.awt.Color
import java.awt.image.{BufferedImage, DataBufferByte}
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO

import org.apache.hadoop.io.{BytesWritable, Text}
import org.apache.logging.log4j.LogManager
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD

import scala.reflect._

/**
 * A set of data which is used in the model optimization process. The dataset can be access in
 * a random data sample sequence. In the training process, the data sequence is a looped endless
 * sequence. While in the validation process, the data sequence is a limited length sequence.
 * User can use the data() method to get the data sequence.
 *
 * The sequence of the data is not fixed. It can be changed by the shuffle() method.
 *
 * User can create a dataset from a RDD, an array and a folder, etc. The DataSet object provides
 * many factory methods.
 *
 * @tparam D Data type
 * @tparam DataSequence Represent a sequence of data
 */
trait AbstractDataSet[D, DataSequence] {
  /**
   * Get a sequence of data
   *
   * @param train if the data is used in train. If yes, the data sequence is a looped endless
   *              sequence, or it has a limited length.
   * @return data sequence
   */
  def data(train: Boolean): DataSequence

  /**
   * Change the order of the data sequence from the data set
   */
  def shuffle(): Unit

  /**
   * Total size of the data set
   * @return
   */
  def size(): Long

  /**
   * Helper function to transform the data type in the data set.
   * @param transformer
   * @tparam C
   * @return
   */
  def transform[C: ClassTag](transformer: Transformer[D, C]): DataSet[C]

  // scalastyle:off methodName
  // scalastyle:off noSpaceBeforeLeftBracket
  /**
   * Helper function to transform the data type in the data set.
   *
   * @param transformer
   * @tparam C
   * @return
   */
  def -> [C: ClassTag](transformer: Transformer[D, C]): DataSet[C] = {
    this.transform(transformer)
  }

  // scalastyle:on noSpaceBeforeLeftBracket
  // scalastyle:on methodName

  /**
   * Convert current DataSet to a local DataSet, in which we use an iterator to represent the
   * data sequence.
   * @return
   */
  def toLocal(): LocalDataSet[D] = this.asInstanceOf[LocalDataSet[D]]

  /**
   * Convert current DataSet to a distributed DataSet, in which we use a RDD to represent the
   * data sequence.
   * @return
   */
  def toDistributed(): DistributedDataSet[D] = this.asInstanceOf[DistributedDataSet[D]]
}

/**
 * Manage some 'local' data, e.g. data in files or memory. We use iterator to go through the data.
 * @tparam T
 */
trait LocalDataSet[T] extends AbstractDataSet[T, Iterator[T]] {
  override def transform[C: ClassTag](transformer: Transformer[T, C]): DataSet[C] = {
    val preDataSet = this
    new LocalDataSet[C] {
      override def shuffle(): Unit = preDataSet.shuffle

      override def size(): Long = preDataSet.size()

      override def data(train: Boolean): Iterator[C] = transformer(preDataSet.data(train))
    }
  }
}

/**
 * Wrap an array as a DataSet.
 * @param buffer
 * @tparam T
 */
class LocalArrayDataSet[T] private[dataset](buffer: Array[T]) extends LocalDataSet[T] {
  override def shuffle(): Unit = {
    RandomGenerator.shuffle(buffer)
  }

  override def data(train: Boolean): Iterator[T] = {
    new Iterator[T] {
      private val index = new AtomicInteger()

      override def hasNext: Boolean = {
        if (train) {
          true
        } else {
          index.get() < buffer.length
        }
      }

      override def next(): T = {
        val curIndex = index.getAndIncrement()
        if (train || curIndex < buffer.length) {
          buffer(if (train) (curIndex % buffer.length) else curIndex)
        } else {
          null.asInstanceOf[T]
        }
      }
    }
  }

  override def size(): Long = buffer.length
}

/**
 * Represent a distributed data. Use RDD to go through all data.
 *
 * @tparam T
 */
trait DistributedDataSet[T] extends AbstractDataSet[T, RDD[T]] {

  override def transform[C: ClassTag](transformer: Transformer[T, C]): DataSet[C] = {
    val preDataSet = this

    val broadcast = this.originRDD().sparkContext.broadcast(transformer)

    val cachedTransformer =
      preDataSet.originRDD().mapPartitions(_ => Iterator
        .single(broadcast.value.cloneTransformer())
      ).setName("Cached Transformer").persist()

    new DistributedDataSet[C] {
      override def size(): Long = preDataSet.size()

      override def shuffle(): Unit = preDataSet.shuffle()

      override def data(train: Boolean): RDD[C] =
        preDataSet.data(train).zipPartitions(cachedTransformer)(
          (data, tran) => tran.next()(data))

      override def originRDD(): RDD[_] = preDataSet.originRDD()

      override def cache(): Unit = {
        cachedTransformer.count()
        isCached = true
      }

      override def unpersist(): Unit = {
        cachedTransformer.unpersist()
        isCached = false
      }
    }
  }

  /**
   * Get the 'origin' RDD of the dataset.
   *
   * @return
   */
  def originRDD(): RDD[_]

  /**
   * Trigger the computation of this dataset and cache it in memory.
   */
  def cache(): Unit = {
    if (originRDD() != null) {
      originRDD().count()
    }
    isCached = true
  }

  /**
   * Unpersist rdd.
   */
  def unpersist(): Unit = {
    if (originRDD() != null) {
      originRDD().unpersist()
      isCached = false
    }
  }

  /**
   * Check if rdd is cached.
   */
  var isCached = false
}

/**
 * Wrap a RDD as a DataSet.
 * @param buffer
 * @param isInOrder whether need keeping original data order, default false
 * @param groupSize offset range, from 0 until buffer.length - groupSize + 1,
 *                  only use when need keep original order
 * @tparam T
 */
class CachedDistriDataSet[T: ClassTag] private[dataset]
(buffer: RDD[Array[T]], isInOrder: Boolean = false, groupSize: Int = 1)
  extends DistributedDataSet[T] {

  protected lazy val count: Long = buffer.mapPartitions(iter => {
    Log4Error.unKnowExceptionError(iter.hasNext, "unexpect empty iterator")
    val array = iter.next()
//    require(!iter.hasNext)
    Log4Error.unKnowExceptionError(!iter.hasNext, "expect only 1 element in the iterator")
    Iterator.single(array.length)
  }).reduce(_ + _)

  protected var indexes: RDD[Array[Int]] = buffer.mapPartitions(iter => {
    Iterator.single((0 until iter.next().length).toArray)
  }).setName("original index").cache()

  override def data(train: Boolean): RDD[T] = {
    val _train = train
    val _groupSize = if (isInOrder) Utils.getBatchSize(groupSize) else 1
    buffer.zipPartitions(indexes)((dataIter, indexIter) => {
      val indexes = indexIter.next()
      val indexOffset = math.max(1, indexes.length - (_groupSize - 1))
      val localData = dataIter.next()
      val offset = if (_train) {
        RandomGenerator.RNG.uniform(0, indexOffset).toInt
      } else {
        0
      }
      new Iterator[T] {
        private val _offset = new AtomicInteger(offset)

        override def hasNext: Boolean = {
          if (_train) true else _offset.get() < localData.length
        }

        override def next(): T = {
          val i = _offset.getAndIncrement()
          if (_train) {
            Log4Error.invalidOperationError(localData.length != 0,
              "dataset on this executor is empty, please increase " +
                "your dataset size or decrease your number of executors.")
            localData(indexes(i % localData.length))
          } else {
            if (i < localData.length) {
              localData(indexes(i))
            } else {
              null.asInstanceOf[T]
            }
          }
        }
      }
    })
  }

  override def size(): Long = count

  override def shuffle(): Unit = {
    if (!isInOrder) {
      indexes.unpersist()
      indexes = buffer.mapPartitions(iter => {
        Iterator.single(RandomGenerator.shuffle((0 until iter.next().length).toArray))
      }).setName("shuffled index").cache()
    }
  }

  override def originRDD(): RDD[_] = buffer

  override def cache(): Unit = {
    buffer.count()
    indexes.count()
    isCached = true
  }

  override def unpersist(): Unit = {
    buffer.unpersist()
    indexes.unpersist()
    isCached = false
  }
}

/**
 * Common used DataSet builder.
 */
object DataSet {
  val logger = LogManager.getLogger(getClass)

  /**
   * Wrap an array as a DataSet.
   */
  def array[T](data: Array[T]): LocalArrayDataSet[T] = {
    new LocalArrayDataSet[T](data)
  }

  /**
   * Wrap an array as a distributed DataSet.
   * @param localData
   * @param sc
   * @tparam T
   * @return
   */
  def array[T: ClassTag](localData: Array[T], sc: SparkContext): DistributedDataSet[T] = {
    val nodeNumber = Engine.nodeNumber()
    new CachedDistriDataSet[T](
      sc.parallelize(localData, nodeNumber)
        // Keep this line, or the array will be send to worker every time
        .coalesce(nodeNumber, true)
        .mapPartitions(iter => {
          Iterator.single(iter.toArray)
        }).setName("cached dataset")
        .cache()
    )
  }

  /**
   * Wrap a RDD as a DataSet.
   * @param data
   * @param partitionNum repartition data rdd to partition number, default node number.
   * @param shuffleData whether shuffle the data, default true.
   * @param groupSize offset range, only use when shuffleData is false
   * @tparam T
   * @return
   */
  def rdd[T: ClassTag](data: RDD[T], partitionNum: Int = Engine.nodeNumber(),
    shuffleData: Boolean = true, groupSize: Int = 1
    ): DistributedDataSet[T] = {
    new CachedDistriDataSet[T](
      data.coalesce(partitionNum, true)
        .mapPartitions(iter => {
          Iterator.single(iter.toArray)
        }).setName("cached dataset")
        .cache()
      , !shuffleData, groupSize)
  }

  def imageFrame(imageFrame: ImageFrame): DataSet[ImageFeature] = {
    imageFrame match {
      case distributedImageFrame: DistributedImageFrame =>
        rdd[ImageFeature](distributedImageFrame.rdd)
      case localImageFrame: LocalImageFrame =>
        array(localImageFrame.array)
    }
  }

  /**
   * Wrap a RDD as a DataSet.
   * @param data
   * @tparam T
   * @return
   */
  private[bigdl] def sortRDD[T: ClassTag](data: RDD[T], isInOrder: Boolean = false,
                                          groupSize: Int = 1): DistributedDataSet[T] = {
    val nodeNumber = Engine.nodeNumber()
    new CachedDistriDataSet[T](
      data.coalesce(nodeNumber, true)
        .mapPartitions(iter => {
          Iterator.single(sortData(iter.toArray, isInOrder))
        }).setName("cached dataset")
        .cache(),
      isInOrder,
      groupSize
    )
  }

  /**
   * sort data from small to big, only support Sample data type.
   * @param data original data
   * @param isInOrder whether to sort data by ascending order
   * @return
   */
  def sortData[T: ClassTag](data: Array[T], isInOrder: Boolean): Array[T] = {
    if (isInOrder) {
      Log4Error.invalidOperationError(classTag[T] == classTag[Sample[_]],
        "DataSet.sortData: Only support sort for sample input")
      data.sortBy(a => a.asInstanceOf[Sample[_]].featureLength(0))
    } else {
      data
    }
  }

  /**
   * Generate a DataSet from a local image folder. The image folder should have two levels. The
   * first level is class folders, and the second level is images. All images belong to a same
   * class should be put into the same class folder. So each image in the path is labeled by the
   * folder it belongs.
   */
  object ImageFolder {
    /**
     * Extract all image paths into a Local DataSet. The paths are all labeled. When the image
     * files are too large(e.g. ImageNet2012 data set), you'd better readd all paths instead of
     * image files themselves.
     * @param path
     * @return
     */
    def paths(path: Path): LocalDataSet[LocalLabeledImagePath] = {
      val buffer = LocalImageFiles.readPaths(path)
      new LocalArrayDataSet[LocalLabeledImagePath](buffer)
    }

    /**
     * Extract all images under the given path into a Local DataSet. The images are all labeled.
     * @param path
     * @param scaleTo
     * @return
     */
    def images(path: Path, scaleTo: Int): DataSet[LabeledBGRImage] = {
      val paths = LocalImageFiles.readPaths(path)
      val total = paths.length
      var count = 1
      val buffer = paths.map(imageFile => {
        if (total < 100 || count % (total / 100) == 0 || count == total) {
          logger.info(s"Cache image $count/$total(${count * 100 / total}%)")
        }
        count += 1

        val bufferBGR = new LabeledBGRImage()
        bufferBGR.copy(BGRImage.readImage(imageFile.path, scaleTo), 255f)
          .setLabel(imageFile.label)
      })

      new LocalArrayDataSet[LabeledBGRImage](buffer)
    }

    /**
     * Extract all images under the given path into a Distributed DataSet. The images are all
     * labeled.
     * @param path
     * @param sc
     * @param scaleTo
     * @return
     */
    def images(path: Path, sc: SparkContext, scaleTo: Int)
    : DataSet[LabeledBGRImage] = {
      val paths = LocalImageFiles.readPaths(path)
      val buffer: Array[LabeledBGRImage] = {
        paths.map(imageFile => {
          val bufferBGR = new LabeledBGRImage()
          bufferBGR.copy(BGRImage.readImage(imageFile.path, scaleTo), 255f)
            .setLabel(imageFile.label)
        })
      }
      array(buffer, sc)
    }
  }

  /**
   * Create a DataSet from a Hadoop sequence file folder.
   */
  object SeqFileFolder {
    val logger = LogManager.getLogger(getClass)

    /**
     * Extract all hadoop sequence file paths from a local file folder.
     * @param path
     * @param totalSize
     * @return
     */
    def paths(path: Path, totalSize: Long): LocalDataSet[LocalSeqFilePath] = {
      logger.info(s"Read sequence files folder $path")
      val buffer: Array[LocalSeqFilePath] = findFiles(path)
      logger.info(s"Find ${buffer.length} sequence files")
      Log4Error.invalidInputError(buffer.length > 0, s"Can't find any sequence" +
        s" files under $path")
      new LocalArrayDataSet[LocalSeqFilePath](buffer) {
        override def size(): Long = {
          totalSize
        }
      }
    }

    /**
     * get label from text of sequence file,
     * @param data text of sequence file, this text can split into parts by "\n"
     * @return
     */
    def readLabel(data: Text): String = {
      val dataArr = data.toString.split("\n")
      if (dataArr.length == 1) {
        dataArr(0)
      } else {
        dataArr(1)
      }
    }

    /**
     * get name from text of sequence file,
     * @param data text of sequence file, this text can split into parts by "\n"
     * @return
     */
    def readName(data: Text): String = {
      val dataArr = data.toString.split("\n")
      Log4Error.invalidInputError(dataArr.length >= 2,
        "key in seq file only contains label, no name")
      dataArr(0)
    }

    /**
     * Extract hadoop sequence files from an HDFS path
     * @param url
     * @param sc
     * @param classNum
     * @return
     */
    def files(url: String, sc: SparkContext, classNum: Int): DistributedDataSet[ByteRecord] = {
      val nodeNumber = Engine.nodeNumber()
      val coreNumber = Engine.coreNumber()
      val rawData = sc.sequenceFile(url, classOf[Text], classOf[Text],
        nodeNumber * coreNumber).map(image => {
        ByteRecord(image._2.copyBytes(), readLabel(image._1).toFloat)
      }).filter(_.label <= classNum)

      rdd[ByteRecord](rawData)
    }

    /**
     * Extract hadoop sequence files from an HDFS path as RDD
     * @param url sequence files folder path
     * @param sc spark context
     * @param classNum class number of data
     * @param partitionNum partition number, default: Engine.nodeNumber() * Engine.coreNumber()
     * @return
     */
    private[bigdl] def filesToRdd(url: String, sc: SparkContext,
      classNum: Int, partitionNum: Option[Int] = None): RDD[ByteRecord] = {
      val num = partitionNum.getOrElse(Engine.nodeNumber() * Engine.coreNumber())
      val rawData = sc.sequenceFile(url, classOf[Text], classOf[Text], num).map(image => {
        ByteRecord(image._2.copyBytes(), readLabel(image._1).toFloat)
      }).filter(_.label <= classNum)
      rawData.coalesce(num, true)
    }

    /**
     * Extract hadoop sequence files from an HDFS path as ImageFrame
     * @param url sequence files folder path
     * @param sc spark context
     * @param classNum class number of data
     * @param partitionNum partition number, default: Engine.nodeNumber() * Engine.coreNumber()
     * @return
     */
    private[bigdl] def filesToImageFrame(url: String, sc: SparkContext,
      classNum: Int, partitionNum: Option[Int] = None): ImageFrame = {
      val num = partitionNum.getOrElse(Engine.nodeNumber() * Engine.coreNumber())
      val rawData = sc.sequenceFile(url, classOf[Text], classOf[Text], num).map(image => {
        val rawBytes = image._2.copyBytes()
        val label = Tensor[Float](T(readLabel(image._1).toFloat))
        val imgBuffer = ByteBuffer.wrap(rawBytes)
        val width = imgBuffer.getInt
        val height = imgBuffer.getInt
        val bytes = new Array[Byte](3 * width * height)
        System.arraycopy(imgBuffer.array(), 8, bytes, 0, bytes.length)
        val imf = ImageFeature(bytes, label)
        imf(ImageFeature.originalSize) = (height, width, 3)
        imf
      }).filter(_[Tensor[Float]](ImageFeature.label).valueAt(1) <= classNum)
      ImageFrame.rdd(rawData)
    }

    private def isSingleChannelImage(image: BufferedImage): Boolean = {
      if (image.getType == BufferedImage.TYPE_BYTE_GRAY) return true
      if (image.getType == BufferedImage.TYPE_USHORT_GRAY) return true
      if (image.getRaster.getNumBands == 1) return true
      false
    }

    /**
     * Decode raw bytes read from an image file into decoded bytes. If the file is 1 channel grey
     * scale image, automatically convert to 3 channels
     * @param in the input raw image bytes
     * @return the decoded 3 channel bytes in BGR order
     */
    private[bigdl] def decodeRawImageToBGR(in: Array[Byte]) : Array[Byte] = {
      val inputStream = new ByteArrayInputStream(in)
      val image = {
        val img = ImageIO.read(inputStream)
        if (isSingleChannelImage(img)) {
          val imageBuff: BufferedImage =
            new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR)
          imageBuff.getGraphics.drawImage(img, 0, 0, new Color(0, 0, 0), null)
          imageBuff
        } else {
          img
        }
      }
      image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData()
    }

    /**
     * Extract hadoop sequence files from an HDFS path as ImageFeatures
     * @param url sequence files folder path
     * @param sc spark context
     * @param partitionNum partition number, default: Engine.nodeNumber() * Engine.coreNumber()
     * @return
     */
    private[bigdl] def filesToRoiImageFeatures(url: String, sc: SparkContext,
      partitionNum: Option[Int] = None): DataSet[ImageFeature] = {
      val num = partitionNum.getOrElse(Engine.nodeNumber() * Engine.coreNumber())
      val rawData = sc.sequenceFile(url, classOf[BytesWritable], classOf[BytesWritable], num)
        .map { data =>
          val metaBytes = new COCODeserializer(ByteBuffer.wrap(data._1.getBytes))
          val fileName = metaBytes.getString
          val (height, width, anno) = metaBytes.getAnnotations

          val labelClasses = Tensor(anno.map(_.categoryIdx.toFloat), Array(anno.length))
          val bboxes = Tensor(
            anno.toIterator.flatMap(ann => {
              val x1 = ann.bbox1
              val y1 = ann.bbox2
              val x2 = ann.bbox3
              val y2 = ann.bbox4
              Iterator(x1, y1, x2, y2)
            }).toArray,
            Array(anno.length, 4))
          val isCrowd = Tensor(anno.map(ann => if (ann.isCrowd) 1f else 0f), Array(anno.length))
          val masks = anno.map(ann => ann.masks)
          Log4Error.invalidInputError(metaBytes.getInt == COCODataset.MAGIC_NUM,
            "Corrupted metadata")

          val rawdata = decodeRawImageToBGR(data._2.getBytes)
          Log4Error.invalidInputError(rawdata.length == height * width * 3,
          s"The image doesn't match the metadata. There are ${rawdata.length} bytes" +
            s" while the height * width * 3 is ${height} * ${width} * 3")
          val imf = ImageFeature(rawdata, RoiLabel(labelClasses, bboxes, masks), fileName)
          imf(ImageFeature.originalSize) = (height, width, 3)
          imf(RoiImageInfo.ISCROWD) = isCrowd
          imf
        }
        .coalesce(num)
     DataSet.rdd(rawData, num)
    }

    private[bigdl] def filesToImageFeatureDataset(url: String, sc: SparkContext,
      classNum: Int, partitionNum: Option[Int] = None): DistributedDataSet[ImageFeature] = {
      rdd[ImageFeature](filesToImageFrame(url, sc, classNum, partitionNum).toDistributed().rdd)
    }

    private[bigdl] def findFiles(path: Path): Array[LocalSeqFilePath] = {
      val directoryStream = Files.newDirectoryStream(path)
      import scala.collection.JavaConverters._
      directoryStream.asScala.map(_.toAbsolutePath.toString)
        .filter(_.endsWith(".seq")).toArray.sortWith(_ < _).map(p => LocalSeqFilePath(Paths.get(p)))
    }
  }

}


text:
  - Added to all incident types
##### First Name
  - Added to all incident types
##### Last Name
  - Added to all incident types.
##### Phone Number
  - Added to all incident types.
##### Mobile Device Model
  - Added to all incident types.
##### Device Hash
  - Added to all incident types.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        ">

    <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
	<dubbo:application name="hai-adm-shopmng" owner="linpn" />

	<!-- 注册中心 -->
	<dubbo:registry address="${dubbo.registry.address}" file="${user.dir}/.dubbo/dubbo-registry-hai-adm-shopmng-consumer.cache" />

	<!-- 服务消费方缺省配置 -->
	<dubbo:consumer timeout="10000" check="false" />

	<!-- ===============================消费hai-srv-shopping服务============================== -->

	<!-- 商品 -->
	<dubbo:reference id="productService" interface="com.haiegoo.shopping.service.product.ProductService" version="1.0" url="dubbo://127.0.0.1:22880"/> <!-- url="dubbo://127.0.0.1:22880" -->

	<!-- 品牌 -->
	<dubbo:reference id="brandService" interface="com.haiegoo.shopping.service.product.BrandService" version="1.0" url="dubbo://127.0.0.1:22880"/>

	<!-- 分类 -->
	<dubbo:reference id="categoryService" interface="com.haiegoo.shopping.service.product.CategoryService" version="1.0" url="dubbo://127.0.0.1:22880"/>

	<!-- 规格 -->
	<dubbo:reference id="specificationService" interface="com.haiegoo.shopping.service.product.SpecificationService" version="1.0" url="dubbo://127.0.0.1:22880"/>

	<!-- 属性 -->
	<dubbo:reference id="propertyService" interface="com.haiegoo.shopping.service.product.PropertyService" version="1.0" url="dubbo://127.0.0.1:22880"/>

	<!-- ===============================消费hai-srv-ucenter服务============================== -->

	<!-- 后台用户 -->
	<dubbo:reference id="adminService" interface="com.haiegoo.ucenter.service.admin.AdminService" version="1.0" /> <!-- url="dubbo://127.0.0.1:21880" -->

	<!-- 角色权限 -->
	<dubbo:reference id="roleService" interface="com.haiegoo.ucenter.service.admin.RoleService" version="1.0" />

	<!-- 应用模块-->
	<dubbo:reference id="moduleService" interface="com.haiegoo.ucenter.service.admin.ModuleService" version="1.0" />

	<!-- 前台用户 -->
	<dubbo:reference id="userService" interface="com.haiegoo.ucenter.service.user.UserService" version="1.0" />

	<!-- 行政区划 -->
	<dubbo:reference id="cityService" interface="com.haiegoo.ucenter.service.user.CityService" version="1.0" />

	<!-- ===============================消费hai-srv-commons服务============================== -->

	<!-- 系统与参数 -->
	<dubbo:reference id="enumsService" interface="com.haiegoo.commons.service.config.EnumsService" version="1.0" /> <!-- url="dubbo://127.0.0.1:20880" -->

</beans>


text:
.class Lcom/android/internal/policy/impl/sec/TickerScrollView$7;
.super Ljava/lang/Object;
.source "TickerScrollView.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/policy/impl/sec/TickerScrollView;->createMessage(Landroid/content/Context;Ljava/lang/String;Lcom/android/internal/policy/impl/sec/TickerUtil$TickerStatus;)Landroid/widget/FrameLayout;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/policy/impl/sec/TickerScrollView;

# direct methods
.method constructor <init>(Lcom/android/internal/policy/impl/sec/TickerScrollView;)V
    .locals 0
    .parameter

    .prologue
    .line 298
    iput-object p1, p0, Lcom/android/internal/policy/impl/sec/TickerScrollView$7;->this$0:Lcom/android/internal/policy/impl/sec/TickerScrollView;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 2
    .parameter "v"

    .prologue
    .line 301
    invoke-static {}, Lcom/android/internal/policy/impl/sec/SamsungLockScreenProperties;->isSinaEnable()Z

    move-result v1

    if-eqz v1, :cond_0

    .line 302
    new-instance v0, Landroid/content/Intent;

    const-string v1, "com.sec.android.app.sns3.sinaweibo.SSOSetupAccount"

    invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    .line 303
    .local v0, intent:Landroid/content/Intent;
    iget-object v1, p0, Lcom/android/internal/policy/impl/sec/TickerScrollView$7;->this$0:Lcom/android/internal/policy/impl/sec/TickerScrollView;

    #getter for: Lcom/android/internal/policy/impl/sec/TickerScrollView;->mContext:Landroid/content/Context;
    invoke-static {v1}, Lcom/android/internal/policy/impl/sec/TickerScrollView;->access$000(Lcom/android/internal/policy/impl/sec/TickerScrollView;)Landroid/content/Context;

    move-result-object v1

    invoke-virtual {v1, v0}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V

    .line 308
    .end local v0           #intent:Landroid/content/Intent;
    :goto_0
    iget-object v1, p0, Lcom/android/internal/policy/impl/sec/TickerScrollView$7;->this$0:Lcom/android/internal/policy/impl/sec/TickerScrollView;

    #getter for: Lcom/android/internal/policy/impl/sec/TickerScrollView;->mTickerCallback:Lcom/android/internal/policy/impl/sec/TickerCallback;
    invoke-static {v1}, Lcom/android/internal/policy/impl/sec/TickerScrollView;->access$200(Lcom/android/internal/policy/impl/sec/TickerScrollView;)Lcom/android/internal/policy/impl/sec/TickerCallback;

    move-result-object v1

    invoke-interface {v1}, Lcom/android/internal/policy/impl/sec/TickerCallback;->goToUnlockScreen()V

    .line 309
    return-void

    .line 305
    :cond_0
    iget-object v1, p0, Lcom/android/internal/policy/impl/sec/TickerScrollView$7;->this$0:Lcom/android/internal/policy/impl/sec/TickerScrollView;

    iget-object v1, v1, Lcom/android/internal/policy/impl/sec/TickerScrollView;->mAccountThread:Lcom/android/internal/policy/impl/sec/TickerScrollView$AccountThread;

    invoke-virtual {v1}, Lcom/android/internal/policy/impl/sec/TickerScrollView$AccountThread;->start()V

    goto :goto_0
.end method


text:
$API_KEY = "***********************************"

# Direct URL of source PDF file.
$SourceFileURL = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-split/sample.pdf"
# PDF document password. Leave empty for unprotected documents.
$Password = ""
# Destination PDF file name
$DestinationFile = ".\result.pdf"

# Prepare URL for `Replace Text With Image from PDF` API call
$query = "https://localhost/pdf/edit/replace-text-with-image"

# Prepare request body (will be auto-converted to JSON by Invoke-RestMethod)
# See documentation: https://apidocs.pdf.co
$body = @{
    "name" = $(Split-Path $DestinationFile -Leaf)
    "password" = $Password
    "url" = $SourceFileURL
    "searchString" = "/creativecommons.org/licenses/by-sa/3.0/"
    "replaceImage" = "https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/image-to-pdf/image1.png"
} | ConvertTo-Json

try {
    # Execute request
    $response = Invoke-WebRequest -Method Post -Headers @{ "x-api-key" = $API_KEY; "Content-Type" = "application/json" } -Body $body -Uri $query

    $jsonResponse = $response.Content | ConvertFrom-Json

    if ($jsonResponse.error -eq $false) {
        # Get URL of generated PDF file
        $resultFileUrl = $jsonResponse.url;

        # Download PDF file
        Invoke-WebRequest -Headers @{ "x-api-key" = $API_KEY } -OutFile $DestinationFile -Uri $resultFileUrl

        Write-Host "Generated PDF file saved as `"$($DestinationFile)`" file."
    }
    else {
        # Display service reported error
        Write-Host $jsonResponse.message
    }
}
catch {
    # Display request error
    Write-Host $_.Exception
}


text:
System.register(["aurelia-framework", "aurelia-logging", "../util"], function (exports_1, context_1) {
    "use strict";
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var __moduleName = context_1 && context_1.id;
    var aurelia_framework_1, aurelia_logging_1, util, MdcGlidList;
    return {
        setters: [
            function (aurelia_framework_1_1) {
                aurelia_framework_1 = aurelia_framework_1_1;
            },
            function (aurelia_logging_1_1) {
                aurelia_logging_1 = aurelia_logging_1_1;
            },
            function (util_1) {
                util = util_1;
            }
        ],
        execute: function () {
            MdcGlidList = (function () {
                function MdcGlidList(element) {
                    this.element = element;
                    this.headerTop = false;
                    this.twoLine = false;
                    this.iconStart = false;
                    this.iconEnd = false;
                    this.aspect = '1x1';
                    this.gutter = '4';
                    this.log = aurelia_logging_1.getLogger('mdc-grid-list');
                }
                MdcGlidList.prototype.bind = function () { };
                MdcGlidList.prototype.unbind = function () { };
                MdcGlidList.prototype.attached = function () {
                    this.headerTopChanged(this.headerTop);
                    this.twoLineChanged(this.twoLine);
                    this.iconStartChanged(this.iconStart);
                    this.iconEndChanged(this.iconEnd);
                    this.aspectChanged(this.aspect);
                    this.gutterChanged(this.gutter);
                };
                MdcGlidList.prototype.widthChanged = function (newValue) {
                };
                MdcGlidList.prototype.headerTopChanged = function (newValue) {
                    var value = util.getBoolean(newValue);
                    this.elementGridlist.classList[value ? 'add' : 'remove']('mdc-grid-list--header-caption');
                };
                MdcGlidList.prototype.twoLineChanged = function (newValue) {
                    var value = util.getBoolean(newValue);
                    this.elementGridlist.classList[value ? 'add' : 'remove']('mdc-grid-list--twoline-caption');
                };
                MdcGlidList.prototype.iconStartChanged = function (newValue) {
                    var value = util.getBoolean(newValue);
                    this.elementGridlist.classList[value ? 'add' : 'remove']('mdc-grid-list--with-icon-align-start');
                };
                MdcGlidList.prototype.iconEndChanged = function (newValue) {
                    var value = util.getBoolean(newValue);
                    this.elementGridlist.classList[value ? 'add' : 'remove']('mdc-grid-list--with-icon-align-end');
                };
                MdcGlidList.prototype.aspectChanged = function (newValue) {
                    var _this = this;
                    var allowed = ['1x1', '16x9', '2x3', '3x2', '4x3', '3x4'];
                    if (allowed.indexOf(newValue) === -1) {
                        this.log.error('aspect has to be one of following values:', allowed);
                        return;
                    }
                    allowed.forEach(function (x) {
                        _this.elementGridlist.classList.remove('mdc-grid-list--tile-aspect-' + x);
                    });
                    this.elementGridlist.classList.add('mdc-grid-list--tile-aspect-' + newValue);
                };
                MdcGlidList.prototype.gutterChanged = function (newValue) {
                    this.elementGridlist.className = this.elementGridlist.className.replace(/\bmdc-grid-list--tile-gutter-\b\d+/g, '');
                    if (newValue === '4') {
                        return;
                    }
                    this.elementGridlist.classList.add('mdc-grid-list--tile-gutter-' + newValue);
                };
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", Object)
                ], MdcGlidList.prototype, "headerTop", void 0);
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", Object)
                ], MdcGlidList.prototype, "twoLine", void 0);
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", Object)
                ], MdcGlidList.prototype, "iconStart", void 0);
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", Object)
                ], MdcGlidList.prototype, "iconEnd", void 0);
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", String)
                ], MdcGlidList.prototype, "aspect", void 0);
                __decorate([
                    aurelia_framework_1.bindable(),
                    __metadata("design:type", Object)
                ], MdcGlidList.prototype, "gutter", void 0);
                MdcGlidList = __decorate([
                    aurelia_framework_1.customElement('mdc-grid-list'),
                    aurelia_framework_1.inject(Element),
                    __metadata("design:paramtypes", [Element])
                ], MdcGlidList);
                return MdcGlidList;
            }());
            exports_1("MdcGlidList", MdcGlidList);
        }
    };
});


text:
import generateUtilityClass from '../generateUtilityClass';
import generateUtilityClasses from '../generateUtilityClasses';

export interface TabPanelUnstyledClasses {
  root: string;
  hidden: string;
}

export type TabPanelUnstyledClassKey = keyof TabPanelUnstyledClasses;

export function getTabPanelUnstyledUtilityClass(slot: string): string {
  return generateUtilityClass('MuiTabPanel', slot);
}

const tabPanelUnstyledClasses: TabPanelUnstyledClasses = generateUtilityClasses('MuiTabPanel', [
  'root',
  'hidden',
]);

export default tabPanelUnstyledClasses;


text:
Add it to your dependencies
```
dependencies:
  route_provider: ^4.4.1
```

and install the package
```
$ pub get
```

## Usage
```dart in html
import 'dart:io';
import 'package:route_provider/route_provider.dart';
main() {
    Auth freeForAll = StaticAuth(authed: true);
    Auth userAuth = MyAuth();
    Responser jsonResponser = JsonResponse();
    HttpServer.bind(InternetAddress.anyIPv4,8080).then((HttpServer server){
        Router(server)
        ..route(
            url: '/',
            responser: FileResponse('docroot/index.html'),
            auth: freeForAll
        )
        ..route(
            url: '/assets/**',
            responser: FolderResponse('docroot/assets/'),
            auth: freeForAll
        )
        ..route(
            url: '/impress',
            responser: FileResponse('docroot/impress.html'),
            auth: freeForAll
        )
        ..route(
            url: '/api/data/:id',
            controller: DataRestApiController(),
            responser: jsonResponser,
            auth: userAuth
        )
        ..start();
    }).catchError((e) => print(e.toString()));
}
```

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request

## Credits

Robert Beyer <4sternrb@googlemail.com>

## License

MIT


text:
package web

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestMaxBodyBytesHandler_Pass(t *testing.T) {
	h := MaxBodyBytesHandler{
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			_, _ = w.Write([]byte("ok"))
		}),
	}
	r := httptest.NewRequest("POST", "/", nil)
	w := httptest.NewRecorder()

	h.ServeHTTP(w, r)

	if w.Body.String() != "ok" {
		t.Errorf("expected response body %q, got %q", "ok", w.Body.String())
	}
}

func TestMaxBodyBytesHandler_Block(t *testing.T) {
	h := MaxBodyBytesHandler{
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if _, err := io.Copy(ioutil.Discard, r.Body); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				_, _ = w.Write([]byte(err.Error()))
			}
		}),
		Limit: 10,
		BodyFunc: func(r *http.Request) (body string, err error) {
			return http.StatusText(http.StatusRequestEntityTooLarge), nil
		},
		ContentType: "text/plain",
	}
	r := httptest.NewRequest("POST", "/", bytes.NewReader([]byte("12345678901")))
	w := httptest.NewRecorder()

	h.ServeHTTP(w, r)

	b, err := ioutil.ReadAll(w.Result().Body)
	if err != nil {
		t.Error(err)
	}

	if string(b) != http.StatusText(http.StatusRequestEntityTooLarge)+"\n" {
		t.Errorf("expected response body %q, got %q", http.StatusText(http.StatusRequestEntityTooLarge)+"\n", string(b))
	}

	contentType := w.Result().Header.Get("Content-Type")
	if contentType != "text/plain" {
		t.Errorf("expected response Content-Type header %q, got %q", "text/plain", contentType)
	}
}

func TestMaxBodyBytesHandler_PanicError(t *testing.T) {
	h := MaxBodyBytesHandler{
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if _, err := io.Copy(ioutil.Discard, r.Body); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				_, _ = w.Write([]byte(err.Error()))
			}
		}),
		Limit: 10,
		BodyFunc: func(r *http.Request) (body string, err error) {
			return "", errTestMaxBodyBytesHandler
		},
	}
	defer func() {
		if err := recover(); err != errTestMaxBodyBytesHandler {
			t.Errorf("expected %v error, got %v", errTestMaxBodyBytesHandler, err)
		}
	}()

	r := httptest.NewRequest("POST", "/", bytes.NewReader([]byte("12345678901")))
	w := httptest.NewRecorder()

	h.ServeHTTP(w, r)
}

var errTestMaxBodyBytesHandler = errors.New("test")

func TestMaxBodyBytesHandler_CustomError(t *testing.T) {
	var e error
	h := MaxBodyBytesHandler{
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if _, err := io.Copy(ioutil.Discard, r.Body); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				_, _ = w.Write([]byte(err.Error()))
			}
		}),
		Limit: 10,
		BodyFunc: func(r *http.Request) (body string, err error) {
			return "", errTestMaxBodyBytesHandler
		},
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			e = err
		},
	}
	r := httptest.NewRequest("POST", "/", bytes.NewReader([]byte("12345678901")))
	w := httptest.NewRecorder()

	h.ServeHTTP(w, r)

	if e != errTestMaxBodyBytesHandler {
		t.Errorf("expected %v error, got %v", errTestMaxBodyBytesHandler, e)
	}
}


text:
#ifndef AVCODEC_LCL_H
#define AVCODEC_LCL_H

#define BMPTYPE_YUV 1
#define BMPTYPE_RGB 2

#define IMGTYPE_YUV111 0
#define IMGTYPE_YUV422 1
#define IMGTYPE_RGB24 2
#define IMGTYPE_YUV411 3
#define IMGTYPE_YUV211 4
#define IMGTYPE_YUV420 5

#define COMP_MSZH 0
#define COMP_MSZH_NOCOMP 1
#define COMP_ZLIB_HISPEED 1
#define COMP_ZLIB_HICOMP 9
#define COMP_ZLIB_NORMAL -1

#define FLAG_MULTITHREAD 1
#define FLAG_NULLFRAME 2
#define FLAG_PNGFILTER 4
#define FLAGMASK_UNUSED 0xf8

#define CODEC_MSZH 1
#define CODEC_ZLIB 3

#endif /* AVCODEC_LCL_H */


text:
package player

import (
	"encoding/json"
	"fmt"
	"github.com/krig/go-sox"
	"goji.io"
	"goji.io/pat"
	"golang.org/x/net/context"
	"net/http"
	"os"
	"strings"
	"sync"
)

// Success and error codes
const (
	success = iota
	failure
)

// Messages
const no_sox_in_msg string = "SoX failed to open input file"
const no_sox_out_msg string = "Sox failed to open output device"
const file_not_found_msg string = "File cannot be found"
const playlist_not_found_msg string = "Playlist cannot be found"
const no_playlists_msg string = "Currently there are no saved playlists"
const format_not_supported_msg string = "Format is not supported"
const cannot_pause_msg string = "Cannot pause. No song is playing"
const cannot_resume_msg = "Cannot resume. No song was paused"
const cannot_next_msg = "Cannot play next song. No next song in queue"
const cannot_previous_msg = "Cannot play previous song. No previous song in queue"
const cannot_get_info_msg = "There is no current song in the queue"
const cannot_save_playlist_msg = "Cannot save playlist"
const cannot_save_empty_queue_msg = "Queue is empty and cannot be saved as playlist"
const cannot_get_queue_info_msg = "Cannot get queue info. Queue is empty"
const cannot_jump_to_song_msg = "Song not available"

const started_playing_info = "Started playing"
const added_to_queue_info = "Added to queue"
const paused_song_info = "Song is paused"
const resume_song_info = "Song is resumed"
const playback_stopped_info = "Playback is stopped and cleaned"
const current_song_info = "The filename of the current song"
const current_queue_info = "The filenames in the current queue"
const queue_saved_as_playlist = "The queue is saved as a playlist"
const playlists_info = "A list of all saved playlists"
const queue_info = "Queue content"

// ResponseContainer defines the format of the web service's response
// It contains code - 0 for success and 1 for error, message that explains actions is performed
// and data which is a list of file names
type ResponseContainer struct {
	// 0 for success, 1 for failure
	Code int
	// Error message or Info message
	Message string
	// Filename (list if filenames)
	Data []string `json:"Data,omitempty"`
}

// writeHttpResponse writes response
func writeHttpResponse(w http.ResponseWriter, container ResponseContainer) {
	message, err1 := json.Marshal(container)
	if err1 != nil {
		http.Error(w, err1.Error(), http.StatusInternalServerError)
	} else {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.WriteHeader(http.StatusOK)
		if message != nil {
			w.Write(message)
		}
	}
}

// getResponseContainer wraps data and error in ResponseContainer
func getResponseContainer(data []string, err error) ResponseContainer {
	container := ResponseContainer{}
	if err != nil {
		container.Code = failure
		container.Message = err.Error()
	} else {
		container.Code = success
		container.Data = data
	}

	return container
}

// alive shows if the service is alive
func alive(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "I'm alive")
}

// playerToServiceResponse constructs the response in the format of the service and writes it
func playerToServiceResponse(w http.ResponseWriter, data []string, err error, successMessage string) {
	container := getResponseContainer(filterPath(data), err)
	if err == nil {
		container.Message = successMessage
	}
	writeHttpResponse(w, container)
}

// filterPath removes the path from list of filenames. Only the part after the last slash remains
func filterPath(data []string) []string {
	filtered := make([]string, 0, len(data))
	for _, element := range data {
		lastSlashIndex := strings.LastIndex(element, "/")
		filtered = append(filtered, element[lastSlashIndex+1:])
	}
	return filtered
}

// Starts playing a file, files from directory or a playlist immediately - current queue is cleared
// The result json contains the names of the files to be played
// or error message if song is not found, format is unsupported or SoX cannot play the file
func play(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	name := pat.Param(ctx, "name")
	data, err := player.play(name)
	playerToServiceResponse(w, data, err, started_playing_info)
}

// Pauses the current song
// The result json contains the filename of the paused song
// or error message if no song is playing at the moment
func pause(w http.ResponseWriter, r *http.Request) {
	data, err := player.pause()
	playerToServiceResponse(w, []string{data}, err, paused_song_info)
}

// Resumes paused song
// The result json contains the filename of the running song
// or error message if no song was paused
func resume(w http.ResponseWriter, r *http.Request) {
	data, err := player.resume()
	playerToServiceResponse(w, []string{data}, err, resume_song_info)
}

// Stops the playback - playing queue is cleared i.e. playback cannot be resumed
// The result json contains message that playback is stopped
func stop(w http.ResponseWriter, r *http.Request) {
	player.stop()
	playerToServiceResponse(w, []string{}, nil, playback_stopped_info)
}

// Starts playing the next from the queue
// Skips playing the current song (if not paused)
// The result json contains the filename of the running song
// or error message if there is no next song
func next(w http.ResponseWriter, r *http.Request) {
	data, err := player.next()
	playerToServiceResponse(w, []string{data}, err, started_playing_info)
}

// Starts playing the previous from the queue
// Skips playing the current song (if not paused)
// The result json contains the filename of the running song
// or error message if there is no previous song
func previous(w http.ResponseWriter, r *http.Request) {
	data, err := player.previous()
	playerToServiceResponse(w, []string{data}, err, started_playing_info)
}

// Gets the filename of the current song
// The result json contains the filename of the running song
// or error message if no song is playing at the moment
func getCurrentSongInfo(w http.ResponseWriter, r *http.Request) {
	data, err := player.getCurrentSongInfo()
	playerToServiceResponse(w, []string{data}, err, current_song_info)
}

// Add a song, directory or playlist to the play queue - songs will be played after all others in the queue
// Will play the song if there is no songs in the queue
// The result json contains the filename of the added song, directory or playlist
// or error message if song is not found, format is unsupported or Sox cannot play the file
func addToQueue(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	filename := pat.Param(ctx, "name")
	data, err := player.addToQueue(filename)
	playerToServiceResponse(w, data, err, added_to_queue_info)
}

// saveAsPlaylist saves the current queue as a playlist
// The result json contains the filename of the playlist
// or error message if queue is empty or playlist cannot be saved
func saveAsPlaylist(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	name := pat.Param(ctx, "name")
	data, err := player.saveAsPlaylist(name)
	playerToServiceResponse(w, []string{data}, err, queue_saved_as_playlist)
}

// listPlaylists list the saved playlists
// The result json contains the filenames of the already saved playlists
// or error message of no playlists exit
func listPlaylists(w http.ResponseWriter, r *http.Request) {
	data, err := player.listPlaylists()
	playerToServiceResponse(w, data, err, playlists_info)
}

// getQueueInfo Displays all songs in the queue
// The result json contains all filenames in the current queue
// or an error message if queue is empty
func getQueueInfo(w http.ResponseWriter, r *http.Request) {
	data, err := player.getQueueInfo()
	playerToServiceResponse(w, data, err, queue_info)
}

var player musicPlayer

func servePage(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "secret/secret.html")
}

func serveCss(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "secret/css/music_player.css")
}

func serveJs(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "secret/script/music_player.js")
}

func jump(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	number := pat.Param(ctx, "number")
	data, err := player.jump(number)
	playerToServiceResponse(w, []string{data}, err, started_playing_info)
}

func getPlaylistDir() string {
	wd, err := os.Getwd()
	playlistsDir := ""
	if err == nil && strings.HasSuffix(wd, "music_player") {
		playlistsDir = "player/playlists/"
	} else {
		playlistsDir = "playlists/"
	}
	return playlistsDir
}

//InitService creates a mux and initializes handle functions for music_player
func InitService(playlistDir string) *goji.Mux {
	player = musicPlayer{playQueueMutex: &sync.Mutex{}}
	player.init(playlistDir)

	// service handle functions
	mux := goji.NewMux()
	mux.HandleFunc(pat.Get("/"), alive)
	mux.HandleFuncC(pat.Put("/play/:name"), play)
	mux.HandleFunc(pat.Post("/pause"), pause)
	mux.HandleFunc(pat.Post("/resume"), resume)
	mux.HandleFunc(pat.Put("/stop"), stop)
	mux.HandleFunc(pat.Post("/next"), next)
	mux.HandleFunc(pat.Post("/previous"), previous)
	mux.HandleFunc(pat.Get("/songinfo"), getCurrentSongInfo)
	mux.HandleFuncC(pat.Post("/add/:name"), addToQueue)
	mux.HandleFuncC(pat.Put("/save/:name"), saveAsPlaylist)
	mux.HandleFunc(pat.Get("/playlists"), listPlaylists)
	mux.HandleFunc(pat.Get("/queueinfo"), getQueueInfo)
	mux.HandleFunc(pat.Get("/secret"), servePage)
	mux.HandleFunc(pat.Get("/css/music_player.css"), serveCss)
	mux.HandleFunc(pat.Get("/script/music_player.js"), serveJs)
	mux.HandleFuncC(pat.Post("/jump/:number"), jump)

	return mux
}

// WaitEnd is used to wait the end of the playing the songs in the play queue
func WaitEnd() {
	player.waitEnd()
}

// Start starts the music_player web service
func Start() {
	// init the player
	mux := InitService(getPlaylistDir())
	// init sox
	if !sox.Init() {
		fmt.Println("sox is not found")
		return
	}
	// clean up
	defer sox.Quit()
	// start the service
	http.ListenAndServe(":8765", mux)
}


text:
soba
====

Simple OS Bootloader for ARM


text:
@interface SettingWindowController ()

#pragma mark - IBOutlet
@property (weak) IBOutlet NSTextField *textField_apiKey;
@property (weak) IBOutlet NSTextField *textField_keyfrom;
@property (weak) IBOutlet NSButton *buttonOpenUrl;
@property (weak) IBOutlet NSButton *button_enableTranslate;
@property (weak) IBOutlet NSComboBox *comboBoxmodel;

#pragma mark - Action

// 是否开启有道翻译
- (IBAction)actionBeginTranslate:(NSButton *)sender;

// 打开有道API开发平台网站
- (IBAction)actionOpenUrlBaiDuApi:(NSButton *)sender;

// 设置更新APIKEY,有道翻译API非收费,每小时/1000次!
- (IBAction)actionUpdatApiKey:(NSButton *)sender;

// 设置翻译的模式 - 百度网页或是有道网页
- (IBAction)actionSelectTranslation:(NSComboBox *)sender;

@end

@implementation SettingWindowController

- (void)windowDidLoad {
    [super windowDidLoad];
    uDefaults = [NSUserDefaults standardUserDefaults];
    // 1.设置是否开启翻译
    if ([uDefaults objectForKey:KEYENABLETRANSLATE] == nil || [[uDefaults objectForKey:KEYENABLETRANSLATE] isEqualToString:@"0"]) {
        [_button_enableTranslate setState:0];
        _comboBoxmodel.hidden = YES;
        _buttonOpenUrl.hidden = YES;
    }
    else {
        [_button_enableTranslate setState:1];
        _comboBoxmodel.hidden = NO;
        _buttonOpenUrl.hidden = NO;
    }
    // 2.检测是否有APIkey 和 keyfrom
    if ([uDefaults objectForKey:KEYAPI] == nil) {
        [_textField_apiKey setStringValue:@""];
    }
    else {
        [_textField_apiKey setStringValue:[uDefaults objectForKey:KEYAPI]];
    }

    if ([uDefaults objectForKey:KEYFROM] == nil) {
        [_textField_keyfrom setStringValue:@""];
    }
    else {
        [_textField_keyfrom setStringValue:[uDefaults objectForKey:KEYFROM]];
    }

    // 3.设置翻译模式 默认为SDK查询方式
    if ([uDefaults objectForKey:KEYAPIMODEL] == nil) {
        [uDefaults setObject:@"0" forKey:KEYAPIMODEL];
        [_comboBoxmodel selectItemAtIndex:0];
    }
    else if ([[uDefaults objectForKey:KEYAPIMODEL] isEqualToString:@"1"]) {
        [_comboBoxmodel selectItemAtIndex:1];
    }
    else {
        [_comboBoxmodel selectItemAtIndex:[uDefaults integerForKey:KEYAPIMODEL]];
    }
}

- (IBAction)actionBeginTranslate:(NSButton *)sender {
    if ([uDefaults objectForKey:KEYENABLETRANSLATE] == nil || [[uDefaults objectForKey:KEYENABLETRANSLATE] isEqualToString:@"0"]) {
        [uDefaults setObject:@"1" forKey:KEYENABLETRANSLATE];
        [_button_enableTranslate setState:1];
        [_comboBoxmodel setHidden:NO];
        [_buttonOpenUrl setHidden:NO];
    }
    else {
        [uDefaults setObject:@"0" forKey:KEYENABLETRANSLATE];
        [_button_enableTranslate setState:0];
        [_comboBoxmodel setHidden:YES];
        [_buttonOpenUrl setHidden:YES];
    }
}

- (IBAction)actionOpenUrlBaiDuApi:(NSButton *)sender {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://fanyi.youdao.com/openapi?path=data-mode"]];
}

- (IBAction)actionUpdatApiKey:(NSButton *)sender {
    if ([[_textField_apiKey stringValue] isEqualToString:@""] || [[_textField_keyfrom stringValue] isEqualToString:@""]) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"您的信息填写不正确!"];
        [alert runModal];
        return;
    }
    [uDefaults setObject:[_textField_apiKey stringValue] forKey:KEYAPI];
    [uDefaults setObject:[_textField_keyfrom stringValue] forKey:KEYFROM];
}

- (IBAction)actionSelectTranslation:(NSComboBox *)sender {
    if ([sender indexOfSelectedItem] == 0) {
        [uDefaults setObject:@"0" forKey:KEYAPIMODEL];
    }
    else if ([sender indexOfSelectedItem] == 1) {
        [uDefaults setObject:@"1" forKey:KEYAPIMODEL];
    }
    else if ([sender indexOfSelectedItem] == 2) {
        [uDefaults setObject:@"2" forKey:KEYAPIMODEL];
    }
}
@end


text:
package filesystem

import (
	"os"
	"syscall"

	"golang.org/x/sys/windows"
)

func umask(mask int) int {
	return 0
}

func addReadMode(mode os.FileMode) os.FileMode {
	return mode | syscall.S_IRUSR
}

func getFreeSpace(path string) (uint64, error) {
	wpath, err := windows.UTF16PtrFromString(path)
	if err != nil {
		return 0, err
	}
	var freeBytes uint64
	if err := windows.GetDiskFreeSpaceEx(wpath, nil, nil, &freeBytes); err != nil {
		return 0, err
	}
	return freeBytes, nil
}


text:
<!DOCTYPE html>
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="svg.css" />
	</head>
	<body>
		<svg></svg>
		<button id="hardwareButton">Click for hardware!</button>

		<script type="text/javascript" src="bundle.js"></script>
	</body>
</html>


text:
package com.googlecode.flickrjandroid.photosets.comments;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.googlecode.flickrjandroid.FlickrException;
import com.googlecode.flickrjandroid.Parameter;
import com.googlecode.flickrjandroid.Response;
import com.googlecode.flickrjandroid.Transport;
import com.googlecode.flickrjandroid.oauth.OAuthInterface;
import com.googlecode.flickrjandroid.oauth.OAuthUtils;
import com.googlecode.flickrjandroid.photos.comments.Comment;

/**
 * Access to the <b>flickr.photosets.comments</b> methods.
 *
 * @author till (Till Krech) flickr:extranoise
 * @version $Id: PhotosetsCommentsInterface.java,v 1.3 2009/07/11 20:30:27 x-mago Exp $
 */
public class PhotosetsCommentsInterface {
    public static final String METHOD_ADD_COMMENT = "flickr.photosets.comments.addComment";
    public static final String METHOD_DELETE_COMMENT = "flickr.photosets.comments.deleteComment";
    public static final String METHOD_EDIT_COMMENT = "flickr.photosets.comments.editComment";
    public static final String METHOD_GET_LIST = "flickr.photosets.comments.getList";

    private String apiKey;
    private String sharedSecret;
    private Transport transportAPI;

    public PhotosetsCommentsInterface(
        String apiKey,
        String sharedSecret,
        Transport transport
    ) {
        this.apiKey = apiKey;
        this.sharedSecret = sharedSecret;
        this.transportAPI = transport;
    }

    /**
     * Add a comment to a photoset.
     * This method requires authentication with 'write' permission.
     * @param photosetId The id of the photoset to add a comment to.
     * @param commentText Text of the comment
     * @return the comment id
     * @throws FlickrException
     * @throws IOException
     * @throws JSONException
     */
    public String addComment(String photosetId, String commentText) throws FlickrException, IOException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_ADD_COMMENT));
        parameters.add(new Parameter(OAuthInterface.PARAM_OAUTH_CONSUMER_KEY, apiKey));

        parameters.add(new Parameter("photoset_id", photosetId));
        parameters.add(new Parameter("comment_text", commentText));
        OAuthUtils.addOAuthToken(parameters);

        // Note: This method requires an HTTP POST request.
        Response response = transportAPI.postJSON(sharedSecret, parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        return response.getData().getJSONObject("comment").getString("id");
    }

    /**
     * Delete a photoset comment as the currently authenticated user.
     * @param commentId The id of the comment to delete from a photoset.
     * @throws FlickrException
     * @throws IOException
     * @throws JSONException
     */
    public void deleteComment(String commentId) throws FlickrException, IOException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_DELETE_COMMENT));
        parameters.add(new Parameter(OAuthInterface.PARAM_OAUTH_CONSUMER_KEY, apiKey));

        parameters.add(new Parameter("comment_id", commentId));
        OAuthUtils.addOAuthToken(parameters);

        // Note: This method requires an HTTP POST request.
        Response response = transportAPI.postJSON(sharedSecret, parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        // This method has no specific response - It returns an empty sucess response if it completes without error.
    }

    /**
     * Edit the text of a comment as the currently authenticated user.
     * This method requires authentication with 'write' permission.
     * @param commentId The id of the comment to edit.
     * @param commentText Update the comment to this text.
     * @throws IOException
     * @throws FlickrException
     * @throws JSONException
     */
    public void editComment(String commentId, String commentText) throws IOException, FlickrException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_EDIT_COMMENT));
        parameters.add(new Parameter(OAuthInterface.PARAM_OAUTH_CONSUMER_KEY, apiKey));

        parameters.add(new Parameter("comment_id", commentId));
        parameters.add(new Parameter("comment_text", commentText));
        OAuthUtils.addOAuthToken(parameters);

        // Note: This method requires an HTTP POST request.
        Response response = transportAPI.postJSON(sharedSecret, parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        // This method has no specific response - It returns an empty sucess response if it completes without error.
    }

    /**
     * Returns the comments for a photoset.
     *
     * This method does not require authentication.
     *
     * @param photosetId The id of the photoset to fetch comments for.
     * @return a list of {@link Comment} objects
     * @throws IOException
     * @throws FlickrException
     * @throws JSONException
     */
    public List<Comment> getList(String photosetId) throws IOException, FlickrException, JSONException {
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter("method", METHOD_GET_LIST));
        parameters.add(new Parameter("api_key", apiKey));

        parameters.add(new Parameter("photoset_id", photosetId));

        Response response = transportAPI.get(transportAPI.getPath(), parameters);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }
        // response:
        //      <comments photoset_id="72157594152539675">
        //      <comment
        //       id="2534725-72157594152539675-72157594172966066"
        //       author="99589152@N00"
        //       authorname="ortrun"
        //       datecreate="1150905040"
        //       permalink="http://www.flickr.com/photos/extranoise/sets/72157594152539675/comments#comment72157594172966066">
        //         really unreal!
        //      </comment>
        //      <comment
        //       id="2534725-72157594152539675-72157594176993150"
        //       author="47093120@N00"
        //       authorname="nis.jensen"
        //       datecreate="1151259227"
        //       permalink="http://www.flickr.com/photos/extranoise/sets/72157594152539675/comments#comment72157594176993150">
        //         Wow - you're better than most - this was a great view - i'll just take it again!
        //      </comment>
        //      <comment
        //       id="2534725-72157594152539675-72157594176996639"
        //       author="47093120@N00"
        //       authorname="nis.jensen"
        //       datecreate="1151259453"
        //       permalink="http://www.flickr.com/photos/extranoise/sets/72157594152539675/comments#comment72157594176996639">
        //        Second it's even better!!!!
        //      </comment>
        //     </comments>
        List<Comment> comments = new ArrayList<Comment>();
        JSONObject commentsElement = response.getData().getJSONObject("comments");
        JSONArray commentNodes = commentsElement.optJSONArray("comment");
        for (int i = 0; commentNodes != null && i < commentNodes.length(); i++) {
            Comment comment = new Comment();
            JSONObject commentElement = commentNodes.getJSONObject(i);
            comment.setId(commentElement.getString("id"));
            comment.setAuthor(commentElement.getString("author"));
            comment.setAuthorName(commentElement.getString("authorname"));
            comment.setPermaLink(commentElement.getString("permalink"));
            long unixTime = 0;
            try {
                unixTime = Long.parseLong(commentElement.getString("datecreate"));
            } catch (NumberFormatException e) {
                // what shall we do?
                e.printStackTrace();
            }
            comment.setDateCreate(new Date(unixTime * 1000L));
            comment.setText(commentElement.getString("_content"));
            comments.add(comment);
        }
        return comments;
    }

}


text:
<?php

class Webcomm_BootstrapNavigation_Helper_Data extends Mage_Core_Helper_Abstract
{

}


text:
<?php namespace InakiAnduaga\LaravelHtmlBuilderExtensions\Url;

use Illuminate\Routing\UrlGenerator as LaravelUrlGenerator;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;

use Illuminate\Config\Repository as Config;

/**
 * Extended UrlGenerator
 */
class UrlGenerator extends LaravelUrlGenerator {

    /**
     * Generate a URL to an application asset.
     *
     * @param  string  $path
     * @param  bool|null  $secure
     * @return string
     */
    public function asset($path, $secure = null)
    {
        if ($this->isValidUrl($path)) return $path;

        //Get redirection config for this url
        $redirector = $this->getRedirectorConfigByAssetExtension($this->getFilepathExtension($path));

        // Once we get the root URL, we will check to see if it contains an index.php
        // file in the paths. If it does, we will remove it since it is not needed
        // for asset paths, but only for routes to endpoints in the application.
        if($redirector['enabled']) {
            $root = $this->getRootUrl($this->getScheme($secure), $this->getScheme($secure).$redirector['endpoint']);
        } else {
            $root = $this->getRootUrl($this->getScheme($secure));
        }

        return $this->removeIndex($root).'/'.trim($path, '/');
    }

    /**
     * Returns the file extension for a given file path
     *
     * @param $filePath
     *
     * @return string
     */
    private function getFilepathExtension($filePath)
    {
        $pathParts = pathinfo($filePath);

        return !empty($pathParts['extension']) ? $pathParts['extension'] : '';

    }

    /**
     * Determines whether redirection should be enabled by extension
     * @param string $extension
     *
     * @return array
     */
    private function getRedirectorConfigByAssetExtension($extension)
    {
        $configuration = app(Config::class)->get('laravel-html-builder-extensions::config.redirector');

        $out = array(
            'enabled' => $configuration['globalDisable'] ? false : true,
            'endpoint' => null,
        );

        switch ($extension) {

            //Scripts
            case 'js':

                if($configuration['scripts']['enabled']) {
                    $out['endpoint'] = $configuration['scripts']['endpoint'];
                } else {
                    $out['enabled'] = false;
                }
                break;

            //Styles
            case 'css':

                if($configuration['styles']['enabled']) {
                    $out['endpoint'] = $configuration['styles']['endpoint'];
                } else {
                    $out['enabled'] = false;
                }
                break;

            //Images
            default:

                if(in_array($extension, $configuration['images']['allowedTypes'])) {
                    $out['endpoint'] = $configuration['images']['endpoint'];
                } else {
                    $out['enabled'] = false;
                }
        }

        return $out;
    }

}