text:
<?php

if (!class_exists('Folder')) {
	App::import('Core', 'Folder');
}
class UploadBehavior extends ModelBehavior {

	var $defaults = array(
		'rootDir'			=> null,
		'pathMethod'		=> 'primaryKey',
		'path'				=> '{ROOT}webroot{DS}files{DS}{model}{DS}{field}{DS}',
		'fields'			=> array('dir' => 'dir', 'type' => 'type', 'size' => 'size'),
		'mimetypes'			=> array(),
		'extensions'		=> array(),
		'maxSize'			=> 2097152,
		'minSize'			=> 8,
		'maxHeight'			=> 0,
		'minHeight'			=> 0,
		'maxWidth'			=> 0,
		'minWidth'			=> 0,
		'thumbnails'		=> true,
		'thumbnailMethod'	=> 'imagick',
		'thumbnailName'		=> null,
		'thumbnailPath'		=> null,
		'thumbnailPrefixStyle'=> true,
		'thumbnailQuality'	=> 75,
		'thumbnailSizes'	=> array(),
		'thumbnailType'		=> false,
		'deleteOnUpdate'	=> false,
		'mediaThumbnailType'=> 'png',
		'saveDir'			=> true,
	);

	var $_imageMimetypes = array(
		'image/bmp',
		'image/gif',
		'image/jpeg',
		'image/pjpeg',
		'image/png',
		'image/vnd.microsoft.icon',
		'image/x-icon',
	);

	var $_mediaMimetypes = array(
		'application/pdf',
		'application/postscript',
	);

	var $_pathMethods = array('flat', 'primaryKey', 'random');

	var $_resizeMethods = array('imagick', 'php');

	var $__filesToRemove = array();

	var $_removingOnly = array();

/**
 * Runtime configuration for this behavior
 *
 * @var array
 **/
	var $runtime;

/**
 * Initiate Upload behavior
 *
 * @param object $model instance of model
 * @param array $config array of configuration settings.
 * @return void
 * @access public
 */
	function setup(&$model, $config = array()) {
		if (isset($this->settings[$model->alias])) return;
		$this->settings[$model->alias] = array();

		foreach ($config as $field => $options) {
			$this->_setupField($model, $field, $options);
		}
	}

/**
 * Setup a particular upload field
 *
 * @param AppModel $model Model instance
 * @param string $field Name of field being modified
 * @param array $options array of configuration settings for a field
 * @return void
 * @author Jose Diaz-Gonzalez
 */
	function _setupField(&$model, $field, $options) {
		if (is_int($field)) {
			$field = $options;
			$options = array();
		}

		$this->defaults['rootDir'] = ROOT . DS . APP_DIR . DS;
		if (!isset($this->settings[$model->alias][$field])) {
			$options = array_merge($this->defaults, (array) $options);

			// HACK: Remove me in next major version
			if (!empty($options['thumbsizes'])) {
				$options['thumbnailSizes'] = $options['thumbsizes'];
			}

			if (!empty($options['prefixStyle'])) {
				$options['thumbnailPrefixStyle'] = $options['prefixStyle'];
			}
			// ENDHACK

			$options['fields'] += $this->defaults['fields'];
			if ($options['rootDir'] === null) {
				$options['rootDir'] = $this->defaults['rootDir'];
			}

			if ($options['thumbnailName'] === null) {
				if ($options['thumbnailPrefixStyle']) {
					$options['thumbnailName'] = '{size}_{filename}';
				} else {
					$options['thumbnailName'] = '{filename}_{size}';
				}
			}

			if ($options['thumbnailPath'] === null) {
				$options['thumbnailPath'] = Folder::slashTerm($this->_path($model, $field, array(
					'isThumbnail' => true,
					'path' => $options['path'],
					'rootDir' => $options['rootDir']
				)));
			} else {
				$options['thumbnailPath'] = Folder::slashTerm($this->_path($model, $field, array(
					'isThumbnail' => true,
					'path' => $options['thumbnailPath'],
					'rootDir' => $options['rootDir']
				)));
			}

			$options['path'] = Folder::slashTerm($this->_path($model, $field, array(
				'isThumbnail' => false,
				'path' => $options['path'],
				'rootDir' => $options['rootDir']
			)));

			if (!in_array($options['thumbnailMethod'], $this->_resizeMethods)) {
				$options['thumbnailMethod'] = 'imagick';
			}
			if (!in_array($options['pathMethod'], $this->_pathMethods)) {
				$options['pathMethod'] = 'primaryKey';
			}
			$options['pathMethod'] = '_getPath' . Inflector::camelize($options['pathMethod']);
			$options['thumbnailMethod'] = '_resize' . Inflector::camelize($options['thumbnailMethod']);
			$this->settings[$model->alias][$field] = $options;
		}
	}

/**
 * Convenience method for configuring UploadBehavior settings
 *
 * @param AppModel $model Model instance
 * @param string $field Name of field being modified
 * @param mixed $one A string or an array of data.
 * @param mixed $two Value in case $one is a string (which then works as the key).
 *   Unused if $one is an associative array, otherwise serves as the values to $one's keys.
 * @return void
 */
	function uploadSettings(&$model, $field, $one, $two = null) {
		if (empty($this->settings[$model->alias][$field])) {
			$this->_setupField($model, $field, array());
		}

		$data = array();

		if (is_array($one)) {
			if (is_array($two)) {
				$data = array_combine($one, $two);
			} else {
				$data = $one;
			}
		} else {
			$data = array($one => $two);
		}
		$this->settings[$model->alias][$field] = $data + $this->settings[$model->alias][$field];
	}

/**
 * Before save method. Called before all saves
 *
 * Handles setup of file uploads
 *
 * @param AppModel $model Model instance
 * @return boolean
 */
	function beforeSave(&$model) {
		$this->_removingOnly = array();
		foreach ($this->settings[$model->alias] as $field => $options) {
			if (!isset($model->data[$model->alias][$field])) continue;
			if (!is_array($model->data[$model->alias][$field])) continue;

			$this->runtime[$model->alias][$field] = $model->data[$model->alias][$field];

			$removing = isset($model->data[$model->alias][$field]['remove']);
			if ($removing || ($this->settings[$model->alias][$field]['deleteOnUpdate']
			&& isset($model->data[$model->alias][$field]['name'])
			&& strlen($model->data[$model->alias][$field]['name']))) {
				// We're updating the file, remove old versions
				if (!empty($model->id)) {
					$data = $model->find('first', array(
						'conditions' => array("{$model->alias}.{$model->primaryKey}" => $model->id),
						'contain' => false,
						'recursive' => -1,
					));
					$this->_prepareFilesForDeletion($model, $field, $data, $options);
				}

				if ($removing) {
					$model->data[$model->alias] = array(
						$field => null,
						$options['fields']['type'] => null,
						$options['fields']['size'] => null,
						$options['fields']['dir'] => null,
					);

					$this->_removingOnly[$field] = true;
					continue;
				} else {
					$model->data[$model->alias][$field] = array(
						$field => null,
						$options['fields']['type'] => null,
						$options['fields']['size'] => null,
					);
				}
			} elseif (!isset($model->data[$model->alias][$field]['name'])
			|| !strlen($model->data[$model->alias][$field]['name'])) {
				// if field is empty, don't delete/nullify existing file
				unset($model->data[$model->alias][$field]);
				continue;
			}

			$model->data[$model->alias] = array_merge($model->data[$model->alias], array(
				$field => $this->runtime[$model->alias][$field]['name'],
				$options['fields']['type'] => $this->runtime[$model->alias][$field]['type'],
				$options['fields']['size'] => $this->runtime[$model->alias][$field]['size']
			));
		}
		return true;
	}

	function afterSave(&$model, $created) {
		$temp = array($model->alias => array());
		foreach ($this->settings[$model->alias] as $field => $options) {
			if (!in_array($field, array_keys($model->data[$model->alias]))) continue;
			if (empty($this->runtime[$model->alias][$field])) continue;
		        if (isset($this->_removingOnly[$field])) continue;

			$tempPath = $this->_getPath($model, $field);

			$path = $this->settings[$model->alias][$field]['path'];
			$thumbnailPath = $this->settings[$model->alias][$field]['thumbnailPath'];

			if (!empty($tempPath)) {
				$path .= $tempPath . DS;
				$thumbnailPath .= $tempPath . DS;
			}
			$tmp = $this->runtime[$model->alias][$field]['tmp_name'];
			$filePath = $path . $model->data[$model->alias][$field];
			if (!$this->handleUploadedFile($model->alias, $field, $tmp, $filePath)) {
				$model->invalidate($field, 'moveUploadedFile');
			}

			$this->_createThumbnails($model, $field, $path, $thumbnailPath);
			if ($model->hasField($options['fields']['dir'])) {
				if ($created && $options['pathMethod'] == '_getPathFlat') {
				} else if ($options['saveDir']) {
					$temp[$model->alias][$options['fields']['dir']] = "\"{$tempPath}\"";
				}
			}
		}

		if (!empty($temp[$model->alias])) {
			$model->updateAll($temp[$model->alias], array(
				$model->alias.'.'.$model->primaryKey => $model->id
			));
		}

		if (empty($this->__filesToRemove[$model->alias])) return true;
		foreach ($this->__filesToRemove[$model->alias] as $file) {
			$result[] = $this->unlink($file);
		}
		return $result;
	}

	function handleUploadedFile($modelAlias, $field, $tmp, $filePath) {
		return !is_uploaded_file($tmp) || !@move_uploaded_file($tmp, $filePath);
	}

	function unlink($file) {
		return @unlink($file);
	}

	function beforeDelete(&$model, $cascade) {
		$data = $model->find('first', array(
			'conditions' => array("{$model->alias}.{$model->primaryKey}" => $model->id),
			'contain' => false,
			'recursive' => -1,
		));

		foreach ($this->settings[$model->alias] as $field => $options) {
			$this->_prepareFilesForDeletion($model, $field, $data, $options);
		}
		return true;
	}

	function afterDelete(&$model) {
		$result = array();
		if (!empty($this->__filesToRemove[$model->alias])) {
			foreach ($this->__filesToRemove[$model->alias] as $file) {
				$result[] = $this->unlink($file);
			}
		}
		return $result;
	}

/**
 * Verify that the uploaded file has been moved to the
 * destination successfully. This rule is special that it
 * is invalidated in afterSave(). Therefore it is possible
 * for save() to return true and this rule to fail.
 *
 * @param Object $model
 * @return boolean Always true
 * @access public
 */
	function moveUploadedFile(&$model) {
		return true;
	}
/**
 * Check that the file does not exceed the max
 * file size specified by PHP
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function isUnderPhpSizeLimit(&$model, $check) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_INI_SIZE;
	}

/**
 * Check that the file does not exceed the max
 * file size specified in the HTML Form
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function isUnderFormSizeLimit(&$model, $check) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_FORM_SIZE;
	}

/**
 * Check that the file was completely uploaded
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function isCompletedUpload(&$model, $check) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_PARTIAL;
	}

/**
 * Check that a file was uploaded
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function isFileUpload(&$model, $check) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_NO_FILE;
	}

/**
 * Check that the PHP temporary directory is missing
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function tempDirExists(&$model, $check, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_NO_TMP_DIR;
	}

/**
 * Check that the file was successfully written to the server
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function isSuccessfulWrite(&$model, $check, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_CANT_WRITE;
	}

/**
 * Check that a PHP extension did not cause an error
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @return boolean Success
 * @access public
 */
	function noPhpExtensionErrors(&$model, $check, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		return $check[$field]['error'] !== UPLOAD_ERR_EXTENSION;
	}

/**
 * Check that the file is of a valid mimetype
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param array $mimetypes file mimetypes to allow
 * @return boolean Success
 * @access public
 */
	function isValidMimeType(&$model, $check, $mimetypes = array(), $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the mimetype is invalid
		if (!isset($check[$field]['type']) || !strlen($check[$field]['type'])) {
			return false;
		}

		// Sometimes the user passes in a string instead of an array
		if (is_string($mimetypes)) {
			$mimetypes = array($mimetypes);
		}

		foreach ($mimetypes as $key => $value) {
			if (!is_int($key)) {
				$mimetypes = $this->settings[$model->alias][$field]['mimetypes'];
				break;
			}
		}

		if (empty($mimetypes)) $mimetypes = $this->settings[$model->alias][$field]['mimetypes'];

		return in_array($check[$field]['type'], $mimetypes);
	}

/**
 * Check that the upload directory is writable
 *
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param string $path Full upload path
 * @return boolean Success
 * @access public
 */
	function isWritable(&$model, $check, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		return is_writable($this->settings[$model->alias][$field]['path']);
	}

/**
 * Check that the upload directory exists
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param string $path Full upload path
 * @return boolean Success
 * @access public
 */
	function isValidDir(&$model, $check, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		return is_dir($this->settings[$model->alias][$field]['path']);
	}

/**
 * Check that the file is below the maximum file upload size
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $size Maximum file size
 * @return boolean Success
 * @access public
 */
	function isBelowMaxSize(&$model, $check, $size = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the size is too small
		if (!isset($check[$field]['size']) || !strlen($check[$field]['size'])) {
			return false;
		}

		if (!$size) $size = $this->settings[$model->alias][$field]['maxSize'];

		return $check[$field]['size'] <= $size;
	}

/**
 * Check that the file is above the minimum file upload size
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $size Minimum file size
 * @return boolean Success
 * @access public
 */
	function isAboveMinSize(&$model, $check, $size = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the size is too small
		if (!isset($check[$field]['size']) || !strlen($check[$field]['size'])) {
			return false;
		}

		if (!$size) $size = $this->settings[$model->alias][$field]['minSize'];

		return $check[$field]['size'] >= $size;
	}

/**
 * Check that the file has a valid extension
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param array $extensions file extenstions to allow
 * @return boolean Success
 * @access public
 */
	function isValidExtension(&$model, $check, $extensions = array(), $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the extension is invalid
		if (!isset($check[$field]['name']) || !strlen($check[$field]['name'])) {
			return false;
		}

		// Sometimes the user passes in a string instead of an array
		if (is_string($extensions)) {
			$extensions = array($extensions);
		}

		// Sometimes a user does not specify any extensions in the validation rule
		foreach ($extensions as $key => $value) {
			if (!is_int($key)) {
				$extensions = $this->settings[$model->alias][$field]['extensions'];
				break;
			}
		}

		if (empty($extensions)) $extensions = $this->settings[$model->alias][$field]['extensions'];
		$pathInfo = $this->_pathinfo($check[$field]['name']);

		return in_array($pathInfo['extension'], $extensions);
	}

/**
 * Check that the file is above the minimum height requirement
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $height Height of Image
 * @return boolean Success
 * @access public
 */
	function isAboveMinHeight(&$model, $check, $height = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the height is too big
		if (!isset($check[$field]['tmp_name']) || !strlen($check[$field]['tmp_name'])) {
			return false;
		}

		if (!$height) $height = $this->settings[$model->alias][$field]['minHeight'];

		list($imgWidth, $imgHeight) = getimagesize($check[$field]['tmp_name']);
		return $height > 0 && $imgHeight >= $height;
	}

/**
 * Check that the file is below the maximum height requirement
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $height Height of Image
 * @return boolean Success
 * @access public
 */
	function isBelowMaxHeight(&$model, $check, $height = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the height is too big
		if (!isset($check[$field]['tmp_name']) || !strlen($check[$field]['tmp_name'])) {
			return false;
		}

		if (!$height) $height = $this->settings[$model->alias][$field]['maxHeight'];

		list($imgWidth, $imgHeight) = getimagesize($check[$field]['tmp_name']);
		return $height > 0 && $imgHeight <= $height;
	}

/**
 * Check that the file is above the minimum width requirement
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $width Width of Image
 * @return boolean Success
 * @access public
 */
	function isAboveMinWidth(&$model, $check, $width = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the height is too big
		if (!isset($check[$field]['tmp_name']) || !strlen($check[$field]['tmp_name'])) {
			return false;
		}

		if (!$width) $width = $this->settings[$model->alias][$field]['minWidth'];

		list($imgWidth, $imgHeight) = getimagesize($check[$field]['tmp_name']);
		return $width > 0 && $imgWidth >= $width;
	}

/**
 * Check that the file is below the maximum width requirement
 *
 * @param Object $model
 * @param mixed $check Value to check
 * @param int $width Width of Image
 * @return boolean Success
 * @access public
 */
	function isBelowMaxWidth(&$model, $check, $width = null, $requireUpload = true) {
		$field = array_pop(array_keys($check));

		if (!empty($check[$field]['remove'])) {
			return true;
		}

		// Allow circumvention of this rule if uploads is not required
		if (!$requireUpload && $check[$field]['error'] === UPLOAD_ERR_NO_FILE) {
			return true;
		}

		// Non-file uploads also mean the height is too big
		if (!isset($check[$field]['tmp_name']) || !strlen($check[$field]['tmp_name'])) {
			return false;
		}

		if (!$width) $width = $this->settings[$model->alias][$field]['maxWidth'];

		list($imgWidth, $imgHeight) = getimagesize($check[$field]['tmp_name']);
		return $width > 0 && $imgWidth <= $width;
	}

	function _resizeImagick(&$model, $field, $path, $size, $geometry, $thumbnailPath) {
		$srcFile  = $path . $model->data[$model->alias][$field];
		$pathInfo = $this->_pathinfo($srcFile);
		$thumbnailType = $imageFormat = $this->settings[$model->alias][$field]['thumbnailType'];

		$isMedia = $this->_isMedia($model, $this->runtime[$model->alias][$field]['type']);
		$image    = new imagick();

		if ($isMedia) {
			$image->setResolution(300, 300);
			$srcFile = $srcFile.'[0]';
		}

		$image->readImage($srcFile);
		$height   = $image->getImageHeight();
		$width    = $image->getImageWidth();

		if (preg_match('/^\\[[\\d]+x[\\d]+\\]$/', $geometry)) {
			// resize with banding
			list($destW, $destH) = explode('x', substr($geometry, 1, strlen($geometry)-2));
			$image->thumbnailImage($destW, $destH);
		} elseif (preg_match('/^[\\d]+x[\\d]+$/', $geometry)) {
			// cropped resize (best fit)
			list($destW, $destH) = explode('x', $geometry);
			$image->cropThumbnailImage($destW, $destH);
		} elseif (preg_match('/^[\\d]+w$/', $geometry)) {
			// calculate heigh according to aspect ratio
			$image->thumbnailImage((int)$geometry-1, 0);
		} elseif (preg_match('/^[\\d]+h$/', $geometry)) {
			// calculate width according to aspect ratio
			$image->thumbnailImage(0, (int)$geometry-1);
		} elseif (preg_match('/^[\\d]+l$/', $geometry)) {
			// calculate shortest side according to aspect ratio
			$destW = 0;
			$destH = 0;
			$destW = ($width > $height) ? (int)$geometry-1 : 0;
			$destH = ($width > $height) ? 0 : (int)$geometry-1;

			$imagickVersion = phpversion('imagick');
			$image->thumbnailImage($destW, $destH, !($imagickVersion[0] == 3));
		}

		if ($isMedia) {
			$thumbnailType = $imageFormat = $this->settings[$model->alias][$field]['mediaThumbnailType'];
		}

		if (!$thumbnailType || !is_string($thumbnailType)) {
			try {
				$thumbnailType = $imageFormat = $image->getImageFormat();
				// Fix file casing
				while (true) {
					$ext = false;
					$pieces = explode('.', $srcFile);
					if (count($pieces) > 1) {
						$ext = end($pieces);
					}

					if (!$ext || !strlen($ext)) {
						break;
					}

					$low = array(
						'ext' => strtolower($ext),
						'thumbnailType' => strtolower($thumbnailType),
					);

					if ($low['ext'] == 'jpg' && $low['thumbnailType'] == 'jpeg') {
						$thumbnailType = $ext;
						break;
					}

					if ($low['ext'] == $low['thumbnailType']) {
						$thumbnailType = $ext;
					}

					break;
				}
			} catch (Exception $e) {$this->log($e->getMessage(), 'upload');
				$thumbnailType = $imageFormat = 'png';
			}
		}

		$fileName = str_replace(
			array('{size}', '{filename}', '{primaryKey}'),
			array($size, $pathInfo['filename'], $model->id),
			$this->settings[$model->alias][$field]['thumbnailName']
		);

		$destFile = "{$thumbnailPath}{$fileName}.{$thumbnailType}";

		$image->setImageCompressionQuality($this->settings[$model->alias][$field]['thumbnailQuality']);
		$image->setImageFormat($imageFormat);
		if (!$image->writeImage($destFile)) {
			return false;
		}

		$image->clear();
		$image->destroy();
		return true;
	}

	function _resizePhp(&$model, $field, $path, $size, $geometry, $thumbnailPath) {
		$srcFile  = $path . $model->data[$model->alias][$field];
		$pathInfo = $this->_pathinfo($srcFile);
		$thumbnailType = $this->settings[$model->alias][$field]['thumbnailType'];

		if (!$thumbnailType || !is_string($thumbnailType)) {
			$thumbnailType = $pathInfo['extension'];
		}

		if (!$thumbnailType) {
			$thumbnailType = 'png';
		}

		$fileName = str_replace(
			array('{size}', '{filename}'),
			array($size, $pathInfo['filename']),
			$this->settings[$model->alias][$field]['thumbnailName']
		);

		$destFile = "{$thumbnailPath}{$fileName}.{$thumbnailType}";

		copy($srcFile, $destFile);
		$src = null;
		$createHandler = null;
		$outputHandler = null;
		switch (strtolower($pathInfo['extension'])) {
			case 'gif':
				$createHandler = 'imagecreatefromgif';
				break;
			case 'jpg':
			case 'jpeg':
				$createHandler = 'imagecreatefromjpeg';
				break;
			case 'png':
				$createHandler = 'imagecreatefrompng';
				break;
			default:
				return false;
		}

		switch (strtolower($thumbnailType)) {
			case 'gif':
				$outputHandler = 'imagegif';
				break;
			case 'jpg':
			case 'jpeg':
				$outputHandler = 'imagejpeg';
				break;
			case 'png':
				$outputHandler = 'imagepng';
				break;
			default:
				return false;
		}

		if ($src = $createHandler($destFile)) {
			$srcW = imagesx($src);
			$srcH = imagesy($src);

			// determine destination dimensions and resize mode from provided geometry
			if (preg_match('/^\\[[\\d]+x[\\d]+\\]$/', $geometry)) {
				// resize with banding
				list($destW, $destH) = explode('x', substr($geometry, 1, strlen($geometry)-2));
				$resizeMode = 'band';
			} elseif (preg_match('/^[\\d]+x[\\d]+$/', $geometry)) {
				// cropped resize (best fit)
				list($destW, $destH) = explode('x', $geometry);
				$resizeMode = 'best';
			} elseif (preg_match('/^[\\d]+w$/', $geometry)) {
				// calculate heigh according to aspect ratio
				$destW = (int)$geometry-1;
				$resizeMode = false;
			} elseif (preg_match('/^[\\d]+h$/', $geometry)) {
				// calculate width according to aspect ratio
				$destH = (int)$geometry-1;
				$resizeMode = false;
			} elseif (preg_match('/^[\\d]+l$/', $geometry)) {
				// calculate shortest side according to aspect ratio
				if ($srcW > $srcH) $destW = (int)$geometry-1;
				else $destH = (int)$geometry-1;
				$resizeMode = false;
			}
			if (!isset($destW)) $destW = ($destH/$srcH) * $srcW;
			if (!isset($destH)) $destH = ($destW/$srcW) * $srcH;

			// determine resize dimensions from appropriate resize mode and ratio
			if ($resizeMode == 'best') {
				// "best fit" mode
				if ($srcW > $srcH) {
					if ($srcH/$destH > $srcW/$destW) $ratio = $destW/$srcW;
					else $ratio = $destH/$srcH;
				} else {
					if ($srcH/$destH < $srcW/$destW) $ratio = $destH/$srcH;
					else $ratio = $destW/$srcW;
				}
				$resizeW = $srcW*$ratio;
				$resizeH = $srcH*$ratio;
			} else if ($resizeMode == 'band') {
				// "banding" mode
				if ($srcW > $srcH) $ratio = $destW/$srcW;
				else $ratio = $destH/$srcH;
				$resizeW = $srcW*$ratio;
				$resizeH = $srcH*$ratio;
			} else {
				// no resize ratio
				$resizeW = $destW;
				$resizeH = $destH;
			}

			$img = imagecreatetruecolor($destW, $destH);
			imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));
			imagecopyresampled($img, $src, ($destW-$resizeW)/2, ($destH-$resizeH)/2, 0, 0, $resizeW, $resizeH, $srcW, $srcH);
			$outputHandler($img, $destFile);
			return true;
		}
		return false;
	}

	function _getPath(&$model, $field) {
		$path = $this->settings[$model->alias][$field]['path'];
		$pathMethod = $this->settings[$model->alias][$field]['pathMethod'];

		if (method_exists($this, $pathMethod)) {
			return $this->$pathMethod($model, $field, $path);
		}

		return $this->_getPathPrimaryKey($model, $field, $path);
	}

	function _getPathFlat(&$model, $field, $path) {
		$destDir = $path;
		$this->_mkPath($destDir);
		return '';
	}

	function _getPathPrimaryKey(&$model, $field, $path) {
		$destDir = $path . $model->id . DIRECTORY_SEPARATOR;
		$this->_mkPath($destDir);
		return $model->id;
	}

	function _getPathRandom(&$model, $field, $path) {
		$endPath = null;
		$decrement = 0;
		$string = crc32($field . time());

		for ($i = 0; $i < 3; $i++) {
			$decrement = $decrement - 2;
			$endPath .= sprintf("%02d" . DIRECTORY_SEPARATOR, substr('000000' . $string, $decrement, 2));
		}

		$destDir = $path . $endPath;
		$this->_mkPath($destDir);

		return substr($endPath, 0, -1);
	}

	function _mkPath($destDir) {
		if (!file_exists($destDir)) {
			@mkdir($destDir, 0777, true);
			@chmod($destDir, 0777);
		}
		return true;
	}

/**
 * Returns a path based on settings configuration
 *
 * @return string
 **/
	function _path(&$model, $fieldName, $options = array()) {
		$defaults = array(
			'isThumbnail' => true,
			'path' => '{ROOT}webroot{DS}files{DS}{model}{DS}{field}{DS}',
			'rootDir' => $this->defaults['rootDir'],
		);

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

		foreach ($options as $key => $value) {
			if ($value === null) {
				$options[$key] = $defaults[$key];
			}
		}

		if (!$options['isThumbnail']) {
			$options['path'] = str_replace(array('{size}', '{geometry}'), '', $options['path']);
		}

		$replacements = array(
			'{ROOT}'	=> $options['rootDir'],
			'{model}'	=> Inflector::underscore($model->alias),
			'{field}'	=> $fieldName,
			'{DS}'		=> DIRECTORY_SEPARATOR,
			'//'		=> DIRECTORY_SEPARATOR,
			'/'			=> DIRECTORY_SEPARATOR,
			'\\'		=> DIRECTORY_SEPARATOR,
		);

		$newPath = Folder::slashTerm(str_replace(
			array_keys($replacements),
			array_values($replacements),
			$options['path']
		));

		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
			if (!preg_match('/^([a-zA-Z]:\\\|\\\\)/', $newPath)) {
				$newPath = $options['rootDir'] . $newPath;
			}
		} elseif ($newPath[0] !== DIRECTORY_SEPARATOR) {
			$newPath = $options['rootDir'] . $newPath;
		}

		$pastPath = $newPath;
		while (true) {
			$pastPath = $newPath;
			$newPath = str_replace(array(
				'//',
				'\\',
				DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR
			), DIRECTORY_SEPARATOR, $newPath);
			if ($pastPath == $newPath) {
				break;
			}
		}

		return $newPath;
	}

	function _pathThumbnail(&$model, $field, $params = array()) {
		return str_replace(
			array('{size}', '{geometry}'),
			array($params['size'], $params['geometry']),
			$params['thumbnailPath']
		);
	}

	function _createThumbnails(&$model, $field, $path, $thumbnailPath) {
		$isImage = $this->_isImage($model, $this->runtime[$model->alias][$field]['type']);
		$isMedia = $this->_isMedia($model, $this->runtime[$model->alias][$field]['type']);
		$createThumbnails = $this->settings[$model->alias][$field]['thumbnails'];
		$hasThumbnails = !empty($this->settings[$model->alias][$field]['thumbnailSizes']);

		if (($isImage || $isMedia) && $createThumbnails && $hasThumbnails) {
			$method = $this->settings[$model->alias][$field]['thumbnailMethod'];

			foreach ($this->settings[$model->alias][$field]['thumbnailSizes'] as $size => $geometry) {
				$thumbnailPathSized = $this->_pathThumbnail($model, $field, compact(
					'geometry', 'size', 'thumbnailPath'
				));
				$this->_mkPath($thumbnailPathSized);
				if (!$this->$method($model, $field, $path, $size, $geometry, $thumbnailPathSized)) {
					$model->invalidate($field, 'resizeFail');
				}
			}
		}
	}

	function _isImage(&$model, $mimetype) {
		return in_array($mimetype, $this->_imageMimetypes);
	}

	function _isMedia(&$model, $mimetype) {
		return in_array($mimetype, $this->_mediaMimetypes);
	}

	function _getMimeType($filePath) {
		if (class_exists('finfo')) {
			$finfo = new finfo(defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME);
			return $finfo->file($filePath);
		}

		return mime_content_type($filePath);
	}

	function _prepareFilesForDeletion(&$model, $field, $data, $options) {
		if (!strlen($data[$model->alias][$field])) return $this->__filesToRemove;

		$dir = $data[$model->alias][$options['fields']['dir']];
		$filePathDir = $this->settings[$model->alias][$field]['path'] . $dir . DS;
		$filePath = $filePathDir.$data[$model->alias][$field];
		$pathInfo = $this->_pathinfo($filePath);

		$this->__filesToRemove[$model->alias] = array();
		$this->__filesToRemove[$model->alias][] = $filePath;

		$createThumbnails = $options['thumbnails'];
		$hasThumbnails = !empty($options['thumbnailSizes']);

		if (!$createThumbnails || !$hasThumbnails) {
			return $this->__filesToRemove;
		}

		$DS = DIRECTORY_SEPARATOR;
		$mimeType = $this->_getMimeType($filePath);
		$isMedia = $this->_isMedia($model, $mimeType);
		$isImagickResize = $options['thumbnailMethod'] == 'imagick';
		$thumbnailType = $options['thumbnailType'];

		if ($isImagickResize) {
			if ($isMedia) {
				$thumbnailType = $options['mediaThumbnailType'];
			}

			if (!$thumbnailType || !is_string($thumbnailType)) {
				try {
					$srcFile = $filePath;
					$image    = new imagick();
					if ($isMedia) {
						$image->setResolution(300, 300);
						$srcFile = $srcFile.'[0]';
					}

					$image->readImage($srcFile);
					$thumbnailType = $image->getImageFormat();
				} catch (Exception $e) {
					$thumbnailType = 'png';
				}
			}
		} else {
			if (!$thumbnailType || !is_string($thumbnailType)) {
				$thumbnailType = $pathInfo['extension'];
			}

			if (!$thumbnailType) {
				$thumbnailType = 'png';
			}
		}

		foreach ($options['thumbnailSizes'] as $size => $geometry) {
			$fileName = str_replace(
				array('{size}', '{filename}', '{primaryKey}'),
				array($size, $pathInfo['filename'], $model->id),
				$options['thumbnailName']
			);

			$thumbnailPath = $options['thumbnailPath'];
			$thumbnailPath = $this->_pathThumbnail($model, $field, compact(
				'geometry', 'size', 'thumbnailPath'
			));

			$thumbnailFilePath = "{$thumbnailPath}{$dir}{$DS}{$fileName}.{$thumbnailType}";
			$this->__filesToRemove[$model->alias][] = $thumbnailFilePath;
		}
		return $this->__filesToRemove;
	}

	function _pathinfo($filename) {
		$pathInfo = pathinfo($filename);

		if (!isset($pathInfo['extension']) || !strlen($pathInfo['extension'])) {
			$pathInfo['extension'] = '';
		}

		// PHP < 5.2.0 doesn't include 'filename' key in pathinfo. Let's try to fix this.
		if (empty($pathInfo['filename'])) {
			$pathInfo['filename'] = basename($pathInfo['basename'], '.' . $pathInfo['extension']);
		}
		return $pathInfo;
	}

}


text:
package org.apache.camel.itest.osgi.blueprint;

import java.lang.reflect.Method;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.DeadLetterChannelBuilder;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.apache.karaf.testing.Helper;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.Constants;
import org.osgi.service.blueprint.container.BlueprintContainer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.equinox;
import static org.ops4j.pax.exam.CoreOptions.felix;
import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
import static org.ops4j.pax.exam.OptionUtils.combine;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.profile;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption;
import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory;
import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle;

/**
 * @version
 */
@RunWith(JUnit4TestRunner.class)
public class CamelBlueprint2Test extends OSGiBlueprintTestSupport {

    @Test
    public void testEndpointInjection() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle10").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle10)", 10000);
        CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=CamelBlueprintTestBundle10)", 10000);
        Object producer = ctn.getComponentInstance("producer");
        assertNotNull(producer);
        assertEquals(TestProducer.class.getName(), producer.getClass().getName());
        Method mth = producer.getClass().getMethod("getTestEndpoint");
        assertNotNull(mth.invoke(producer));
    }

    @Test
    public void testRouteContext() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle11").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle11)", 10000);
        CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=CamelBlueprintTestBundle11)", 10000);
        assertEquals(3, ctx.getRoutes().size());
    }

    @Test
    @Ignore("TODO: Does not work")
    public void testProxy() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle12").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle12)", 10000);
        CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=CamelBlueprintTestBundle12)", 10000);
        Object proxy = ctn.getComponentInstance("myProxySender");
        assertNotNull(proxy);
        assertEquals(1, proxy.getClass().getInterfaces().length);
        assertEquals(TestProxySender.class.getName(), proxy.getClass().getInterfaces()[0].getName());
    }

    @Test
    public void testErrorHandler() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle14").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle14)", 10000);
        CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=CamelBlueprintTestBundle14)", 10000);
        assertEquals(1, ctx.getRoutes().size());
        RouteDefinition rd = ctx.getRouteDefinitions().get(0);
        assertNotNull(rd.getErrorHandlerRef());
        Object eh = ctx.getRegistry().lookup(rd.getErrorHandlerRef());
        assertEquals(DeadLetterChannelBuilder.class.getName(), eh.getClass().getName());
    }

    @Test
    public void testRouteWithNonStdComponentFromBlueprint() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle15").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle15)", 10000);
        CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.symbolicname=CamelBlueprintTestBundle15)", 10000);
        assertEquals(1, ctx.getRoutes().size());
        assertSame(ctn.getComponentInstance("mycomp"), ctx.getComponent("mycomp"));
    }

    @Test
    public void testJsseUtilNamespace() throws Exception {
        getInstalledBundle("CamelBlueprintTestBundle18").start();
        BlueprintContainer ctn = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=CamelBlueprintTestBundle18)", 10000);

        SSLContextParameters scp = (SSLContextParameters) ctn.getComponentInstance("sslContextParameters");

        assertEquals("TLS", scp.getSecureSocketProtocol());

        assertNotNull(scp.getKeyManagers());
        assertEquals("changeit", scp.getKeyManagers().getKeyPassword());
        assertNull(scp.getKeyManagers().getProvider());
        assertNotNull(scp.getKeyManagers().getKeyStore());
        assertNull(scp.getKeyManagers().getKeyStore().getType());

        assertNotNull(scp.getTrustManagers());
        assertNull(scp.getTrustManagers().getProvider());
        assertNotNull(scp.getTrustManagers().getKeyStore());
        assertNull(scp.getTrustManagers().getKeyStore().getType());

        assertNull(scp.getSecureRandom());

        assertNull(scp.getClientParameters());

        assertNull(scp.getServerParameters());

        assertEquals("test", scp.getCamelContext().getName());

        assertNotNull(scp.getCamelContext());
        assertNotNull(scp.getKeyManagers().getCamelContext());
        assertNotNull(scp.getKeyManagers().getKeyStore().getCamelContext());
        assertNotNull(scp.getTrustManagers().getCamelContext());
        assertNotNull(scp.getTrustManagers().getKeyStore().getCamelContext());
    }

    @Configuration
    public static Option[] configure() throws Exception {

        Option[] options = combine(
                // Default karaf environment
                Helper.getDefaultOptions(
                    // this is how you set the default log level when using pax logging (logProfile)
                    Helper.setLogLevel("WARN")),

                bundle(newBundle()
                        .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-10.xml"))
                        .add(TestProducer.class)
                        .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle10")
                        .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                        .build()).noStart(),

                bundle(newBundle()
                        .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-11.xml"))
                        .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle11")
                        .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                        .build()).noStart(),

                bundle(newBundle()
                        .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-12.xml"))
                        .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle12")
                        .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                        .build()).noStart(),

                bundle(newBundle()
                        .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-14.xml"))
                        .add(TestProxySender.class)
                        .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle14")
                        .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                        .build()).noStart(),

                bundle(newBundle()
                        .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-15.xml"))
                        .add(TestProxySender.class)
                        .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle15")
                        .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                        .build()).noStart(),

                bundle(newBundle()
                       .add("OSGI-INF/blueprint/test.xml", OSGiBlueprintTestSupport.class.getResource("blueprint-18.xml"))
                       .add(JsseUtilTester.class)
                       .add("localhost.ks", OSGiBlueprintTestSupport.class.getResourceAsStream("/org/apache/camel/itest/osgi/util/jsse/localhost.ks"))
                       .set(Constants.BUNDLE_SYMBOLICNAME, "CamelBlueprintTestBundle18")
                       .set(Constants.DYNAMICIMPORT_PACKAGE, "*")
                       .build()).noStart(),

                // install the spring, http features first
                scanFeatures(getKarafFeatureUrl(), "jetty"),
                // using the features to install the camel components
                scanFeatures(getCamelKarafFeatureUrl(),
                        "camel-core", "camel-blueprint", "camel-test", "camel-mail", "camel-jaxb", "camel-jms"),

                workingDirectory("target/paxrunner/"),

                felix(),
                equinox());

                // for remote debugging
                // vmOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5008"));

        return options;
    }

}

redpajama_set_name: RedPajamaGithub


text:
@interface MMBaseRequest (Promise)

- (PMKPromise *)promise;

@end


text:
const uint8_t *bsg_ksdlimageUUID(const char *const imageName, bool exactMatch) {
    if (imageName != NULL) {
        BSG_Mach_Header_Info *img = bsg_mach_headers_image_named(imageName, exactMatch);
        if (img != NULL) {
            uintptr_t cmdPtr = bsg_mach_headers_first_cmd_after_header(img->header);
            if (cmdPtr != 0) {
                for (uint32_t iCmd = 0; iCmd < img->header->ncmds; iCmd++) {
                    const struct load_command *loadCmd = (struct load_command *)cmdPtr;
                    if (loadCmd->cmd == LC_UUID) {
                        struct uuid_command *uuidCmd = (struct uuid_command *)cmdPtr;
                        return uuidCmd->uuid;
                    }
                    cmdPtr += loadCmd->cmdsize;
                }
            }
        }
    }
    return NULL;
}

bool bsg_ksdldladdr(const uintptr_t address, Dl_info *const info) {
    info->dli_fname = NULL;
    info->dli_fbase = NULL;
    info->dli_sname = NULL;
    info->dli_saddr = NULL;

    BSG_Mach_Header_Info *image = bsg_mach_headers_image_at_address(address);
    if (image == NULL) {
        return false;
    }
    const uintptr_t addressWithSlide = address - image->slide;
    const uintptr_t segmentBase =
        bsg_mach_headers_image_at_base_of_image_index(image->header) + image->slide;
    if (segmentBase == 0) {
        return false;
    }

    info->dli_fname = image->name;
    info->dli_fbase = (void *)image->header;

    // Find symbol tables and get whichever symbol is closest to the address.
    const BSG_STRUCT_NLIST *bestMatch = NULL;
    uintptr_t bestDistance = ULONG_MAX;
    uintptr_t cmdPtr = bsg_mach_headers_first_cmd_after_header(image->header);
    if (cmdPtr == 0) {
        return false;
    }
    for (uint32_t iCmd = 0; iCmd < image->header->ncmds; iCmd++) {
        const struct load_command *loadCmd = (struct load_command *)cmdPtr;
        if (loadCmd->cmd == LC_SYMTAB) {
            const struct symtab_command *symtabCmd =
                (struct symtab_command *)cmdPtr;
            const BSG_STRUCT_NLIST *symbolTable =
                (BSG_STRUCT_NLIST *)(segmentBase + symtabCmd->symoff);
            const uintptr_t stringTable = segmentBase + symtabCmd->stroff;

            for (uint32_t iSym = 0; iSym < symtabCmd->nsyms; iSym++) {
                // If n_value is 0, the symbol refers to an external object.
                if (symbolTable[iSym].n_value != 0) {
                    uintptr_t symbolBase = symbolTable[iSym].n_value;
                    uintptr_t currentDistance = addressWithSlide - symbolBase;
                    if ((addressWithSlide >= symbolBase) &&
                        (currentDistance <= bestDistance)) {
                        bestMatch = symbolTable + iSym;
                        bestDistance = currentDistance;
                    }
                }
            }
            if (bestMatch != NULL) {
                info->dli_saddr =
                    (void *)(bestMatch->n_value + image->slide);
                info->dli_sname = (char *)((intptr_t)stringTable +
                                           (intptr_t)bestMatch->n_un.n_strx);
                if (*info->dli_sname == '_') {
                    info->dli_sname++;
                }
                // This happens if all symbols have been stripped.
                if (info->dli_saddr == info->dli_fbase &&
                    bestMatch->n_type == 3) {
                    info->dli_sname = NULL;
                }
                break;
            }
        }
        cmdPtr += loadCmd->cmdsize;
    }

    return true;
}


text:
import concatFn from '../../static/concat';
import { Enumerable } from '../../internal/Enumerable';

function concat<TSource>(...sources: Iterable<TSource>[]): Enumerable<TSource> {
    return new Enumerable(concatFn(...sources));
}

Enumerable.concat = concat;

declare module '../../internal/Enumerable' {
    namespace Enumerable {
        export function concat<TSource>(...sources: Iterable<TSource>[]): Enumerable<TSource>;
    }
}


text:
package com.lewis.webscraper;

import java.text.NumberFormat;
import java.text.ParseException;

public class PlayerFactory {

	public Player createPlayer(String url) {
		BrowserService service = new BrowserService(url);
		String name = service.getPlayerName();
		Number price = 0;
		try {
			price = NumberFormat.getNumberInstance(java.util.Locale.US).parse(service.getPlayerPrice());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String position = service.getPlayerPosition();
	    String league = service.getPlayerLeague();
		String type = service.getPlayerType();
		String lastUpdated = service.getLastUpdated();
		return new Player(name, price.intValue(), position, league, type, lastUpdated);
	}

}


text:
from .singleton_form import *
from .monomial_form import *
from .polynomial_form import *
from .numerical_base_form import *
from .equivalent_form import *
from sympy import *
from sympy.abc import x,y,z

import unittest

'''
    NOTE: Sympy doesn't honor expression flag evaluate=False
        for the identity property. This may be a crippling problem, that needs
        to be handled by whatever implements this library
        Test a12 has been left in there just in case the issue is resolved
'''
class TestSymp(unittest.TestCase):
    def setUp(self):
        self.a1 = Pow(x, 2)
        self.a2 = Add(x, y,evaluate=False)
        self.a3 = Mul(x,y,2,3,evaluate=False)
        self.a4 = Mul(Pow(x,3),y,4,evaluate=False)
        self.a5 = Pow(3, 5,evaluate=False)
        self.a6 = Pow(3, pi,evaluate=False)
        self.a7 = Mul(Pow(x,4),Pow(x,9),evaluate=False)
        self.a8 = Mul(Pow(y,3),Pow(x,2),evaluate=False)
        self.a9 = Mul(Pow(y,pi),Pow(x,10),evaluate=False)
        self.a10 = Add(3,pi,pi,evaluate=False)
        self.a11 = Add(1,9,pi,evaluate=False)
        self.a13 = Add(152, pi,evaluate=False)
        self.a14 = Add(3, pi,evaluate=False)
        self.a15 = Add(3, Mul(4, pi),evaluate=False)
        self.a16 = Mul(3,pi,evaluate=False)
        self.a17 = Mul(Pow(x,3),Pow(y,2),z,Pow(2,-1),evaluate=False)
        self.a18 = Mul(Mul(Pow(x,3),Pow(y,2),z),Pow(2,-1,evaluate=False),evaluate=False)
        self.a19 = Mul(Pow(Integer(2), Integer(-1)), Pow(Symbol('m'), Integer(3)),evaluate=False)
        self.a20 = sin(x)
        self.a21 = Mul(sin(x),3,Pow(2,-1,evaluate=False),evaluate=False)
        self.a22 = Add(Pow(x,4),Pow(x,3),Pow(x,2),x,1,evaluate=False)
        self.a23 = Add(Mul(2,pi),Mul(3,pi),evaluate=False)
        self.a24 = Pow(Add(x,1),2,evaluate=False)
        self.a25 = Mul(3,Add(3,x),evaluate=False) #N
        self.a26 = Add(Mul(3,Pow(x,2)),Pow(x,1),5,evaluate=False) #N - Exponent 1
        self.a26 = Add(Mul(3,Pow(x,2)),Pow(x,0),5,evaluate=False) #N - Exponent 0
        self.a27 = Add(Mul(0,Pow(x,2)),Pow(x,0),5,evaluate=False) #N - 0*x
        self.a28 = Mul(2,Pow(4,-1,evaluate=False),evaluate=False) #N - 2/4
        self.a29 = Add(x, Mul(2,Pow(4,-1,evaluate=False),evaluate=False),evaluate=False) #N - x + 2/4
        self.a30 = Add(x, Mul(-1,Pow(3,-1,evaluate=False),evaluate=False))
        self.a31 = Mul(pi,Pow(pi,-1,evaluate=False),evaluate=False) #N - pi/pi
        self.a32 = Mul(pi,Pow(pi,-2,evaluate=False),evaluate=False) #N - pi/pi^2
        self.a33 = Pow(pi,pi,evaluate=False)
        self.a34 = Mul(-1,Pow(pi,pi,evaluate=False),evaluate=False)
        self.a35 = Pow(Mul(-1,pi),pi,evaluate=False)
        self.a36 = Add(x,3,Add(x,2,evaluate=False),evaluate=False)

        #Polynomials from Wikipedia
        self.w1 = Add(Pow(x,2),Mul(4,x),4,evaluate=False) #CC,RR,QQ,ZZ
        self.w2 = Add(Pow(x,2),-4,evaluate=False)

        self.b1 = Mul(Pow(3,5,evaluate=False),Pow(9,10,evaluate=False),evaluate=False)
        self.b2 = Pow(3,5,evaluate=False)
        self.b3 = Pow(9,10,evaluate=False)
        self.b4 = Pow(3,3,evaluate=False)

        self.total_exprs = [x,y,z,self.a1,self.a2,self.a3,self.a4,self.a5,self.a6,
            self.a7,self.a8,self.a9,self.a10,self.a11,self.a13,
            self.a14,self.a15,self.a16,self.a17,self.a18,self.a19,self.a20,
            self.a21,self.a22,self.a23,self.a24,self.a25,self.a26,self.a27,
            self.a28,self.a29,self.a30,self.a31,self.a32,self.a33,self.a34,
            self.a35,self.a36,self.b1,self.b2,self.b3,self.b4]
    '''
        Tests that ensure that all functions actualy produce a valuable output.
    '''
    def test_singleton_output(self):
        for i in self.total_exprs:
            if not is_singleton_form(i)[1]:
                print srepr(i)
            self.assertIsNotNone(is_singleton_form(i)[1])

    def test_monomial_output(self):
        for i in self.total_exprs:
            if not is_monomial_form(i)[1]:
                print srepr(i)
            self.assertIsNotNone(is_monomial_form(i)[1])

    def test_fully_expanded_polynomial_output(self):
        for i in self.total_exprs:
            if not is_fully_expanded_polynomial(i)[1]:
                print srepr(i)
            self.assertIsNotNone(is_fully_expanded_polynomial(i)[1])

    def test_fully_factored_real_polynomial_output(self):
        for i in self.total_exprs:
            if not is_fully_factored_polynomial(i)[1]:
                print srepr(i)
            self.assertIsNotNone(is_fully_factored_polynomial(i)[1])

    def test_fully_factored_complex_polynomial_output(self):
        for i in self.total_exprs:
            if not is_fully_factored_polynomial(i,domain='CC')[1]:
                print srepr(i)
            self.assertIsNotNone(is_fully_factored_polynomial(i,domain='CC')[1])

    def test_fully_factored_integer_polynomial_output(self):
        for i in self.total_exprs:
            if not is_fully_factored_polynomial(i,domain='ZZ')[1]:
                print srepr(i)
            self.assertIsNotNone(is_fully_factored_polynomial(i,domain='ZZ')[1])

    def test_simplified_exp_bases_output(self):
        for i in self.total_exprs:
            if not simplified_exp_bases(i)[1]:
                print srepr(i)
            self.assertIsNotNone(simplified_exp_bases(i)[1])

    def test_minimised_exp_bases_output(self):
        for i in self.total_exprs:
            if not minimised_exp_bases(i)[1]:
                print srepr(i)
            self.assertIsNotNone(minimised_exp_bases(i)[1])

    def test_singleton(self):
        self.assertTrue(is_singleton_form(x)[0])
        self.assertTrue(is_singleton_form(y)[0])
        self.assertTrue(is_singleton_form(z)[0])
        self.assertFalse(is_singleton_form(self.a1)[0])
        self.assertFalse(is_singleton_form(self.a2)[0])
        self.assertFalse(is_singleton_form(self.a3)[0]) #N
        self.assertFalse(is_singleton_form(self.a4)[0])
        self.assertFalse(is_singleton_form(self.a5)[0]) #N
        self.assertTrue(is_singleton_form(self.a6)[0])
        self.assertFalse(is_singleton_form(self.a7)[0])
        self.assertFalse(is_singleton_form(self.a8)[0])
        self.assertFalse(is_singleton_form(self.a9)[0])
        self.assertFalse(is_singleton_form(self.a10)[0]) #N
        self.assertFalse(is_singleton_form(self.a11)[0]) #N
        #self.assertFalse(is_singleton_form(self.a12)[0]) #N
        self.assertTrue(is_singleton_form(self.a13)[0])
        self.assertTrue(is_singleton_form(self.a14)[0])
        self.assertTrue(is_singleton_form(self.a15)[0])
        self.assertTrue(is_singleton_form(self.a16)[0])
        self.assertFalse(is_singleton_form(self.a17)[0])
        self.assertFalse(is_singleton_form(self.a18)[0])
        self.assertFalse(is_singleton_form(self.a19)[0])
        self.assertTrue(is_singleton_form(self.a20)[0])
        self.assertFalse(is_singleton_form(self.a21)[0])
        self.assertFalse(is_singleton_form(self.a22)[0])
        self.assertFalse(is_singleton_form(self.a23)[0]) #N
        self.assertFalse(is_singleton_form(self.a24)[0])
        self.assertFalse(is_singleton_form(self.a25)[0]) #N
        self.assertFalse(is_singleton_form(self.a26)[0]) #N
        self.assertFalse(is_singleton_form(self.a27)[0]) #N
        self.assertFalse(is_singleton_form(self.a28)[0]) #N
        self.assertFalse(is_singleton_form(self.a29)[0]) #N
        self.assertFalse(is_singleton_form(self.a30)[0])
        self.assertFalse(is_singleton_form(self.a31)[0]) #N
        self.assertFalse(is_singleton_form(self.a32)[0]) #N
        self.assertTrue(is_singleton_form(self.a33)[0])
        self.assertTrue(is_singleton_form(self.a34)[0])
        self.assertTrue(is_singleton_form(self.a35)[0])
        self.assertFalse(is_singleton_form(self.a36)[0])

    def test_expanded_monomial(self):
        self.assertTrue(is_monomial_form(x)[0])
        self.assertTrue(is_monomial_form(y)[0])
        self.assertTrue(is_monomial_form(z)[0])
        self.assertTrue(is_monomial_form(self.a1)[0])
        self.assertFalse(is_monomial_form(self.a2)[0])
        self.assertFalse(is_monomial_form(self.a3)[0]) #N
        self.assertTrue(is_monomial_form(self.a4)[0])
        self.assertFalse(is_monomial_form(self.a5)[0]) #N
        self.assertTrue(is_monomial_form(self.a6)[0])
        self.assertFalse(is_monomial_form(self.a7)[0])
        self.assertTrue(is_monomial_form(self.a8)[0])
        self.assertTrue(is_monomial_form(self.a9)[0])
        self.assertFalse(is_monomial_form(self.a10)[0]) #N
        self.assertFalse(is_monomial_form(self.a11)[0]) #N
        #self.assertFalse(is_monomial_form(self.a12)[0]) #N
        self.assertTrue(is_monomial_form(self.a13)[0])
        self.assertTrue(is_monomial_form(self.a14)[0])
        self.assertTrue(is_monomial_form(self.a15)[0])
        self.assertTrue(is_monomial_form(self.a16)[0])
        self.assertTrue(is_monomial_form(self.a17)[0])
        self.assertTrue(is_monomial_form(self.a18)[0])
        self.assertTrue(is_monomial_form(self.a19)[0])
        self.assertTrue(is_monomial_form(self.a20)[0])
        self.assertTrue(is_monomial_form(self.a21)[0])
        self.assertFalse(is_monomial_form(self.a22)[0])
        self.assertFalse(is_monomial_form(self.a23)[0]) #N
        self.assertFalse(is_monomial_form(self.a24)[0])
        self.assertFalse(is_monomial_form(self.a25)[0]) #N
        self.assertFalse(is_monomial_form(self.a26)[0]) #N
        self.assertFalse(is_monomial_form(self.a27)[0]) #N
        self.assertFalse(is_monomial_form(self.a28)[0]) #N
        self.assertFalse(is_monomial_form(self.a29)[0]) #N
        self.assertFalse(is_monomial_form(self.a30)[0])
        self.assertFalse(is_monomial_form(self.a31)[0]) #N
        self.assertFalse(is_monomial_form(self.a32)[0]) #N
        self.assertTrue(is_monomial_form(self.a33)[0])
        self.assertTrue(is_monomial_form(self.a34)[0])
        self.assertTrue(is_monomial_form(self.a35)[0])
        self.assertFalse(is_monomial_form(self.a36)[0])

    def test_expanded_polynomial(self):
        self.assertTrue(is_fully_expanded_polynomial(x)[0])
        self.assertTrue(is_fully_expanded_polynomial(y)[0])
        self.assertTrue(is_fully_expanded_polynomial(z)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a1)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a2)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a3)[0]) #N
        self.assertTrue(is_fully_expanded_polynomial(self.a4)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a5)[0]) #N
        self.assertTrue(is_fully_expanded_polynomial(self.a6)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a7)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a8)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a9)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a10)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a11)[0]) #N
        #self.assertFalse(is_fully_expanded_polynomial(self.a12)[0]) #N
        self.assertTrue(is_fully_expanded_polynomial(self.a13)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a14)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a15)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a16)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a17)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a18)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a19)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a20)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a21)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a22)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a23)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a24)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a25)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a26)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a27)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a28)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a29)[0]) #N
        self.assertTrue(is_fully_expanded_polynomial(self.a30)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a31)[0]) #N
        self.assertFalse(is_fully_expanded_polynomial(self.a32)[0]) #N
        self.assertTrue(is_fully_expanded_polynomial(self.a33)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a34)[0])
        self.assertTrue(is_fully_expanded_polynomial(self.a35)[0])
        self.assertFalse(is_fully_expanded_polynomial(self.a36)[0])

    def test_real_factored_polynomial(self):
        self.assertTrue(is_fully_factored_polynomial(x,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(y,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(z,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a1,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a2,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a3,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a4,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a5,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a6,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a7,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a8,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a9,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a10,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a11,domain='RR')[0]) #N
        #self.assertFalse(is_fully_factored_polynomial(self.a12,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a13,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a14,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a15,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a16,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a17,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a18,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a19,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a20,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a21,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a22,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a23,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a24,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a25,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a26,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a27,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a28,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a29,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a30,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a31,domain='RR')[0]) #N
        self.assertFalse(is_fully_factored_polynomial(self.a32,domain='RR')[0]) #N
        self.assertTrue(is_fully_factored_polynomial(self.a33,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a34,domain='RR')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a35,domain='RR')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a36,domain='RR')[0])

    def test_complex_factored_polynomial(self):
        self.assertTrue(is_fully_factored_polynomial(x,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(y,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(z,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a1,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a2,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a3,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a4,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a5,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a6,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a7,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a8,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a9,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a10,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a11,domain='CC')[0])#N
        #self.assertFalse(is_fully_factored_polynomial(self.a12,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a13,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a14,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a15,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a16,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a17,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a18,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a19,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a20,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a21,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a22,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a23,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a24,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a25,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a26,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a27,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a28,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a29,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a30,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a31,domain='CC')[0])#N
        self.assertFalse(is_fully_factored_polynomial(self.a32,domain='CC')[0])#N
        self.assertTrue(is_fully_factored_polynomial(self.a33,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a34,domain='CC')[0])
        self.assertTrue(is_fully_factored_polynomial(self.a35,domain='CC')[0])
        self.assertFalse(is_fully_factored_polynomial(self.a36,domain='CC')[0])

    def test_simplified_exp_bases(self):
        self.assertFalse(simplified_exp_bases(self.b1)[0])
        self.assertTrue(simplified_exp_bases(self.b2)[0])
        self.assertTrue(simplified_exp_bases(self.b3)[0])
        self.assertTrue(simplified_exp_bases(self.b4)[0])

    def test_minimized_exp_bases(self):
        self.assertFalse(minimised_exp_bases(self.b1)[0])
        self.assertTrue(minimised_exp_bases(self.b2)[0])
        self.assertFalse(minimised_exp_bases(self.b3)[0])
        self.assertTrue(minimised_exp_bases(self.b4)[0])

if __name__ == '__main__':
    unittest.main()


text: <DOCTYPE html>


text:
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\Mailer\Bridge\Amazon\Transport\SesTransportFactory;
use Symfony\Component\Mailer\Bridge\Google\Transport\GmailTransportFactory;
use Symfony\Component\Mailer\Bridge\Mailchimp\Transport\MandrillTransportFactory;
use Symfony\Component\Mailer\Bridge\Mailgun\Transport\MailgunTransportFactory;
use Symfony\Component\Mailer\Bridge\Mailjet\Transport\MailjetTransportFactory;
use Symfony\Component\Mailer\Bridge\OhMySmtp\Transport\OhMySmtpTransportFactory;
use Symfony\Component\Mailer\Bridge\Postmark\Transport\PostmarkTransportFactory;
use Symfony\Component\Mailer\Bridge\Sendgrid\Transport\SendgridTransportFactory;
use Symfony\Component\Mailer\Bridge\Sendinblue\Transport\SendinblueTransportFactory;
use Symfony\Component\Mailer\Transport\AbstractTransportFactory;
use Symfony\Component\Mailer\Transport\NativeTransportFactory;
use Symfony\Component\Mailer\Transport\NullTransportFactory;
use Symfony\Component\Mailer\Transport\SendmailTransportFactory;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;

return static function (ContainerConfigurator $container) {
    $container->services()
        ->set('mailer.transport_factory.abstract', AbstractTransportFactory::class)
            ->abstract()
            ->args([
                service('event_dispatcher'),
                service('http_client')->ignoreOnInvalid(),
                service('logger')->ignoreOnInvalid(),
            ])
            ->tag('monolog.logger', ['channel' => 'mailer'])

        ->set('mailer.transport_factory.amazon', SesTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.gmail', GmailTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.mailchimp', MandrillTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.mailjet', MailjetTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.mailgun', MailgunTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.postmark', PostmarkTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.sendgrid', SendgridTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.null', NullTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.sendmail', SendmailTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.sendinblue', SendinblueTransportFactory::class)
        ->parent('mailer.transport_factory.abstract')
        ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.ohmysmtp', OhMySmtpTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory')

        ->set('mailer.transport_factory.smtp', EsmtpTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory', ['priority' => -100])

        ->set('mailer.transport_factory.native', NativeTransportFactory::class)
            ->parent('mailer.transport_factory.abstract')
            ->tag('mailer.transport_factory');
};


text:
Configurando o Composer
=======================

Após a instalação do template de projetos, é uma boa ideia ajustar o `composer.json` padrão, que pode ser encontrado
no diretório raiz:

```json
{
    "name": "yiisoft/yii2-app-advanced",
    "description": "Yii 2 Advanced Project Template",
    "keywords": ["yii2", "framework", "advanced", "project template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.6.0",
        "yiisoft/yii2": "~2.0.14",
        "yiisoft/yii2-bootstrap4": "~2.0.0",
        "yiisoft/yii2-swiftmailer": "~2.0.0 || ~2.1.0"
    },
    "require-dev": {
        "yiisoft/yii2-debug": "~2.1.0",
        "yiisoft/yii2-gii": "~2.2.0",
        "yiisoft/yii2-faker": "~2.0.0",
        "codeception/codeception": "^4.0",
        "codeception/module-asserts": "^1.0",
        "codeception/module-yii2": "^1.0",
        "codeception/module-filesystem": "^1.0",
        "phpunit/phpunit": "~5.7.27 || ~6.5.5",
        "codeception/verify": "~0.5.0 || ~1.1.0",
        "symfony/browser-kit": ">=2.7 <=4.2.4"
    },
    "config": {
        "process-timeout": 1800,
        "fxp-asset": {
            "enabled": false
        }
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        }
    ]
}
```

Primeiro vamos alterar as informações básicas. Modifique `name`, `description`, `keywords`, `homepage` e `support`
para corresponder as informações do seu projeto.

Agora a parte interessante. Você pode adicionar mais pacotes que a sua aplicação necessita, na seção `require`.
Todos os pacotes são provindos do [packagist.org](https://packagist.org/) então, sinta-se a vontade para procurar
pacotes úteis no website.

Após alterar seu `composer.json` você pode executar o comando `composer update --prefer-dist`, aguardar o download e
instalação dos pacotes e depois utilizá-los. Todas as classes são carregadas automaticamente através de autoloading.


text:
package com.google.ie.business.dao.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Query;
import com.google.ie.business.domain.Idea;
import com.google.ie.business.domain.Tag;
import com.google.ie.business.domain.User;
import com.google.ie.business.service.ServiceConstants;
import com.google.ie.dto.RetrievalInfo;
import com.google.ie.test.DatastoreTest;

import org.junit.Before;
import org.junit.Test;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Test cases for IdeaDaoImpl class
 *
 * @author abraina
 */
public class IdeaDaoImplTest extends DatastoreTest {

    private IdeaDaoImpl ideaDao;
    private UserDaoImpl userDao;
    private TagDaoImpl tagDao;

    @Before
    public void setUp() {
        super.setUp();
        if (ideaDao == null) {
            ideaDao = new IdeaDaoImpl();
            ideaDao.setPersistenceManagerFactory(pmf);
            userDao = new UserDaoImpl();
            userDao.setPersistenceManagerFactory(pmf);
            tagDao = new TagDaoImpl();
            tagDao.setPersistenceManagerFactory(pmf);
        }
    }

    @Test
    public void save() {
        Idea idea = new Idea();
        idea.setTitle("Title");
        ideaDao.saveIdea(idea);
        Query query = new Query(Idea.class.getSimpleName());
        assertEquals(1,
                        DatastoreServiceFactory.getDatastoreService().prepare(query)
                        .countEntities());
    }

    @Test
    public void save_existingIdea() {
        Idea idea = new Idea();
        idea.setTitle("Title");
        idea = ideaDao.saveIdea(idea);
        idea.setTitle("Title1234");
        idea = ideaDao.saveIdea(idea);
        Idea newIdea = ideaDao.getIdea(idea);
        assertEquals("Title1234", newIdea.getTitle());
        Query query = new Query(Idea.class.getSimpleName());
        assertEquals(1,
                        DatastoreServiceFactory.getDatastoreService().prepare(query)
                        .countEntities());
    }

    @Test
    public void getUserIdeas() {
        User user = new User();
        user.setUserKey("UserTestKey");
        String key = user.getUserKey();

        Idea idea1 = new Idea();
        idea1.setTitle("title1");
        idea1.setCreatorKey(key);
        ideaDao.saveIdea(idea1);
        RetrievalInfo dummyInfo = createDummyRetrievalParam(0, 1,
                        DaoConstants.DEFAULT_IDEA_ORDERING_FIELD,
                        DaoConstants.DEFAULT_IDEA_ORDERING_TYPE);
        Set<String> statusOfIdeas = new HashSet<String>();
        statusOfIdeas.add("published");
        List<Idea> ideas = ideaDao.getUserIdeas(user, statusOfIdeas, dummyInfo);
        assertNotNull(ideas);
    }

    @Test
    public void getUserIdeas_checkNumberOfIdeasReturned() {
        User user = new User();
        user.setReputationPoints(100);
        user = userDao.saveUser(user);

        String key = user.getUserKey();
        Idea idea1 = new Idea();
        idea1.setTitle("title1");
        idea1.setCreatorKey(key);
        idea1.setStatus("Objectionable");
        ideaDao.saveIdea(idea1);

        Idea idea2 = new Idea();
        idea2.setTitle("title2");
        idea2.setCreatorKey(key);
        idea2.setStatus("Saved");
        ideaDao.saveIdea(idea2);

        RetrievalInfo dummyInfo = createDummyRetrievalParam(0, 2,
                        DaoConstants.DEFAULT_IDEA_ORDERING_FIELD,
                        DaoConstants.DEFAULT_IDEA_ORDERING_TYPE);
        Set<String> statusOfIdeas = new HashSet<String>();
        statusOfIdeas.add("Published");
        statusOfIdeas.add("Objectionable");
        statusOfIdeas.add("Saved");
        List<Idea> ideas = ideaDao.getUserIdeas(user, statusOfIdeas, dummyInfo);
        assertEquals(2, ideas.size());
    }

    @Test
    public void getUserIdeas_checkRetrievalInfoParam() {
        User user = new User();
        user.setReputationPoints(100);
        user = userDao.saveUser(user);

        RetrievalInfo retrievalParam = createDummyRetrievalParam(0, 1,
                        DaoConstants.DEFAULT_IDEA_ORDERING_FIELD,
                        DaoConstants.DEFAULT_IDEA_ORDERING_TYPE);
        String key = user.getUserKey();
        Idea idea1 = new Idea();
        idea1.setTitle("title1");
        idea1.setCreatorKey(key);
        ideaDao.saveIdea(idea1);

        Idea idea2 = new Idea();
        idea2.setTitle("title2");
        idea2.setCreatorKey(key);
        idea2.setStatus("Published");
        ideaDao.saveIdea(idea2);

        Set<String> statusOfIdeas = new HashSet<String>();
        statusOfIdeas.add("Published");
        List<Idea> ideas = ideaDao.getUserIdeas(user, statusOfIdeas,
                        retrievalParam);
        assertEquals(1, ideas.size());
    }

    @Test
    public void getIdea() {
        Idea newIdea;
        Idea ideaOld = new Idea();
        ideaOld.setTitle("TestTitle");
        ideaOld.setCreatorKey("userKey");
        ideaOld.setStatus(Idea.STATUS_PUBLISHED);
        newIdea = ideaDao.saveIdea(ideaOld);
        assertNotNull(ideaDao.getIdea(newIdea));
    }

    @Test
    public void getIdeas() {
        Idea newIdea;
        Idea ideaOld = new Idea();
        ideaOld.setTitle("TestTitle");
        ideaOld.setCreatorKey("userKey");
        ideaOld.setStatus(Idea.STATUS_PUBLISHED);
        newIdea = ideaDao.saveIdea(ideaOld);

        RetrievalInfo retrievalParam = createDummyRetrievalParam(0, 1,
                        DaoConstants.IDEA_ORDERING_FIELD_PUBLISH_DATE,
                        DaoConstants.DEFAULT_IDEA_ORDERING_TYPE);
        Set<String> statusOfIdeas = new HashSet<String>();
        statusOfIdeas.add("Published");
        assertNotNull(ideaDao.getIdeas(retrievalParam, statusOfIdeas));
        assertEquals(newIdea.getTitle(),
                        ideaDao.getIdeas(retrievalParam, statusOfIdeas).get(0).getTitle());
    }

    @Test
    public void getIdeasByTagKey() {
        Idea expectedIdea = new Idea();
        Tag tag = new Tag();
        tag.setTitle("tag1");
        tag = tagDao.saveTag(tag);
        System.out.println("Tag key ::" + tag.getKey());
        expectedIdea.setTitle("Test Idea");
        expectedIdea.setCreatorKey("userKey");
        expectedIdea.setStatus(Idea.STATUS_PUBLISHED);
        Set<String> tagKeys = new HashSet<String>();
        tagKeys.add(tag.getKey());
        expectedIdea.setTagKeys(tagKeys);
        expectedIdea = ideaDao.saveIdea(expectedIdea);
        Set<String> setOfStatus = new HashSet<String>();
        setOfStatus.add(Idea.STATUS_PUBLISHED);
        List<Idea> listOfIdeas = ideaDao.getIdeasByTagKey(tag.getKey(), setOfStatus, new
                        RetrievalInfo(0, 10, ServiceConstants.DEFAULT_IDEA_ORDERING_FIELD,
                        ServiceConstants.DEFAULT_IDEA_ORDERING_TYPE));
        assertNotNull(listOfIdeas);
        Idea actualIdea = listOfIdeas.iterator().next();
        assertEquals(expectedIdea.getTitle(), actualIdea.getTitle());
    }
}


text:
Skeleton project for running Nightwatch.js tests both on the local machine, and in SauceLabs.<br>
npm scripting is used to simplify running the locally installed nightwatch module, instead of installing it globally.

### Getting Started
1. Clone the repo
2. Open CLI inside the local project directory
3. Install dependencies with `npm install`
4. If you're running tests in SauceLabs, configure nightwatch to use your credentials using either approach:
  - Add environment variables (_SAUCE_USERNAME_, _SAUCE_ACCESS_KEY_) with their associated values to your machine
  - Hardcode them inside _nightwatch.json_ (in the default environment)
5. You are ready to go

### Example commands
Running tests on your local machine
  - __npm run nightwatch -- -t tests/ExampleTest.js -e chrome__
    - This will run the `ExampleTest.js`
    - Test will run using the Chrome browser
  - __npm run nightwatch -- -t tests/ExampleTest.js -e chrome,ie11__
    - This will run the `ExampleTest.js`
    - Test will run using the Chrome browser and the IE 11 browser, the two browsers will run in parallel

Running tests in SauceLabs
  - __npm run nightwatch -- -t tests/ExampleTest.js -e sauce_chrome__
    - This will run the `ExampleTest.js`
    - Test will run using the Chrome browser
  - __npm run nightwatch -- -e sauce_chrome__
    - This will run all of the tests under the `./tests/` directory
    - Tests will in serial, using the Chrome browser
  - __npm run nightwatch -- -e sauce_chrome_parallel__
    - This will run all of the tests under the `./tests/` directory
    - Tests will __in parallel__, using the Chrome browser


text:
package org.cloudfoundry.client.v3.packages;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;

/**
 * The response payload for the Get Package operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _GetPackageResponse extends Package {

}


text:
package fisica;

import processing.core.*;

import java.util.ArrayList;

import org.jbox2d.common.*;
import org.jbox2d.collision.*;
import org.jbox2d.collision.shapes.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.dynamics.joints.*;

/**
 * Represents a blob body that can be added to a world.
 * Blobs are soft bodies that are composed of vertices and tries to maintain constant the volume the vertices enclose.
 * Blobs can be created by adding vertices using the {@link #vertex(float,float) vertex} method in a similar way to {@link FPoly FPoly}:
 *

 * {@code
 * FBlob myBlob = new FBlob();
 * myBlob.vertex(40, 10);
 * myBlob.vertex(50, 20);
 * myBlob.vertex(60, 30);
 * myBlob.vertex(60, 40);
 * myBlob.vertex(50, 50);
 * myBlob.vertex(40, 60);
 * myBlob.vertex(30, 70);
 * myBlob.vertex(20, 60);
 * myBlob.vertex(10, 50);
 * myBlob.vertex(10, 40);
 * myBlob.vertex(20, 30);
 * myBlob.vertex(30, 20);
 * myBlob.vertex(40, 10);
 * world.add(myBlob);
 * }
 *

 *
 * or it may be initialized using the method {@link #setAsCircle(float) setAsCircle} to set the initial shape as a circle:
 *

 * {@code
 * FBlob myBlob = new FBlob();
 * myBlob.setAsCircle(40);
 * world.add(myBlob);
 * }
 *

 *
 * @usage Bodies
 * @see FBox
 * @see FCircle
 * @see FPoly
 * @see FLine
 */
public class FBlob extends FBody {
  protected ArrayList m_vertices;  // in world coords
  protected ArrayList m_vertexBodies;  // in world coords
  protected float m_damping = 0.0f;
  protected float m_frequency = 0.0f;
  protected float m_vertexSize = 0.4f;  // in world coords

  protected Vec2 m_force = new Vec2();
  protected float m_torque = 0.0f;
  protected float m_density = 1.0f;
  protected float m_restitution = 0.5f;
  protected float m_friction = 0.5f;
  protected boolean m_bullet = false;

  protected FConstantVolumeJoint m_joint;

  /**
   * Constructs a blob body that can be added to a world.  It creates an empty blob, before adding the blob to the world use {@link #vertex(float,float) vertex} or {@link #setAsCircle(float) setAsCircle} to define the initial shape of the blob.
   */
  public FBlob() {
    super();

    m_vertices = new ArrayList();
    m_vertexBodies = new ArrayList();
  }

  public void addToWorld(FWorld world) {
    // Create the constant volume joint
    m_joint = new FConstantVolumeJoint();
    m_joint.setFrequency(m_frequency);
    m_joint.setDamping(m_damping);
    m_joint.updateStyle(this);

    // Create bodies from the vertices and add them to the
    // constant volume joint that we just created
    for (int i=0; i<m_vertices.size(); i++) {
      Vec2 p = Fisica.worldToScreen((Vec2)m_vertices.get(i));
      FBody fb = new FCircle(getVertexSize());
      fb.setPosition(p.x, p.y);
      fb.setDensity(m_density);
      fb.setRestitution(m_restitution);
      fb.setFriction(m_friction);
      fb.setGroupIndex(m_groupIndex);
      fb.setFilterBits(m_filterBits);
      fb.setCategoryBits(m_categoryBits);
      fb.setState(this);
      m_vertexBodies.add(fb);
    }

    for (int i=0; i<m_vertexBodies.size(); i++) {
      FBody fb = (FBody)m_vertexBodies.get(i);
      fb.setDrawable(false);
      fb.setParent(this);
      fb.setRotatable(false);
      world.add(fb);

      Vec2 f = Fisica.worldToScreen(m_force);
      fb.addForce(f.x, f.y);
      fb.addTorque(m_torque);

      m_joint.addBody(fb);
    }

    m_joint.setCollideConnected(false);
    world.add(m_joint);
  }

  public void removeFromWorld() {
    // Remove the constant volume joint
    m_joint.removeFromWorld();

    // Remove the vertex bodies
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)(m_vertexBodies.get(i))).removeFromWorld();
    }
  }

  /**
   * Adds a vertex body to the initial shape of the blob.  This method must be called before adding the body to the world.
   *
   * @param b  b the body to be added
   */
  public void addVertexBody(FBody b){
    m_vertexBodies.add(b);
  }

  /**
   * Adds a vertex to the initial shape of the blob.  This method must be called before adding the body to the world.
   *
   * @param x  x coordinate of the vertex to be added
   * @param y  y coordinate of the vertex to be added
   */
  public void vertex(float x, float y){
    m_vertices.add(Fisica.screenToWorld(x, y));
  }

  /**
   * Gets the x coordinate of the ith vertex of the initial shape of the blob.
   *
   * @param i  index of the vertex to retrieve
   * @return  the x coordinate of the vertex to retrieve
   */
  public float getVertexX(int i){
    return Fisica.worldToScreen((Vec2)m_vertices.get(i)).x;
  }

  /**
   * Gets the y coordinate of the ith vertex of the initial shape of the blob.
   *
   * @param i  index of the vertex to retrieve
   * @return  the y coordinate of the vertex to retrieve
   */
  public float getVertexY(int i){
    return Fisica.worldToScreen((Vec2)m_vertices.get(i)).y;
  }

  /**
   * Sets the initial shape of the blob to a circle.  This method removes all the previous vertices tha may have been added by the use of the {@link #vertex(float,float) vertex}.  This method must be called before adding the body to the world.
   *
   * @param x  x coordinate of the position of the circle
   * @param y  y coordinate of the position of the circle
   * @param size  size of the circle
   * @param vertexCount  number of vertices of the circle
   */
  public void setAsCircle(float x, float y,
                          float size, int vertexCount) {
    m_vertices.clear();

    for (int i=0; i<vertexCount; i++) {
      float angle = Fisica.parent().map(i, 0, vertexCount, 0, Fisica.parent().TWO_PI);
      float vx = x + size/2 * Fisica.parent().sin(angle);
      float vy = y + size/2 * Fisica.parent().cos(angle);

      this.vertex(vx, vy);
    }
  }

  /**
   * Sets the initial shape of the blob to a circle.  This method removes all the previous vertices tha may have been added by the use of the {@link #vertex(float,float) vertex}.  This method must be called before adding the body to the world.
   *
   * @param x  x coordinate of the position of the circle
   * @param y  y coordinate of the position of the circle
   * @param size  size of the circle
   */
  public void setAsCircle(float x, float y, float size) {
      setAsCircle(x, y, size, 30);
  }

  /**
   * Sets the initial shape of the blob to a circle.  This method removes all the previous vertices tha may have been added by the use of the {@link #vertex(float,float) vertex}.  This method must be called before adding the body to the world.
   *
   * @param size  size of the circle
   */
  public void setAsCircle(float size) {
    setAsCircle(0, 0, size, 30);
  }

  /**
   * Sets the initial shape of the blob to a circle.  This method removes all the previous vertices tha may have been added by the use of the {@link #vertex(float,float) vertex}.  This method must be called before adding the body to the world.
   *
   * @param size  size of the circle
   * @param vertexCount  number of vertices of the circle
   */
  public void setAsCircle(float size, int vertexCount) {
    setAsCircle(0, 0, size, vertexCount);
  }

  /**
   * Returns the size of the circular vertices of the blob.  This method must be called before the body is added to the world.
   *
   * @return size of the circular vertices of the blob
   */
  public float getVertexSize(){
    return Fisica.worldToScreen(m_vertexSize);
  }

  /**
   * Sets the size of the circular vertices of the blob.  This method must be called before the body is added to the world.
   *
   * @param size  size of the circular vertices of the blob
   */
  public void setVertexSize(float size){
    m_vertexSize = Fisica.screenToWorld(size);
  }

  /**
   * Returns vertices of the blob.
   *
   * @return list of vertex bodies
   */
  public ArrayList getVertexBodies() {
    return m_vertexBodies;
  }

  /**
   * Sets the frequency of the springs used to maintain the volume defined by the vertices constant.
   *
   * @param frequency  the frequency of the springs of the constant volume joint
   */
  public void setFrequency(float frequency) {
    if ( m_joint != null ) {
      m_joint.setFrequency(frequency);
    }

    m_frequency = frequency;
  }

  /**
   * Sets the damping of the springs used to maintain the volume defined by the vertices constant.
   *
   * @param damping  the damping of the springs of the constant volume joint
   */
  public void setDamping(float damping) {
    if ( m_joint != null ) {
      m_joint.setDamping(damping);
    }

    m_damping = damping;
  }

  public void addForce(float fx, float fy) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).addForce(fx, fy);
    }

    m_force.add(Fisica.screenToWorld(fx, fy));
  }

  public void addTorque(float t) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).addTorque(t);
    }

    m_torque += t;
  }

  public void setDensity(float d) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).setDensity(d);
    }

    m_density = d;
  }

  public void setFriction(float d) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).setFriction(d);
    }

    m_friction = d;
  }

  public void setRestitution(float d) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).setRestitution(d);
    }

    m_restitution = d;
  }

  public void setBullet(boolean d) {
    for (int i=0; i<m_vertexBodies.size(); i++) {
      ((FBody)m_vertexBodies.get(i)).setBullet(d);
    }

    m_bullet = d;
  }

  public void setNoStroke() {
    super.setNoStroke();

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void setNoFill() {
    super.setNoFill();

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void setFillColor(int col) {
    super.setFillColor(col);

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void setStrokeColor(int col) {
    super.setStrokeColor(col);

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void setStrokeWeight(float col) {
    super.setStrokeWeight(col);

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void setDrawable(boolean val) {
    super.setDrawable(val);

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void attachImage( PImage img ) {
    super.attachImage(img);

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }

  public void dettachImage() {
    super.dettachImage();

    if (m_joint != null) {
      m_joint.updateStyle(this);
    }
  }
}