text:
<?php

if (!defined('_PS_VERSION_'))
	exit;

if (defined('_PS_ADMIN_DIR_') === false)
	define('_PS_ADMIN_DIR_', _PS_ROOT_DIR_.'/admin/');

require_once(dirname(__FILE__).'/classes/CronJobsForms.php');

class CronJobs extends PaymentModule
{
	const EACH = -1;

	protected $_successes;
	protected $_warnings;

	public $webservice_url = 'http://webcron.prestashop.com/crons';

	public function __construct()
	{
		$this->name = 'cronjobs';
		$this->tab = 'administration';
		$this->version = '1.2.5';
		$this->module_key = '';

		$this->controllers = array('callback');

		$this->currencies = true;
		$this->currencies_mode = 'checkbox';
		$this->author = 'PrestaShop';
		$this->need_instance = true;

		$this->bootstrap = true;
		$this->display = 'view';

		parent::__construct();

		if ($this->id)
			$this->init();

		$this->displayName = $this->l('Cron tasks manager');
		$this->description = $this->l('Manage all your automated web tasks from a single interface.');

		if (function_exists('curl_init') == false)
			$this->warning = $this->l('To be able to use this module, please activate cURL (PHP extension).');
	}

	public function install()
	{
		Configuration::updateValue('CRONJOBS_ADMIN_DIR', Tools::encrypt(_PS_ADMIN_DIR_));
		Configuration::updateValue('CRONJOBS_MODE', 'webservice');
		Configuration::updateValue('CRONJOBS_MODULE_VERSION', $this->version);
		Configuration::updateValue('CRONJOBS_WEBSERVICE_ID', 0);

		$token = Tools::encrypt(Tools::getShopDomainSsl().time());
		Configuration::updateGlobalValue('CRONJOBS_EXECUTION_TOKEN', $token);

		if (parent::install())
		{
			$this->updateWebservice(true);

			return $this->installDb() && $this->installTab() &&
				$this->registerHook('actionModuleRegisterHookAfter') &&
				$this->registerHook('actionModuleUnRegisterHookAfter') &&
				$this->registerHook('backOfficeHeader');
		}

		return false;
	}

	protected function init()
	{
		$new_admin_dir = (Tools::encrypt(_PS_ADMIN_DIR_) != Configuration::get('CRONJOBS_ADMIN_DIR'));
		$new_module_version = version_compare($this->version, Configuration::get('CRONJOBS_MODULE_VERSION'), '!=');

		if ($new_admin_dir || $new_module_version)
		{
			Configuration::updateValue('CRONJOBS_MODULE_VERSION', $this->version);
			Configuration::updateValue('CRONJOBS_ADMIN_DIR', Tools::encrypt(_PS_ADMIN_DIR_));

			if (Configuration::get('CRONJOBS_MODE') == 'webservice')
				return $this->enableWebservice();
			return $this->disableWebservice();
		}
	}

	public function uninstall()
	{
		Configuration::deleteByName('CRONJOBS_MODE');

		$this->disableWebservice();

		return	$this->uninstallDb() &&
			$this->uninstallTab() &&
			parent::uninstall();
	}

	public function installDb()
	{
		return Db::getInstance()->execute('
			CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.$this->name.' (
			`id_cronjob` INTEGER(10) NOT NULL AUTO_INCREMENT,
			`id_module` INTEGER(10) DEFAULT NULL,
			`description` TEXT DEFAULT NULL,
			`task` TEXT DEFAULT NULL,
			`hour` INTEGER DEFAULT \'-1\',
			`day` INTEGER DEFAULT \'-1\',
			`month` INTEGER DEFAULT \'-1\',
			`day_of_week` INTEGER DEFAULT \'-1\',
			`updated_at` DATETIME DEFAULT NULL,
			`one_shot` BOOLEAN NOT NULL DEFAULT 0,
			`active` BOOLEAN DEFAULT FALSE,
			`id_shop` INTEGER DEFAULT \'0\',
			`id_shop_group` INTEGER DEFAULT \'0\',
			PRIMARY KEY(`id_cronjob`),
			INDEX (`id_module`))
			ENGINE='._MYSQL_ENGINE_.' default CHARSET=utf8'
		);
	}

	public function uninstallDb()
	{
		return Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.$this->name);
	}

	public function installTab()
	{
		$tab = new Tab();
		$tab->active = 1;
		$tab->name = array();
		$tab->class_name = 'AdminCronJobs';

		foreach (Language::getLanguages(true) as $lang)
			$tab->name[$lang['id_lang']] = 'Cron Jobs';

		$tab->id_parent = -1;
		$tab->module = $this->name;

		return $tab->add();
	}

	public function uninstallTab()
	{
		$id_tab = (int)Tab::getIdFromClassName('AdminCronJobs');

		if ($id_tab)
		{
			$tab = new Tab($id_tab);
			return $tab->delete();
		}

		return false;
	}

	public function hookActionModuleRegisterHookAfter($params)
	{
		$hook_name = $params['hook_name'];

		if ($hook_name == 'actionCronJob')
		{
			$module = $params['object'];
			$this->registerModuleHook($module->id);
			$this->updateWebservice(Configuration::get('CRONJOBS_MODE') == 'webservice');
		}
	}

	public function hookActionModuleUnRegisterHookAfter($params)
	{
		$hook_name = $params['hook_name'];

		if ($hook_name == 'actionCronJob')
		{
			$module = $params['object'];
			$this->unregisterModuleHook($module->id);
			$this->updateWebservice(Configuration::get('CRONJOBS_MODE') == 'webservice');
		}
	}

	public function hookBackOfficeHeader()
	{
		if (Tools::getValue('configure') == $this->name)
		{
			if (version_compare(_PS_VERSION_, '1.6', '<') == true)
			{
				$this->context->controller->addCSS($this->_path.'css/bootstrap.min.css');
				$this->context->controller->addCSS($this->_path.'css/configure-ps-15.css');
			}
			else
				$this->context->controller->addCSS($this->_path.'css/configure-ps-16.css');
		}
	}

	public function getContent()
	{
		$output = null;
		CronJobsForms::init($this);
		$this->checkLocalEnvironment();

		if (Tools::isSubmit('submitCronJobs'))
			$this->postProcessConfiguration();
		elseif (Tools::isSubmit('submitNewCronJob'))
			$submit_cron = $this->postProcessNewJob();
		elseif (Tools::isSubmit('submitUpdateCronJob'))
			$submit_cron = $this->postProcessUpdateJob();

		$this->context->smarty->assign(array(
			'module_dir' => $this->_path,
			'module_local_dir' => $this->local_path,
		));

		$this->context->smarty->assign('form_errors', $this->_errors);
		$this->context->smarty->assign('form_infos', $this->_warnings);
		$this->context->smarty->assign('form_successes', $this->_successes);

		if ((Tools::isSubmit('submitNewCronJob') || Tools::isSubmit('newcronjobs') || Tools::isSubmit('updatecronjobs')) &&
			((isset($submit_cron) == false) || ($submit_cron === false)))
		{
			$back_url = $this->context->link->getAdminLink('AdminModules', false)
				.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name
				.'&token='.Tools::getAdminTokenLite('AdminModules');
		}

		$output = $output.$this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');

		if (Tools::isSubmit('newcronjobs') || ((isset($submit_cron) == true) && ($submit_cron === false)))
			$output = $output.$this->renderForm(CronJobsForms::getJobForm(), CronJobsForms::getNewJobFormValues(), 'submitNewCronJob', true, $back_url);
		elseif (Tools::isSubmit('updatecronjobs') && Tools::isSubmit('id_cronjob'))
		{
			$form_structure = CronJobsForms::getJobForm('Update cron task', true);
			$form = $this->renderForm($form_structure, CronJobsForms::getUpdateJobFormValues(), 'submitUpdateCronJob', true, $back_url, true);
			$output = $output.$form;
		}
		elseif (Tools::isSubmit('deletecronjobs') && Tools::isSubmit('id_cronjob'))
			$this->postProcessDeleteCronJob((int)Tools::getValue('id_cronjob'));
		elseif (Tools::isSubmit('oneshotcronjobs'))
			$this->postProcessUpdateJobOneShot();
		elseif (Tools::isSubmit('statuscronjobs'))
			$this->postProcessUpdateJobStatus();
		elseif (defined('_PS_HOST_MODE_') == false)
			$output = $output.$this->renderForm(CronJobsForms::getForm(), CronJobsForms::getFormValues(), 'submitCronJobs');

		return $output.$this->renderTasksList();
	}

	public function sendCallback()
	{
		ignore_user_abort(true);
		set_time_limit(0);

		ob_start();
		echo $this->name.'_prestashop';
		header('Connection: close');
		header('Content-Length: '.ob_get_length());
		ob_end_flush();
		ob_flush();
		flush();
	}

	public static function isActive($id_module)
	{
		$module = Module::getInstanceByName('cronjobs');

		if (($module == false) || ($module->active == false))
			return false;

		$query = 'SELECT `active` FROM '._DB_PREFIX_.'cronjobs WHERE `id_module` = \''.(int)$id_module.'\'';
		return (bool)Db::getInstance()->getValue($query);
	}

	/**
	 * $taks should be a valid URL
	 */
	public static function addOneShotTask($task, $description, $execution = array())
	{
		if (self::isTaskURLValid($task) == false)
			return false;

		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		$query = 'SELECT `active` FROM '._DB_PREFIX_.'cronjobs
			WHERE `task` = \''.urlencode($task).'\' AND `updated_at` IS NULL
				AND `one_shot` IS TRUE
				AND `id_shop` = \''.$id_shop.'\' AND `id_shop_group` = \''.$id_shop_group.'\'';

		if ((bool)Db::getInstance()->getValue($query) == true)
			return true;

		if (count($execution) == 0)
		{
			$query = 'INSERT INTO '._DB_PREFIX_.'cronjobs
				(`description`, `task`, `hour`, `day`, `month`, `day_of_week`, `updated_at`, `one_shot`, `active`, `id_shop`, `id_shop_group`)
				VALUES (\''.$description.'\', \''.urlencode($task).'\', \'0\', \''.CronJobs::EACH.'\', \''.CronJobs::EACH.'\', \''.CronJobs::EACH.'\',
					NULL, TRUE, TRUE, '.$id_shop.', '.$id_shop_group.')';

			return Db::getInstance()->execute($query);
		}
		else
		{
			$hour = (int)$execution['hour'];
			$day = (int)$execution['day'];
			$month = (int)$execution['month'];
			$day_of_week = (int)$execution['day_of_week'];

			if ($this->isFrequencyValid($hour, $day, $month, $day_of_week))
			{
				$query = 'INSERT INTO '._DB_PREFIX_.'cronjobs
					(`description`, `task`, `hour`, `day`, `month`, `day_of_week`, `updated_at`, `one_shot`, `active`, `id_shop`, `id_shop_group`)
					VALUES (\''.$description.'\', \''.urlencode($task).'\', \''.$hour.'\', \''.$day.'\', \''.$month.'\', \''.$day_of_week.'\',
						NULL, TRUE, TRUE, '.$id_shop.', '.$id_shop_group.')';

				return Db::getInstance()->execute($query);
			}
		}

		return false;
	}

	protected function checkLocalEnvironment()
	{
		if ($this->isLocalEnvironment() == true)
			$this->setWarningMessage('You are using the Cron jobs module on a local installation:
				you will not be able to use the Basic mode or reliably call remote cron tasks in your current environment.
				To use this module at its best, you should switch to an online installation.');
	}

	protected function isLocalEnvironment()
	{
		if (isset($_SERVER['REMOTE_ADDR']) === false)
			return true;

		return in_array(Tools::getRemoteAddr(), array('127.0.0.1', '::1'));
	}

	protected function renderForm($form, $form_values, $action, $cancel = false, $back_url = false, $update = false)
	{
		$helper = new HelperForm();

		$helper->show_toolbar = false;
		$helper->module = $this;
		$helper->default_form_language = $this->context->language->id;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

		$helper->identifier = $this->identifier;
		$helper->submit_action = $action;

		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
		.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;

		if ($update == true)
			$helper->currentIndex .= '&id_cronjob='.(int)Tools::getValue('id_cronjob');

		$helper->token = Tools::getAdminTokenLite('AdminModules');

		$helper->tpl_vars = array(
			'fields_value' => $form_values,
			'id_language' => $this->context->language->id,
			'languages' => $this->context->controller->getLanguages(),
			'back_url' => $back_url,
			'show_cancel_button' => $cancel,
		);

		return $helper->generateForm($form);
	}

	protected function renderTasksList()
	{
		$helper = new HelperList();

		$helper->title = $this->l('Cron tasks');
		$helper->table = $this->name;
		$helper->no_link = true;
		$helper->shopLinkType = '';
		$helper->identifier = 'id_cronjob';
		$helper->actions = array('edit', 'delete');

		$values = CronJobsForms::getTasksListValues();
		$helper->listTotal = count($values);
		$helper->tpl_vars = array('show_filters' => false);

		$helper->toolbar_btn['new'] = array(
			'href' => $this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name
			.'&newcronjobs=1&token='.Tools::getAdminTokenLite('AdminModules'),
			'desc' => $this->l('Add new task')
		);

		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;

		return $helper->generateList($values, CronJobsForms::getTasksList());
	}

	protected function postProcessConfiguration()
	{
		if (Tools::isSubmit('cron_mode') == true)
		{
			if (Tools::getValue('cron_mode') == 'advanced')
				return $this->disableWebservice();
			return $this->enableWebservice();
		}
	}

	protected function postProcessNewJob()
	{
		if ($this->isNewJobValid() == true)
		{
			$description = Tools::getValue('description');
			$task = urlencode(Tools::getValue('task'));
			$hour = (int)Tools::getValue('hour');
			$day = (int)Tools::getValue('day');
			$month = (int)Tools::getValue('month');
			$day_of_week = (int)Tools::getValue('day_of_week');

			$result = Db::getInstance()->getRow('SELECT id_cronjob FROM '._DB_PREFIX_.$this->name.'
				WHERE `task` = \''.$task.'\' AND `hour` = \''.$hour.'\' AND `day` = \''.$day.'\'
				AND `month` = \''.$month.'\' AND `day_of_week` = \''.$day_of_week.'\'');

			if ($result == false)
			{
				$id_shop = (int)Context::getContext()->shop->id;
				$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

				$query = 'INSERT INTO '._DB_PREFIX_.$this->name.'
					(`description`, `task`, `hour`, `day`, `month`, `day_of_week`, `updated_at`, `active`, `id_shop`, `id_shop_group`)
					VALUES (\''.$description.'\', \''.$task.'\', \''.$hour.'\', \''.$day.'\', \''.$month.'\', \''.$day_of_week.'\', NULL, TRUE, '.$id_shop.', '.$id_shop_group.')';

				if (($result = Db::getInstance()->execute($query)) != false)
					return $this->setSuccessMessage('The task has been successfully added.');
				return $this->setErrorMessage('An error happened: the task could not be added.');
			}

			return $this->setErrorMessage('This cron task already exists.');
		}

		return false;
	}

	protected function postProcessUpdateJob()
	{
		if (Tools::isSubmit('id_cronjob') == false)
			return false;

		$description = Tools::getValue('description');
		$task = urlencode(Tools::getValue('task'));
		$hour = (int)Tools::getValue('hour');
		$day = (int)Tools::getValue('day');
		$month = (int)Tools::getValue('month');
		$day_of_week = (int)Tools::getValue('day_of_week');
		$id_cronjob = (int)Tools::getValue('id_cronjob');

		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		$query = 'UPDATE '._DB_PREFIX_.$this->name.'
			SET `description` = \''.$description.'\',
				`task` = \''.$task.'\',
				`hour` = \''.$hour.'\',
				`day` = \''.$day.'\',
				`month` = \''.$month.'\',
				`day_of_week` = \''.$day_of_week.'\'
			WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'';

		if (($result = Db::getInstance()->execute($query)) != false)
			return $this->setSuccessMessage('The task has been updated.');
		return $this->setErrorMessage('The task has not been updated');
	}

	public function addNewModulesTasks()
	{
		$crons = Hook::getHookModuleExecList('actionCronJob');

		if ($crons == false)
			return false;

		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		foreach ($crons as $cron)
		{
			$id_module = (int)$cron['id_module'];
			$module = Module::getInstanceById((int)$cron['id_module']);

			if ($module == false)
			{
				Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.$this->name.' WHERE `id_cronjob` = \''.(int)$cron['id_cronjob'].'\'');
				break;
			}

			$cronjob = (bool)Db::getInstance()->getValue('SELECT `id_cronjob` FROM `'._DB_PREFIX_.$this->name.'`
				WHERE `id_module` = \''.$id_module.'\' AND `id_shop` = \''.$id_shop.'\' AND `id_shop_group` = \''.$id_shop_group.'\'');

			if ($cronjob == false)
				$this->registerModuleHook($id_module);
		}
	}

	protected function postProcessUpdateJobOneShot()
	{
		if (Tools::isSubmit('id_cronjob') == false)
			return false;

		$id_cronjob = (int)Tools::getValue('id_cronjob');
		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		Db::getInstance()->execute('UPDATE '._DB_PREFIX_.$this->name.'
			SET `one_shot` = IF (`one_shot`, 0, 1) WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'');

		Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name
			.'&token='.Tools::getAdminTokenLite('AdminModules'));
	}

	protected function postProcessUpdateJobStatus()
	{
		if (Tools::isSubmit('id_cronjob') == false)
			return false;

		$id_cronjob = (int)Tools::getValue('id_cronjob');
		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		Db::getInstance()->execute('UPDATE '._DB_PREFIX_.$this->name.'
			SET `active` = IF (`active`, 0, 1) WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'');

		Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name
			.'&token='.Tools::getAdminTokenLite('AdminModules'));
	}

	protected function isNewJobValid()
	{
		if ((Tools::isSubmit('description') == true) &&
			(Tools::isSubmit('task') == true) &&
			(Tools::isSubmit('hour') == true) &&
			(Tools::isSubmit('day') == true) &&
			(Tools::isSubmit('month') == true) &&
			(Tools::isSubmit('day_of_week') == true))
		{
			if (self::isTaskURLValid(Tools::getValue('task')) == false)
				return $this->setErrorMessage('The target link you entered is not valid. It should be an absolute URL, on the same domain as your shop.');

			$hour = Tools::getValue('hour');
			$day = Tools::getValue('day');
			$month = Tools::getValue('month');
			$day_of_week = Tools::getValue('day_of_week');

			return $this->isFrequencyValid($hour, $day, $month, $day_of_week);
		}

		return false;
	}

	protected function isFrequencyValid($hour, $day, $month, $day_of_week)
	{
		$success = true;

		if ((($hour >= -1) && ($hour < 24)) == false)
			$success &= $this->setErrorMessage('The value you chose for the hour is not valid. It should be between 00:00 and 23:59.');
		if ((($day >= -1) && ($day <= 31)) == false)
			$success &= $this->setErrorMessage('The value you chose for the day is not valid.');
		if ((($month >= -1) && ($month <= 31)) == false)
			$success &= $this->setErrorMessage('The value you chose for the month is not valid.');
		if ((($day_of_week >= -1) && ($day_of_week < 7)) == false)
			$success &= $this->setErrorMessage('The value you chose for the day of the week is not valid.');

		return $success;
	}

	protected static function isTaskURLValid($task)
	{
		$task = urlencode($task);
		$shop_url = urlencode(Tools::getShopDomain(true, true).__PS_BASE_URI__);
		$shop_url_ssl = urlencode(Tools::getShopDomainSsl(true, true).__PS_BASE_URI__);

		return ((strpos($task, $shop_url) === 0) || (strpos($task, $shop_url_ssl) === 0));
	}

	protected function setErrorMessage($message)
	{
		$this->_errors[] = $this->l($message);
		return false;
	}

	protected function setSuccessMessage($message)
	{
		$this->_successes[] = $this->l($message);
		return true;
	}

	protected function setWarningMessage($message)
	{
		$this->_warnings[] = $this->l($message);
		return false;
	}

	protected function enableWebservice()
	{
		Configuration::updateValue('CRONJOBS_MODE', 'webservice');
		$this->updateWebservice(true);
	}

	protected function disableWebservice()
	{
		Configuration::updateValue('CRONJOBS_MODE', 'advanced');
		$this->updateWebservice(false);
	}

	protected function updateWebservice($use_webservice)
	{
		$link = new Link();
		$admin_folder = rtrim(str_replace(_PS_ROOT_DIR_.'/', null, _PS_ADMIN_DIR_), '/');
		$path = Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.$admin_folder;
		$cron_url = $path.'/'.$link->getAdminLink('AdminCronJobs', false);

		$webservice_id = Configuration::get('CRONJOBS_WEBSERVICE_ID') ? '/'.Configuration::get('CRONJOBS_WEBSERVICE_ID') : null;

		$data = array(
			'callback' => $link->getModuleLink($this->name, 'callback'),
			'domain' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__,
			'cronjob' => $cron_url.'&token='.Configuration::getGlobalValue('CRONJOBS_EXECUTION_TOKEN'),
			'cron_token' => Configuration::getGlobalValue('CRONJOBS_EXECUTION_TOKEN'),
			'active' => (bool)$use_webservice
		);

		$context_options = array('http' => array(
			'method' => (is_null($webservice_id) == true) ? 'POST' : 'PUT',
			'content' => http_build_query($data)
		));

		// die(var_dump(_PS_ADMIN_DIR_, $admin_folder, $path, $cron_url, $this->webservice_url.$webservice_id, $context_options));

		$result = Tools::file_get_contents($this->webservice_url.$webservice_id, false, stream_context_create($context_options));

		if ($result != false)
			Configuration::updateValue('CRONJOBS_WEBSERVICE_ID', (int)$result);

		if (((Tools::isSubmit('install') == true) || (Tools::isSubmit('reset') == true)) && ((bool)$result == false))
			return true;
		elseif (((Tools::isSubmit('install') == false) || (Tools::isSubmit('reset') == false)) && ((bool)$result == false))
			return $this->setErrorMessage('An error occurred while trying to contact PrestaShop\'s cron tasks webservice.');
		elseif ($this->isLocalEnvironment() == true)
			return true;

		if ((bool)$use_webservice == true)
			return $this->setSuccessMessage('Your cron tasks have been successfully added to PrestaShop\'s cron tasks webservice.');
		return $this->setSuccessMessage('Your cron tasks have been successfully registered using the Advanced mode.');
	}

	protected function postProcessDeleteCronJob($id_cronjob)
	{
		$id_cronjob = Tools::getValue('id_cronjob');
		$id_module = Db::getInstance()->getValue('SELECT `id_module` FROM '._DB_PREFIX_.$this->name.' WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'');

		if ((bool)$id_module == false)
			Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.$this->name.' WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'');
		else
			Db::getInstance()->execute('UPDATE '._DB_PREFIX_.$this->name.' SET `active` = FALSE WHERE `id_cronjob` = \''.(int)$id_cronjob.'\'');

		return Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', false)
			.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name
			.'&token='.Tools::getAdminTokenLite('AdminModules'));
	}

	protected function registerModuleHook($id_module)
	{
		$module = Module::getInstanceById($id_module);
		$id_shop = (int)Context::getContext()->shop->id;
		$id_shop_group = (int)Context::getContext()->shop->id_shop_group;

		if (is_callable(array($module, 'getCronFrequency')) == true)
		{
			$frequency = $module->getCronFrequency();

			$query = 'INSERT INTO '._DB_PREFIX_.$this->name.'
				(`id_module`, `hour`, `day`, `month`, `day_of_week`, `active`, `id_shop`, `id_shop_group`)
				VALUES (\''.$id_module.'\', \''.$frequency['hour'].'\', \''.$frequency['day'].'\',
					\''.$frequency['month'].'\', \''.$frequency['day_of_week'].'\',
					TRUE, '.$id_shop.', '.$id_shop_group.')';
		}
		else
			$query = 'INSERT INTO '._DB_PREFIX_.$this->name.'
				(`id_module`, `active`, `id_shop`, `id_shop_group`)
				VALUES ('.$id_module.', FALSE, '.$id_shop.', '.$id_shop_group.')';

		return Db::getInstance()->execute($query);
	}

	protected function unregisterModuleHook($id_module)
	{
		return Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.$this->name.' WHERE `id_module` = \''.(int)$id_module.'\'');
	}
}


text:
require "active_batch/engine"
require "active_batch/batched_job"

module ActiveBatch
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.DataPipeline.Model
{
    /// <summary>
    /// <para>Contains the output from the ActivatePipeline action.</para>
    /// </summary>
    public class ActivatePipelineResult
    {

    }
}


text:
<?php
/*
Section: delete-account
Language: German
*/

$translations = array(
    'h1' => 'Account löschen',

    'mysql-username' => 'MySQL Benutzername',

    'mysql-user-password' => 'MySQL Benutzer-Passwort',

    'ph1' => 'Geben Sie Ihren MySQL Benutzernamen ein',

    'ph2' => 'Geben Sie Ihr MySQL Benutzer-Passwort ein',

    'error1' => 'Sie erhalten eine Email, um die Löschung Ihres Datenbank Accounts zu bestätigen!',

    'error2' => 'Der Benutzer existiert nicht!',

    'error3' => 'Das Passwort ist falsch!',
);
?>


text:
package liquid.order.domain;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by mat on 4/21/16.
 */
public enum OrderChangeItem {
    CONTAINER_QUANTITY("containerQty", "container.quantity");

    private final String fieldName;

    private final String i18nKey;

    private OrderChangeItem(String fieldName, String i18nKey) {
        this.fieldName = fieldName;
        this.i18nKey = i18nKey;
    }

    public String getFieldName() {
        return fieldName;
    }

    public String getI18nKey() {
        return i18nKey;
    }

    public static Map<String, String> toMap() {
        Map<String, String> map = new TreeMap<String, String>();
        OrderChangeItem[] items = values();
        for (OrderChangeItem item : items) {
            map.put(item.fieldName, item.i18nKey);
        }
        return map;
    }
 }


text:
from __future__ import absolute_import

from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
    String,
)
from openpyxl.descriptors.excel import Relation

class Hyperlink(Serialisable):

    tagname = "hyperlink"

    ref = String()
    location = String(allow_none=True)
    tooltip = String(allow_none=True)
    display = String(allow_none=True)
    id = Relation()
    target = String(allow_none=True)

    __attrs__ = ("ref", "location", "tooltip", "display", "id")

    def __init__(self,
                 ref=None,
                 location=None,
                 tooltip=None,
                 display=None,
                 id=None,
                 target=None,
                ):
        self.ref = ref
        self.location = location
        self.tooltip = tooltip
        self.display = display
        self.id = id
        self.target = target


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DotNetty.Transport.Channels.Sockets
{
    using System;
    using System.Diagnostics.Contracts;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Threading.Tasks;
    using DotNetty.Buffers;
    using DotNetty.Common.Concurrency;
    using DotNetty.Common.Utilities;

    public abstract class AbstractSocketChannel : AbstractChannel
    {
        [Flags]
        protected enum StateFlags
        {
            Open = 1,
            ReadScheduled = 1 << 1,
            WriteScheduled = 1 << 2,
            Active = 1 << 3
            // todo: add input shutdown and read pending here as well?
        }

        internal static readonly EventHandler<SocketAsyncEventArgs> IoCompletedCallback = OnIoCompleted;
        static readonly Action<object, object> ConnectCallbackAction = (u, e) => ((ISocketChannelUnsafe)u).FinishConnect((SocketChannelAsyncOperation)e);
        static readonly Action<object, object> ReadCallbackAction = (u, e) => ((ISocketChannelUnsafe)u).FinishRead((SocketChannelAsyncOperation)e);
        static readonly Action<object, object> WriteCallbackAction = (u, e) => ((ISocketChannelUnsafe)u).FinishWrite((SocketChannelAsyncOperation)e);

        protected readonly Socket Socket;
        SocketChannelAsyncOperation readOperation;
        SocketChannelAsyncOperation writeOperation;
        volatile bool inputShutdown;
        volatile bool readPending;
        volatile StateFlags state;

        TaskCompletionSource connectPromise;
        CancellationTokenSource connectCancellation;

        protected AbstractSocketChannel(IChannel parent, Socket socket)
            : base(parent)
        {
            this.Socket = socket;
            this.state = StateFlags.Open;

            try
            {
                this.Socket.Blocking = false;
            }
            catch (SocketException ex)
            {
                try
                {
                    socket.Close();
                }
                catch (SocketException ex2)
                {
                    if (ChannelEventSource.Log.IsWarningEnabled)
                    {
                        ChannelEventSource.Log.Warning("Failed to close a partially initialized socket.", ex2);
                    }
                }

                throw new ChannelException("Failed to enter non-blocking mode.", ex);
            }
        }

        public override bool Open
        {
            get { return this.IsInState(StateFlags.Open); }
        }

        public override bool Active
        {
            get { return this.IsInState(StateFlags.Active); }
        }

        protected bool ReadPending
        {
            get { return this.readPending; }
            set { this.readPending = value; }
        }

        protected bool InputShutdown
        {
            get { return this.inputShutdown; }
        }

        protected void ShutdownInput()
        {
            this.inputShutdown = true;
        }

        protected void SetState(StateFlags stateToSet)
        {
            this.state |= stateToSet;
        }

        protected bool ResetState(StateFlags stateToReset)
        {
            StateFlags oldState = this.state;
            if ((oldState & stateToReset) != 0)
            {
                this.state = oldState & ~stateToReset;
                return true;
            }
            return false;
        }

        protected bool IsInState(StateFlags stateToCheck)
        {
            return (this.state & stateToCheck) == stateToCheck;
        }

        protected SocketChannelAsyncOperation ReadOperation
        {
            get { return this.readOperation ?? (this.readOperation = new SocketChannelAsyncOperation(this, true)); }
        }

        protected SocketChannelAsyncOperation PrepareWriteOperation(IByteBuffer buffer)
        {
            SocketChannelAsyncOperation operation = this.writeOperation ?? (this.writeOperation = new SocketChannelAsyncOperation(this, false));
            if (!buffer.HasArray)
            {
                throw new NotImplementedException("IByteBuffer implementations not backed by array are currently not supported.");
            }
            operation.SetBuffer(buffer.Array, buffer.ArrayOffset + buffer.WriterIndex, buffer.WritableBytes);
            return operation;
        }

        protected void ResetWriteOperation()
        {
            SocketChannelAsyncOperation operation = this.writeOperation;
            Contract.Requires(operation != null);
            operation.SetBuffer(null, 0, 0);
        }

        /// <remarks>PORT NOTE: matches behavior of NioEventLoop.processSelectedKey</remarks>
        static void OnIoCompleted(object sender, SocketAsyncEventArgs args)
        {
            var operation = (SocketChannelAsyncOperation)args;
            AbstractSocketChannel channel = operation.Channel;
            var @unsafe = (ISocketChannelUnsafe)channel.Unsafe;
            IEventLoop eventLoop = channel.EventLoop;
            switch (args.LastOperation)
            {
                case SocketAsyncOperation.Accept:
                    if (eventLoop.InEventLoop)
                    {
                        @unsafe.FinishRead(operation);
                    }
                    else
                    {
                        eventLoop.Execute(ReadCallbackAction, @unsafe, operation);
                    }
                    break;
                case SocketAsyncOperation.Connect:
                    if (eventLoop.InEventLoop)
                    {
                        @unsafe.FinishConnect(operation);
                    }
                    else
                    {
                        eventLoop.Execute(ConnectCallbackAction, @unsafe, operation);
                    }
                    break;
                case SocketAsyncOperation.Receive:
                    if (eventLoop.InEventLoop)
                    {
                        @unsafe.FinishRead(operation);
                    }
                    else
                    {
                        eventLoop.Execute(ReadCallbackAction, @unsafe, operation);
                    }
                    break;
                case SocketAsyncOperation.Send:
                    if (eventLoop.InEventLoop)
                    {
                        @unsafe.FinishWrite(operation);
                    }
                    else
                    {
                        eventLoop.Execute(WriteCallbackAction, @unsafe, operation);
                    }
                    break;
                default:
                    // todo: think of a better way to comm exception
                    throw new ArgumentException("The last operation completed on the socket was not expected");
            }
        }

        internal interface ISocketChannelUnsafe : IChannelUnsafe
        {
            /// <summary>
            /// Finish connect
            /// </summary>
            void FinishConnect(SocketChannelAsyncOperation operation);

            /// <summary>
            /// Read from underlying {@link SelectableChannel}
            /// </summary>
            void FinishRead(SocketChannelAsyncOperation operation);

            void FinishWrite(SocketChannelAsyncOperation operation);
        }

        protected abstract class AbstractSocketUnsafe : AbstractUnsafe, ISocketChannelUnsafe
        {
            protected AbstractSocketUnsafe(AbstractSocketChannel channel)
                : base(channel)
            {
            }

            public AbstractSocketChannel Channel
            {
                get { return (AbstractSocketChannel)this.channel; }
            }

            public override sealed Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress)
            {
                // todo: handle cancellation
                AbstractSocketChannel ch = this.Channel;
                if (!ch.Open)
                {
                    return this.CreateClosedChannelExceptionTask();
                }

                try
                {
                    if (ch.connectPromise != null)
                    {
                        throw new InvalidOperationException("connection attempt already made");
                    }

                    bool wasActive = this.channel.Active;
                    if (ch.DoConnect(remoteAddress, localAddress))
                    {
                        this.FulfillConnectPromise(wasActive);
                        return TaskEx.Completed;
                    }
                    else
                    {
                        ch.connectPromise = new TaskCompletionSource(remoteAddress);

                        // Schedule connect timeout.
                        TimeSpan connectTimeout = ch.Configuration.ConnectTimeout;
                        if (connectTimeout > TimeSpan.Zero)
                        {
                            CancellationTokenSource cts = ch.connectCancellation = new CancellationTokenSource();

                            ch.EventLoop.Schedule(
                                c =>
                                {
                                    // todo: make static / cache delegate?..
                                    var self = (AbstractSocketChannel)c;
                                    // todo: call Socket.CancelConnectAsync(...)
                                    TaskCompletionSource promise = ch.connectPromise;
                                    var cause =
                                        new ConnectTimeoutException("connection timed out: " + remoteAddress);
                                    if (promise != null && promise.TrySetException(cause))
                                    {
                                        self.CloseAsync();
                                    }
                                },
                                this.channel,
                                connectTimeout,
                                cts.Token);
                        }

                        ch.connectPromise.Task.ContinueWith(t =>
                        {
                            if (ch.connectCancellation != null)
                            {
                                ch.connectCancellation.Cancel();
                            }
                            ch.connectPromise = null;
                            this.channel.CloseAsync();
                        },
                            TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously);

                        return ch.connectPromise.Task;
                    }
                }
                catch (Exception ex)
                {
                    this.CloseIfClosed();
                    return TaskEx.FromException(this.AnnotateConnectException(ex, remoteAddress));
                }
            }

            void FulfillConnectPromise(bool wasActive)
            {
                TaskCompletionSource promise = this.Channel.connectPromise;
                if (promise == null)
                {
                    // Closed via cancellation and the promise has been notified already.
                    return;
                }

                // trySuccess() will return false if a user cancelled the connection attempt.
                bool promiseSet = promise.TryComplete();

                // Regardless if the connection attempt was cancelled, channelActive() event should be triggered,
                // because what happened is what happened.
                if (!wasActive && this.channel.Active)
                {
                    this.channel.Pipeline.FireChannelActive();
                }

                // If a user cancelled the connection attempt, close the channel, which is followed by channelInactive().
                if (!promiseSet)
                {
                    this.CloseAsync();
                }
            }

            void FulfillConnectPromise(Exception cause)
            {
                TaskCompletionSource promise = this.Channel.connectPromise;
                if (promise == null)
                {
                    // Closed via cancellation and the promise has been notified already.
                    return;
                }

                // Use tryFailure() instead of setFailure() to avoid the race against cancel().
                promise.TrySetException(cause);
                this.CloseIfClosed();
            }

            public void FinishConnect(SocketChannelAsyncOperation operation)
            {
                Contract.Assert(this.channel.EventLoop.InEventLoop);

                AbstractSocketChannel ch = this.Channel;
                try
                {
                    bool wasActive = ch.Active;
                    ch.DoFinishConnect(operation);
                    this.FulfillConnectPromise(wasActive);
                }
                catch (Exception ex)
                {
                    TaskCompletionSource promise = ch.connectPromise;
                    EndPoint remoteAddress = promise == null ? null : (EndPoint)promise.Task.AsyncState;
                    this.FulfillConnectPromise(this.AnnotateConnectException(ex, remoteAddress));
                }
                finally
                {
                    // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is used
                    // See https://github.com/netty/netty/issues/1770
                    if (ch.connectCancellation != null)
                    {
                        ch.connectCancellation.Cancel();
                    }
                    ch.connectPromise = null;
                }
            }

            public abstract void FinishRead(SocketChannelAsyncOperation operation);

            protected override sealed void Flush0()
            {
                // Flush immediately only when there's no pending flush.
                // If there's a pending flush operation, event loop will call FinishWrite() later,
                // and thus there's no need to call it now.
                if (this.IsFlushPending())
                {
                    return;
                }
                base.Flush0();
            }

            public void FinishWrite(SocketChannelAsyncOperation operation)
            {
                ChannelOutboundBuffer input = this.OutboundBuffer;
                try
                {
                    operation.Validate();
                    int sent = operation.BytesTransferred;
                    this.Channel.ResetWriteOperation();
                    if (sent > 0)
                    {
                        object msg = input.Current;
                        var buffer = msg as IByteBuffer;
                        if (buffer != null)
                        {
                            buffer.SetWriterIndex(buffer.WriterIndex + sent);
                        }
                        // todo: FileRegion support
                    }
                }
                catch (Exception ex)
                {
                    input.FailFlushed(ex, true);
                    throw;
                }

                // directly call super.flush0() to force a flush now
                base.Flush0();
            }

            bool IsFlushPending()
            {
                return this.Channel.IsInState(StateFlags.WriteScheduled);
            }
        }

        protected override bool IsCompatible(IEventLoop eventLoop)
        {
            return true;
        }

        protected override void DoBeginRead()
        {
            if (this.inputShutdown)
            {
                return;
            }

            if (!this.Open)
            {
                return;
            }

            this.readPending = true;

            if (!this.IsInState(StateFlags.ReadScheduled))
            {
                this.state |= StateFlags.ReadScheduled;
                this.ScheduleSocketRead();
            }
        }

        protected abstract void ScheduleSocketRead();

        /// <summary>
        ///  Connect to the remote peer
        /// </summary>
        protected abstract bool DoConnect(EndPoint remoteAddress, EndPoint localAddress);

        /// <summary>
        /// Finish the connect
        /// </summary>
        protected abstract void DoFinishConnect(SocketChannelAsyncOperation operation);

        protected override void DoClose()
        {
            TaskCompletionSource promise = this.connectPromise;
            if (promise != null)
            {
                // Use TrySetException() instead of SetException() to avoid the race against cancellation due to timeout.
                promise.TrySetException(ClosedChannelException);
                this.connectPromise = null;
            }

            CancellationTokenSource cancellation = this.connectCancellation;
            if (cancellation != null)
            {
                cancellation.Cancel();
                this.connectCancellation = null;
            }
        }
    }
}


text:
import vtk

def main():
    colors = vtk.vtkNamedColors()

    # Create an image
    source1 = vtk.vtkImageCanvasSource2D()
    source1.SetScalarTypeToUnsignedChar()
    source1.SetNumberOfScalarComponents(3)
    source1.SetExtent(0, 100, 0, 100, 0, 0)
    source1.SetDrawColor(0,0,0,1)
    source1.FillBox(0, 100, 0, 100)
    source1.SetDrawColor(255,0,0,1)
    source1.FillBox(10, 20, 10, 20)
    source1.FillBox(40, 50, 20, 30)
    source1.Update()

    # Convert the image to a polydata
    imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter()
    imageDataGeometryFilter.SetInputConnection(source1.GetOutputPort())
    imageDataGeometryFilter.Update()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Visualization
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("white")) # Background color white
    renderWindow.Render()
    renderWindowInteractor.Start()

if __name__ == '__main__':
    main()


text:
<?php
print "
Settings: Movement Configurations
";
?>

<?php print wtheadline('Movement behavior', 'can be fine tuned to suit your needs. Many of the configurations deal with speed, timing, force, and friction which help determine the behavior of the physical or non-physical breed object.'); ?>

Movement Essentials

        	<?php print breedSetting(
		'Frequency of move attempts in seconds',
		'1.2',
		'This value sets the frequency of move attempts in seconds. For each move attempt, the breed will rotate and move towards the destination vector based on the movement behavior defined.'
		);?>
        	<?php print breedSetting(
		'Max attempts to reach it\'s destination',
		'-1',
		'The maximum number of attempts the breed can use to reach it\'s destination for each movement request. If the limit has been reached, the breed calls the arrived callback (if defined) for the move() method. You may set this to \'-1\' to allow an unlimited number of movement attempts for it to reach it\'s destination.'
		);?>
        	<?php print breedSetting(
		'Distance in meters from target destination',
		'2.0',
		'This value defines the distance in meters for how close a breed must be to it\'s target destination before calling the arrived callback.'
		);?>

Restrictions

        	<?php print breedSetting(
		'Use legacy prim system',
		'YES',
		'To use the \'nonphys\' and \'nonphysUp\' movement behaviors, which rely on llSetKeyframedMotion() to provide smooth non-physical movement, Legacy Prims must be disabled otherwise attempts to use these behaviors result in the default \'setpos\' movement. Set to NO for mesh support.'
		);?>
        	<?php print breedSetting(
		'Remain physical after physical movement',
		'NO',
		'This value defines the physics status after a physical movement. If NO, the physics are disabled after movement. If true, the breed object remains physical.'
		);?>
        	<?php print breedSetting(
		'Finish move before accepting new move requests',
		'NO',
		'In order to ensure breeds finish their move to their destination vector before accepting new move requests, set this value to YES. It will ignore new requests until the destination has been reached. Otherwise set this to NO to allow the movement to be interupted and redirected to a new destination or with new movement behavior.'
		);?>
        	<?php print breedSetting(
		'Allow breed to drift beyond it\'s destination',
		'NO',
		'This filter determines if a breed can move beyond it\'s destination if it arrives or comes within the margin of error (Target_Dist_Min) between movements as defined by the Move_Timer. The distance to the destination vector is checked twice during movement cycles, once as soon as the cycle occurs, and a second time when the movement occurs. This value, when enabled, blocks the first filter which results in an unconstrained movement towards the destination vector and is vital for a smooth transition between multiple destination vectors. When set to YES, the breed will more seamlessly glide through assigned destinations; less precise, more smooth.'
		);?>
        	<?php print breedSetting(
		'Each move attempt will trigger a synced animation',
		'NO',
		'If an animation is linked to the move() type, the animation is triggered once when movement begins (good for animations that are set to repeat) and stops the animation when the move() is completed. If this value is set to YES, each move attempt will trigger the animation.'
		);?>

Fine Tuning

        	<?php print breedSetting(
		'Turning Speed',
		'0.2',
		'The strength of the turning behavior is represented by efficiency and time. A lower efficiency value indicates a stronger turn, while a higher value will result in a more realistic and slightly more rounded turn. If the value is too high, the breed may not reach it\'s rotational target by the time it reaches it\'s linear destination, thus causing it to circle around the destination position endlessly.'
		);?>
        	<?php print breedSetting(
		'Turning Time',
		'0.2',
		'The time in seconds it takes the breed to reach it\'s rotational target based on the efficiency of the turn and the speed of the Move Timer and forward velocity.');?>
        	<?php print breedSetting(
		'Prim Material',
		'FLESH',
		'The object\'s "prim material" is how the physics engine determines how the physical object reacts to other primsets, avatars, and terrain.
OPTIONS: Stone, Metal, Glass, Wood, Flesh, Plastic, Rubber');?>
        	<?php print breedSetting(
		'Ground Friction',
		'0.2',
		'Friction applied to "walk" and "run" movement types.
  0.0 = Full Friction | >0.0 = Less Friction');?>
        	<?php print breedSetting(
		'Slope Offset',
		'0.5',
		'This offset gives you control over the AVOID_SLOPES flag for the move() method. This flag only detects inclines that are greater than the breed-object\'s geometric center plus this offset. If the incline is greater than this height, the breed will not attempt to move to that destination, instead calling the avoid callback defined within the method, otherwise silently fails.');?>
        	<?php print breedSetting(
		'Water Timeout',
		'5',
		'This value is only used with the \'swim\' movement behavior which acts as an occurance counter that counts the number of move attempts (defined by the frequency of the Move Timer) while the breed is out of the water. In plain english, this value multiplied by the Move Timer is the time in seconds the breed is allowed to be out of the water before \'water_end\' event is raised. If the throttle is not reached before being resubmerged, the throttle count is reset.');?>

Under the Hood

        	<?php print breedSetting(
		'Speed : setpos',
		'0.7',
		'This is the default movement behavior for undefined or unrecognized movement attributes. This is non-physical, incremental movement defined not by speed but in distance the breed travels per each increment, no further than 10 meters. For long, rapid re-positioning, use \'warp\'. To define how fast the increments occur, set the Move Timer. This movement type is 2 dimensional meaning it doesn\'t go up or down, but parallel to it\'s starting vertical position despite it\'s environment.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Speed : nonphys',
		'3.5',
		'This is a non-physical movement type which uses llSetKeyframedMotion() to provide a smooth move behavior. This value is the time in seconds for the breed to reach it\'s destination, thus a lower value equals faster movement. Requires Legacy Prims to be disabled.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Speed : nonphysUp',
		'3.5',
		'This is a similar movement behavior to \'nonphys\' but allows the breed to look up/down towards it\'s destination where \'nonphys\' points forwards at all times.',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : walk',
		'4',
		'The \'walk\' is the default ground movement behavior which responds to physical gravity of the object\'s mass, a higher speed will be required for larger breeds, especially when traversing rough terrain or steep inclines.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : walk',
		'0.8',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : run',
		'8',
		'The \'run\' movement behavior is the same as \'walk\' but gives an alternately faster movement without having to define a speed value in the move() method.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : run',
		'0.8',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : hop',
		'8',
		'The \'hop\' movement behavior moves at half speed/distance as \'walk\' with same speed value but pushes the breed vertically at full speed creating a hopping behavior which moves full force upwards and half force forwards.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : hop',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : jump',
		'15',
		'The \'jump\' movement behavior is the same as \'hop\' but gives an alternately faster movement without having to define a speed value in the move() method.',
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : jump',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : swim',
		'5',
		"The 'swim' movement type is an underwater swimming behavior influenced strictly by region water, when the surface of the water is breached the buoyancy is decreased, thus applying additional gravity to keep it in the water. The recovery time between breach and re-submergence is defined by Move Timer. When a breach occurs, a counter tracks the number of cycles based on Move Timer, when those cycles reach or exceed the 'thottle_water_start' condition, the 'water_end' event is raised, thus allowing for alternate functionality for dealing with being out of the water. Once this event is raised, if the breed is resubmerged, the 'water_start' event is raised and the throttle cycles are reset. Additional events 'water' and 'land' exist for non-swim related environmental conditions, however the natived 'water_start' and 'water_end' with throttles are more suited for the 'swim' movement type.",
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : swim',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : hover',
		'2',
		"The 'hover' movement type is a three dimensional motion useful as a slower version of 'fly' with the same gravity and angular behavior.",
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : hover',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : fly',
		'5.5',
		"The 'fly' movement behavior is the same as 'hover' but gives an alternately faster movement without having to define a speed value in the move() method.",
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : fly',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>

        	<?php print breedSetting(
		'Speed : float',
		'3.5',
		"The 'float' movement behaves like a boat, where it floats on the surface of the water. It has a hover height equal to the height of the linkset's geometric center. The behavior will limit the breed from being submerged in the water, and is useful for forcing breeds to tread water when a 'water' event is raised to keep them from sinking. This motion type is effective on land but with slightly different angular behavior than a 'walk' movement type.",
		'',
		''
		);?>
        	<?php print breedSetting(
		'Gravity : float',
		'0.0',
		'Additional gravity modifier applied to this behavior. ',
		'',
		''
		);?>


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('monitorings', '0009_auto_20160509_0151'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='monitoringinstitution',
            unique_together=set([('monitoring', 'institution')]),
        ),
    ]


text:
namespace Nuterra.Build.ModuleImport
{
	internal class dnSpy_AsmEditor_Resources
	{
		public static string ERR_IM_CouldNotFindEditedMethod { get; internal set; } = "ERR_IM_CouldNotFindEditedMethod";
		public static string ERR_IM_CouldNotFindEditedType { get; internal set; } = "ERR_IM_CouldNotFindEditedType";
		public static string ERR_IM_CouldNotFindField { get; internal set; } = "ERR_IM_CouldNotFindField";
		public static string ERR_IM_CouldNotFindMethod { get; internal set; } = "ERR_IM_CouldNotFindMethod";
		public static string ERR_IM_CouldNotFindMethodType { get; internal set; } = "ERR_IM_CouldNotFindMethodType";
		public static string ERR_IM_CouldNotFindType { get; internal set; } = "ERR_IM_CouldNotFindType";
		public static string ERR_IM_RenamingVirtualEventsIsNotSupported { get; internal set; } = "ERR_IM_RenamingVirtualEventsIsNotSupported";
		public static string ERR_IM_RenamingVirtualMethodsIsNotSupported { get; internal set; } = "ERR_IM_RenamingVirtualMethodsIsNotSupported";
		public static string ERR_IM_RenamingVirtualPropsIsNotSupported { get; internal set; } = "ERR_IM_RenamingVirtualPropsIsNotSupported";
	}
}


text:
SYNONYM

#### According to
IRMNG Homonym List

#### Published in
J. Phys. , Chém. , Hist. Nat. & Arts 94: 175.

#### Original name
null

### Remarks
null


text:
package com.intellij.codeInsight.daemon.impl;

import com.intellij.ProjectTopics;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.hint.TooltipController;
import com.intellij.ide.PowerSaveMode;
import com.intellij.ide.todo.TodoConfiguration;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.command.CommandAdapter;
import com.intellij.openapi.command.CommandEvent;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.roots.ModuleRootEvent;
import com.intellij.openapi.roots.ModuleRootListener;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFilePropertyEvent;
import com.intellij.profile.Profile;
import com.intellij.profile.ProfileChangeAdapter;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author cdr
 */
class DaemonListeners implements Disposable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.DaemonListeners");

  private final Project myProject;
  private final DaemonCodeAnalyzerImpl myDaemonCodeAnalyzer;

  private boolean myEscPressed;

  private volatile boolean cutOperationJustHappened;
  private final EditorTracker myEditorTracker;

  public DaemonListeners(Project project, DaemonCodeAnalyzerImpl daemonCodeAnalyzer, EditorTracker editorTracker) {
    myProject = project;
    myDaemonCodeAnalyzer = daemonCodeAnalyzer;

    final MessageBusConnection connection = myProject.getMessageBus().connect();
    EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();

    eventMulticaster.addDocumentListener(new DocumentAdapter() {
      // clearing highlighters before changing document because change can damage editor highlighters drastically, so we'll clear more than necessary
      public void beforeDocumentChange(final DocumentEvent e) {
        if (isUnderIgnoredAction(null)) return;
        Document document = e.getDocument();
        VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
        Project project = virtualFile == null ? null : ProjectUtil.guessProjectForFile(virtualFile);
        if (!worthBothering(document, project)) {
          return; //no need to stop daemon if something happened in the console
        }
        stopDaemon(true);
        UpdateHighlightersUtil.updateHighlightersByTyping(myProject, e);
      }
    }, this);

    eventMulticaster.addCaretListener(new CaretListener() {
      public void caretPositionChanged(CaretEvent e) {
        Editor editor = e.getEditor();
        if (!worthBothering(editor.getDocument(), editor.getProject())) {
          return; //no need to stop daemon if something happened in the console
        }

        stopDaemon(true);
        myDaemonCodeAnalyzer.hideLastIntentionHint();
      }
    }, this);

    eventMulticaster.addEditorMouseMotionListener(new MyEditorMouseMotionListener(), this);
    eventMulticaster.addEditorMouseListener(new MyEditorMouseListener(), this);

    myEditorTracker = editorTracker;
    EditorTrackerListener editorTrackerListener = new EditorTrackerListener() {
      private List<Editor> myActiveEditors = Collections.emptyList();
      public void activeEditorsChanged(@NotNull List<Editor> editors) {
        List<Editor> activeEditors = myEditorTracker.getActiveEditors();
        if (!myActiveEditors.equals(activeEditors)) {
          myActiveEditors = activeEditors;
          stopDaemon(true);  // do not stop daemon if idea loses/gains focus
          if (LaterInvocator.isInModalContext()) {
            // editor appear in modal context, reenable the daemon
            myDaemonCodeAnalyzer.setUpdateByTimerEnabled(true);
          }
        }
      }
    };
    myEditorTracker.addEditorTrackerListener(editorTrackerListener, this);

    EditorFactoryListener editorFactoryListener = new EditorFactoryAdapter() {
      public void editorCreated(EditorFactoryEvent event) {
        Editor editor = event.getEditor();
        Document document = editor.getDocument();
        if (!worthBothering(document, editor.getProject())) {
          return;
        }
        myDaemonCodeAnalyzer.repaintErrorStripeRenderer(editor);
      }
    };
    EditorFactory.getInstance().addEditorFactoryListener(editorFactoryListener, this);

    PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(myProject);
    PsiChangeHandler changeHandler = new PsiChangeHandler(myProject, documentManager, EditorFactory.getInstance(),connection,
                                                          daemonCodeAnalyzer.getFileStatusMap());
    Disposer.register(this, changeHandler);
    PsiManager.getInstance(myProject).addPsiTreeChangeListener(changeHandler, changeHandler);

    connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() {
      public void beforeRootsChange(ModuleRootEvent event) {
      }

      public void rootsChanged(ModuleRootEvent event) {
        final FileEditor[] editors = FileEditorManager.getInstance(myProject).getSelectedEditors();
        if (editors.length == 0) return;
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          public void run() {
            if (myProject.isDisposed()) return;
            for (FileEditor fileEditor : editors) {
              if (fileEditor instanceof TextEditor) {
                myDaemonCodeAnalyzer.repaintErrorStripeRenderer(((TextEditor)fileEditor).getEditor());
              }
            }
          }
        }, ModalityState.stateForComponent(editors[0].getComponent()));
      }
    });

    connection.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
      public void enteredDumbMode() {
        myDaemonCodeAnalyzer.restart();
      }

      public void exitDumbMode() {
        myDaemonCodeAnalyzer.restart();
      }
    });

    connection.subscribe(PowerSaveMode.TOPIC, new PowerSaveMode.Listener() {
      @Override
      public void powerSaveStateChanged() {
        stopDaemon(true);
      }
    });

    CommandProcessor.getInstance().addCommandListener(new MyCommandListener(), this);
    ApplicationListener applicationListener = new MyApplicationListener();
    ApplicationManager.getApplication().addApplicationListener(applicationListener, this);
    EditorColorsManager.getInstance().addEditorColorsListener(new MyEditorColorsListener(),this);
    InspectionProfileManager.getInstance().addProfileChangeListener(new MyProfileChangeListener(), this);
    TodoConfiguration.getInstance().addPropertyChangeListener(new MyTodoListener(), this);
    ActionManagerEx.getInstanceEx().addAnActionListener(new MyAnActionListener(), this);
    VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
      public void propertyChanged(VirtualFilePropertyEvent event) {
        String propertyName = event.getPropertyName();
        if (VirtualFile.PROP_NAME.equals(propertyName)) {
          myDaemonCodeAnalyzer.restart();
          PsiFile psiFile = PsiManager.getInstance(myProject).findFile(event.getFile());
          if (psiFile != null && !myDaemonCodeAnalyzer.isHighlightingAvailable(psiFile)) {
            Document document = FileDocumentManager.getInstance().getCachedDocument(event.getFile());
            if (document != null) {
              // highlight markers no more
              //todo clear all highlights regardless the pass id

              // Here color scheme required for TextEditorFields, as far as I understand this
              // code related to standard file editors, which always use Global color scheme,
              // thus we can pass null here.
              final EditorColorsScheme editorColorScheme = null;

              UpdateHighlightersUtil.setHighlightersToEditor(myProject, document, 0, document.getTextLength(),
                                                             Collections.<HighlightInfo>emptyList(),
                                                             editorColorScheme,
                                                             Pass.UPDATE_ALL);
            }
          }
        }
        if (!propertyName.equals(PsiTreeChangeEvent.PROP_WRITABLE)) {
          stopDaemon(true);
        }
      }
    }, this);

    ((EditorEventMulticasterEx)eventMulticaster).addErrorStripeListener(new ErrorStripeHandler(myProject), this);

    final NamedScopesHolder[] holders = NamedScopesHolder.getAllNamedScopeHolders(project);
    NamedScopesHolder.ScopeListener scopeListener = new NamedScopesHolder.ScopeListener() {
      public void scopesChanged() {
        myDaemonCodeAnalyzer.reloadScopes();
      }
    };
    for (NamedScopesHolder holder : holders) {
      holder.addScopeListener(scopeListener);
    }

    ModalityStateListener modalityStateListener = new ModalityStateListener() {
      public void beforeModalityStateChanged(boolean entering) {
        // before showing dialog we are in non-modal context yet, and before closing dialog we are still in modal context
        boolean inModalContext = LaterInvocator.isInModalContext();
        stopDaemon(inModalContext);
        myDaemonCodeAnalyzer.setUpdateByTimerEnabled(inModalContext);
      }
    };
    LaterInvocator.addModalityStateListener(modalityStateListener,this);
  }

  static boolean isUnderIgnoredAction(Object action) {
    if (action instanceof DocumentRunnable.IgnoreDocumentRunnable) return true;
    DocumentRunnable currentWriteAction = ApplicationManager.getApplication().getCurrentWriteAction(DocumentRunnable.IgnoreDocumentRunnable.class);
    return currentWriteAction instanceof DocumentRunnable.IgnoreDocumentRunnable;
  }

  private boolean worthBothering(final Document document, Project project) {
    if (document == null) return true;
    if (project != null && project != myProject) return false;
    // cached is essential here since we do not want to create PSI file in alien project
    PsiFile psiFile = PsiDocumentManager.getInstance(project == null ? myProject : project).getCachedPsiFile(document);
    return psiFile != null;
  }

  public void dispose() {
  }

  boolean canChangeFileSilently(PsiFileSystemItem file) {
    if (cutOperationJustHappened) return false;
    VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return false;
    if (file instanceof PsiCodeFragment) return true;
    Project project = file.getProject();
    if (!ModuleUtil.projectContainsFile(project, virtualFile, false)) return false;
    Result vcs = vcsThinksItChanged(virtualFile, project);
    if (vcs == Result.CHANGED) return true;
    if (vcs == Result.UNCHANGED) return false;

    return canUndo(virtualFile);
  }

  private boolean canUndo(VirtualFile virtualFile) {
    for (FileEditor editor : FileEditorManager.getInstance(myProject).getEditors(virtualFile)) {
      if (UndoManager.getInstance(myProject).isUndoAvailable(editor)) return true;
    }
    return false;
  }

  private static enum Result {
    CHANGED, UNCHANGED, NOT_SURE
  }
  private Result vcsThinksItChanged(VirtualFile virtualFile, Project project) {
    AbstractVcs activeVcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(virtualFile);
    if (activeVcs == null) return Result.NOT_SURE;

    FilePath path = new FilePathImpl(virtualFile);
    boolean vcsIsThinking = !VcsDirtyScopeManager.getInstance(myProject).whatFilesDirty(Arrays.asList(path)).isEmpty();
    if (vcsIsThinking) return Result.UNCHANGED; // do not modify file which is in the process of updating

    FileStatus status = FileStatusManager.getInstance(project).getStatus(virtualFile);
    if (status == FileStatus.UNKNOWN) return Result.NOT_SURE;
    return status == FileStatus.MODIFIED || status == FileStatus.ADDED ? Result.CHANGED : Result.UNCHANGED;
  }

  private class MyApplicationListener extends ApplicationAdapter {
    private boolean myDaemonWasRunning;

    public void beforeWriteActionStart(Object action) {
      myDaemonWasRunning = myDaemonCodeAnalyzer.isRunning();
      if (!myDaemonWasRunning) return; // we'll restart in writeActionFinished()
      stopDaemon(true);
    }

    public void writeActionFinished(Object action) {
      if (myDaemonWasRunning) {
        stopDaemon(true);
      }
    }
  }

  private class MyCommandListener extends CommandAdapter {
    private final Object myCutActionName =
      ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_CUT).getTemplatePresentation().getText();

    public void commandStarted(CommandEvent event) {
      Document affectedDocument = extractDocumentFromCommand(event);
      if (isUnderIgnoredAction(null)) return;
      if (!worthBothering(affectedDocument, event.getProject())) return;

      cutOperationJustHappened = myCutActionName.equals(event.getCommandName());
      if (!myDaemonCodeAnalyzer.isRunning()) return;
      if (LOG.isDebugEnabled()) {
        LOG.debug("cancelling code highlighting by command:" + event.getCommand());
      }
      stopDaemon(false);
    }

    private Document extractDocumentFromCommand(CommandEvent event) {
      Document affectedDocument = event.getDocument();
      if (affectedDocument != null) return affectedDocument;
      Object id = event.getCommandGroupId();

      if (id instanceof Document) {
        affectedDocument = (Document)id;
      }
      else if (id instanceof DocCommandGroupId) {
        affectedDocument = ((DocCommandGroupId)id).getDocument();
      }
      return affectedDocument;
    }

    public void commandFinished(CommandEvent event) {
      Document affectedDocument = extractDocumentFromCommand(event);
      if (isUnderIgnoredAction(null)) return;
      if (!worthBothering(affectedDocument, event.getProject())) return;

      if (myEscPressed) {
        myEscPressed = false;
        if (affectedDocument != null) {
          // prevent Esc key to leave the document in the not-highlighted state
          if (!myDaemonCodeAnalyzer.getFileStatusMap().allDirtyScopesAreNull(affectedDocument)) {
            stopDaemon(true);
          }
        }
      }
      else if (!myDaemonCodeAnalyzer.isRunning()) {
        stopDaemon(true);
      }
    }
  }

  private class MyEditorColorsListener implements EditorColorsListener {
    public void globalSchemeChange(EditorColorsScheme scheme) {
      myDaemonCodeAnalyzer.restart();
    }
  }

  private class MyTodoListener implements PropertyChangeListener {
    public void propertyChange(PropertyChangeEvent evt) {
      if (TodoConfiguration.PROP_TODO_PATTERNS.equals(evt.getPropertyName())) {
        myDaemonCodeAnalyzer.restart();
      }
    }
  }

  private class MyProfileChangeListener extends ProfileChangeAdapter {
    public void profileChanged(Profile profile) {
      myDaemonCodeAnalyzer.restart();
    }

    public void profileActivated(Profile oldProfile, Profile profile) {
      myDaemonCodeAnalyzer.restart();
    }
  }

  private class MyAnActionListener implements AnActionListener {
    private final AnAction escapeAction = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_ESCAPE);

    public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
      myEscPressed = action == escapeAction;
    }

    public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
    }

    public void beforeEditorTyping(char c, DataContext dataContext) {
      Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
      //no need to stop daemon if something happened in the console
      if (editor != null && !worthBothering(editor.getDocument(), editor.getProject())) {
        return;
      }
      stopDaemon(true);
    }
  }

  private static class MyEditorMouseListener extends EditorMouseAdapter {

    public void mouseExited(EditorMouseEvent e) {
      if (!TooltipController.getInstance().shouldSurvive(e.getMouseEvent())) {
        DaemonTooltipUtil.cancelTooltips();
      }
    }
  }

  private class MyEditorMouseMotionListener implements EditorMouseMotionListener {
    public void mouseMoved(EditorMouseEvent e) {
      Editor editor = e.getEditor();
      if (myProject != editor.getProject()) return;

      boolean shown = false;
      try {
        // There is a possible case that cursor is located at soft wrap-introduced virtual space (that is mapped to offset
        // of the document symbol just after soft wrap). We don't want to show any tooltips for it then.
        VisualPosition visual = editor.xyToVisualPosition(e.getMouseEvent().getPoint());
        if (editor.getSoftWrapModel().isInsideOrBeforeSoftWrap(visual)) {
          return;
        }
        LogicalPosition logical = editor.visualToLogicalPosition(visual);
        if (e.getArea() == EditorMouseEventArea.EDITING_AREA && !UIUtil.isControlKeyDown(e.getMouseEvent())) {
          int offset = editor.logicalPositionToOffset(logical);
          if (editor.offsetToLogicalPosition(offset).column != logical.column) return; // we are in virtual space
          HighlightInfo info = myDaemonCodeAnalyzer.findHighlightByOffset(editor.getDocument(), offset, false);
          if (info == null || info.description == null) return;
          DaemonTooltipUtil.showInfoTooltip(info, editor, offset);
          shown = true;
        }
      }
      finally {
        if (!shown && !TooltipController.getInstance().shouldSurvive(e.getMouseEvent())) {
          DaemonTooltipUtil.cancelTooltips();
        }
      }
    }

    public void mouseDragged(EditorMouseEvent e) {
      TooltipController.getInstance().cancelTooltips();
    }
  }

  private void stopDaemon(boolean toRestartAlarm) {
    myDaemonCodeAnalyzer.stopProcess(toRestartAlarm);
  }

  Collection<FileEditor> getSelectedEditors() {
    // Editors in modal context
    List<Editor> editors = myEditorTracker.getActiveEditors();

    Collection<FileEditor> activeFileEditors = new THashSet<FileEditor>(editors.size());
    for (Editor editor : editors) {
      TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
      activeFileEditors.add(textEditor);
    }
    if (ApplicationManager.getApplication().getCurrentModalityState() != ModalityState.NON_MODAL) {
      return activeFileEditors;
    }

    // Editors in tabs.
    Collection<FileEditor> result = new THashSet<FileEditor>();
    Collection<Document> documents = new THashSet<Document>(activeFileEditors.size());
    final FileEditor[] tabEditors = FileEditorManager.getInstance(myProject).getSelectedEditors();
    for (FileEditor tabEditor : tabEditors) {
      if (tabEditor instanceof TextEditor) {
        documents.add(((TextEditor)tabEditor).getEditor().getDocument());
      }
      result.add(tabEditor);
    }
    // do not duplicate documents
    for (FileEditor fileEditor : activeFileEditors) {
      if (fileEditor instanceof TextEditor && documents.contains(((TextEditor)fileEditor).getEditor().getDocument())) continue;
      result.add(fileEditor);
    }
    return result;
  }
}


text:
import getCommands from '../config/commands';

export default app => new Promise((resolve) => {
  app.set('port', getCommands().port || 8000);
  resolve({});
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<document>
    <properties>
        <author email="ian@caret.cam.ac.uk">Ian Boston</author>
        <title>RWiki Software Requirements Specification</title>
    </properties>

                Please note, this document is in draft and constantly evolving. The current release in 2.0.
                The next release will be 2.1. You should look to JIRA to see which of the features in the
                roadmap will be in the 2.1 release.

                Cut and paste required

            <subsection name="1.5 Release Feature List">

Wiki Markup

 Radeox wiki markup (as in SnipSnap)

 Radeox Macros ( eg image, rss etc) extensible

 Sakai integration

 knows about user, realm and site.

 will access sakai resources

 Spaces, like Snips in SnipSnap

 automatic default space is created named by SiteID

 all pages with no specific space id, are assumed to be in the same
                                space as the parent page

 Subspaces may be generated

 Cross worksite spaces may be generated

 pages may be shared between worksites.

 Permissions

 Space persmissions derived from Site Realms and Roles.

 Addition per page permissions on each page.

 Allows complete public anon view of pages if selected.

 Sakai Tool integration

 Resources may be included into pages (images are rendered)

Rendered output of any tool in work site ( to be implemented)

 Wikipage navigation

 Current tool generates breadcrumbs as a stack of pages you have
                                recently seen. A page can only appear once in this list, and hence
                                if you go back to a previous page it is removed from the list and
                                re-inserted at the end.

 Breadcrumbs contain links to previous searches.

 Searches are performed on page name and on full-text search.

 Searches should be restricted to only pages that you can see.

            </subsection>

                   This section outlines the requirements that were addressed by the 2.0 release.

                <subsection name="Sakai 2.0.x" >

                        Must use a Sakai 2.0.x build mechanism and deploy into sakai 2.0.0 or 2.0.1.

                </subsection>
                <subsection name="Architecture" >

                        The archtetecture needs to be reviewed to achieve a lower memory overhead with a
                        higher page serving performance. Pages should typically be served in < 50ms on
                        a low end PowerBook (eg 1.3GHz G4). The architecture should be structured in a service
                        oriented way to eliminate heavy object consumption as part of the request cycle.

                </subsection>
                <subsection name="Markup" >

                        The implemented markup is based on Radeox, which a simplified version of the
                        markup found in SnipSnap. Most of the complex macros seen in SnipSnap are not present (eg Blogs).
                        All of the standard markup (linking and formatting) is present.

                </subsection>
                <subsection name="Optimistic Locking" >

                        The aim of optimistic locking is to allow users to edit a page without
                        unduley risking overwriting someone elses work. If user A starts editing a
                        page, then user B edits and saves the same page, user A, when they save their
                        changes could overwrite user B's edits. With optimistic locking user A is notified that
                        user B has made changes whilst user A was editing, and user A get the option to
                        decide what action to take.

                        Optimistic
                        Locking has been achieved by maintaining a version field with each page, however
                        we are not relying on the optimistic locking features of Hibernate to determine
                        when an optimistic lock has been violated. This is performed by the code and the user
                        is given the opertunity to either overwrite the interceeding content or accept that content.
                        We found using Hibernates own optimistic locking mechanisms did not give the user enough control
                        over the operation.

                </subsection>
                <subsection name="Version Control">

                        As pages are edited, each edit results in a new version of the page. The time of the edit and its
                        entire content are stored in the database. We are not using an RCS based version control.

                </subsection>
                <subsection name="Diff View" >

                        With Version Control a Diff view is required. The Diff view should allow the user to view the
                        differences between two versions, that the user can select. It should enable the user to clearly
                        identify what has changed between to the two versions. We are not, at this stage looking to
                        see a complete change history in a single page (as with Track Changes in Microsoft Word) as this is
                        probably to complicated to implement at this stage.

                </subsection>
                <subsection name="Preview" >

                        To avoid forcing he user to save their changes just to see if they have formatted the changes correctly
                        we need to have a preview function on the edit page. This should maintain the edit state of the edit page
                        and without saving the edits, allow the user to preview their wiki markup as it will appear on the final
                        page. The user should not be asked to navigate back and forward to see the preview.

                </subsection>
                <subsection name="Attachement Support" >

                       Each RWiki space within the worksite should manage its own subfolder in sakai
                        resources that contains attachments. RWiki should reuse the sakai resources
                        functionality to enable a use to upload content on the page. It should provide
                         a list of uploaded the contents, for that page, on the pages (e.g. there are
                          5 attachments to this page). Should investigate what happens when a resource
                           is moved, and how be might handle it. Is their an event in Resources we can watch ?

                </subsection>
                <subsection name="Image Support" >

                        It should be possible to reference any file in resources inside RWiki.
                         If the source can be rendered as an image, a img tag should be used,
                         otherwise a link should be used. This is probably implemented in the
                         properties file that implements the mark-up.

                </subsection>
                <subsection name="Maths Support" >

                        It should be possible to insert Latex mark-up into the page (suitably delimited).
                         Where that mark-up us present, a plug-in should use a Latex-rendering engine to
                         emit wither MathML or a gif to represent the math, see MediaWiki for examples.

                </subsection>
                <subsection name="Prepopulated Pages" >

                        The existing blank pages that are deployed on install need to be expanded.
                         Their should be some basic structure setup and some help on the
                         available mark-up.

                </subsection>

            <subsection name="2.0 Release Feature List">

Move to Sakai 2.0 done

Rewrite request archetecture done

Check functionality with Sakai 1.5 postponed pending demand

Implement version control done

Implement complete robust optimistic locking done

Implement usable preview support done

QA Rewritten archetecture done

Implement Visual Diff of versions done

Implement Prepopulated pages, sidebars, help, howto's done

Implement Export support postponed pending more requirements

Needs to take account of Helpers and Archiving

Review markup done

Implement attachement support postponed, using Sakai Resources

Need to make it easier to put attachements in

Implement Navigation support done

Implement Image Support done

Reskin UI layout done

Implement Maths Support done

            </subsection>

Comment Support

 We would like to scope the requirements for adding comment support.
                            There are several issues to be resolved:

 What sort of permission structure should be added?

 Do we want comments on comments?

 Any other thoughts?

Performance of History

Comments

Event integration

Navigation Persistance

RSS feed of recent changes

Helpers

Integration of Events into Courier

Rename a page needs discussion

Spelling

            <subsection name="Improving the performance of History" >

 In our current model we use an attached List of RWikiHistoryObjects for
                                    storing the history of a page.

 This link is currently a hard-link and thus when the number of
                                    revisions gets large there will be a definite slow down in performance.

 There are two options to solve this problem:

 Use Lazy Initialization and inherit all of the difficulties
                                        associated with that

 Separate the link, and break ORM.

            </subsection>
            <subsection name="Comments">

To make the wiki usefull in a educational environment, we
                would need comments on a page. This is probably a sequence of wiki pages, probably
                    with a different set of permissions, that a associated with the main page.
 </subsection>

            <subsection name="Event  Integration">

               RWiki should register events, navigation from
                page to page, when an edit is started, every transaction with RWiki should cause an
                event to register.

            </subsection>
            <subsection name="Navigation Persistance">

At the moment there is no navigational
                persistance. When you switch between tools, you loose the state of the RWiki tool.
                We want to provide Navigational persistance without locking anything. There are a
                few options.

Client Side

The tools stores its state in client side cookies so that when the user
                            returns to the start page, the tool moves to the last state page, by
                            refresshing the page. This is a minimal impact approach.... however it
                            will only work relyably for gets. If applied to POSTs and editing page,
                            we probably will not be able to store all state in cookies.

Server Side

As we move via each page we maintain a client state in the server
                            session. This means that all copies of the Wiki tool within the Same
                            worksite, Same session are tied, when on the home page. It may be
                            possible to track new Windows, same session, and/or new tab same
                            session. In addition we have to track editing content, so, periodically
                            as the use types, their state is saved to the server. Then when the
                            switch tools/worksite and come back to the edit window, their edits are
                            not lost.

Issues

Both mechanisms must track windows in the same session and not tie them
                            together.

Both mechanisms must only restore state on the Home page, since that is
                            the one where state will be reconstituted from.

Should consider enclosed view state as exists in .NET (only as a
                            informative model, not as an example of good implementation)

            </subsection>
            <subsection name="RSS feed">

                Feed of recient changes as RSS, but also other features. If
                these events are RWiki specific they should be RWiki standalone, otherwise they
                should integrate with Sakai Events.
</subsection>
            <subsection name="Helpers">
At the moment we have a rendering service for RWiki. We also
                need to expose the pages of the wiki as undecorated content so that other tools can
                use the content. If RWiki becomes fragment capable via its helper, then its content
                will become available via JSR-168 provider. That is why this is important.
</subsection>
            <subsection name="Courier">
With events in place, these should flow to the UI, so that a
                user is notified when annother user starts to edit a page. This might include all
                activities in the wiki space for the worksite.
</subsection>
            <subsection name="Rename page">
Need to rename a page, however this creates and issue
                for references. Perhapse we need a permlink to avoid external 404's
</subsection>
            <subsection name="Spelling">

A non intrusive spell checker that cheked spelling as typing (using ajax),
                        as you might have noticed, my speling is bad!

            </subsection>

</document>


text:
<!DOCTYPE html>

    <title>submergence:Agent#logout~details documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../../../highlight.css" />

            spare

                :submergence:Agent#logout~details

Deactivate sessions belonging to a User or User/Client pair. Active Socket.io connections are
selected and terminated.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
/*
You'll notice this littered with !important declarations - this is due
to the inline-editing controls being injected into abitrary layouts and
this is the hackish attempt at trying to keep them consistant across
implementations, by not being overridden by the stylesheets for each
particular site's layout.
*/

/* TOOLBAR */

#editable-toolbar, .editable-highlight, .editable-link {top:0; left:0;
    z-index:300; position:absolute;}
#editable-toolbar {z-index:9000; display:none; padding-left:2px !important;}
#editable-loading {z-index:10000; display:none; position:absolute;}
#editable-toolbar {position:fixed;}
.editable-highlight {border:1px solid #ccc;}
.editable-link {display: block;}

#editable-toolbar, .editable-link {
    background:#fffcc3; float:left; cursor:pointer; padding:6px 8px;
    white-space:nowrap; border:1px solid #ccc; line-height:1em;}

#editable-toolbar a, .editable-link {text-decoration:none;
    color:#222 !important; font-size:11px !important;
    font-weight:normal; text-transform:uppercase;}

#editable-toolbar a {border-left:1px solid #bbb; padding:0 8px 0 12px;
    display:none;}
a#editable-toolbar-toggle {border-left:0px !important; text-decoration:none;
    display:inline !important; font-weight:bold !important;
    font-size:14px !important;}

/* FORM */

.editable-form {
    padding:20px; background:#fffcc3; border:1px solid #000;
    line-height:1em; border-radius:4px; min-width:350px;
    box-shadow: 0 0 80px #222;

    -ms-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
.editable-form .mce-tinymce {min-width: 770px;}
.editable-form table, .editable-form textarea, .editable-form input {
    width: 100%; margin: .5em 0; font-size: 14px;}
.mceToolbar table {width: auto !important; margin: 0 !important;}
.editable-form .booleanfield {width: auto;}
.editable-form input.datetimefield {width: 80px; margin-left: 8px;}
.editable-form select {width:auto;}
.editable-form input[type="file"] {width: 300px;}
.editable-form p {margin: .5em 0 !important; padding: 0 !important;
    line-height: 0 !important; border: 0 !important;}
.editable-form p:first-child {margin-top: 0px;}
.editable-form .helptext {font-size: 70%; color: #444; font-style: italic;}
.editable-form label {text-transform: capitalize !important;
    font-weight: bold !important; line-height: 1.1em !important;
    font-size: 15px !important; color: #000 !important; float:none;}
.editable-form .btn {width:auto; cursor:pointer; float:right;
    margin:15px 0 0 15px; padding:5px 15px; border-radius:3px;}
.editable-form textarea {line-height: normal; width: 500px;} /* GH #1382 */


text:
#ifndef	INCLUDED_NSString_GNUstepBase_h
#define	INCLUDED_NSString_GNUstepBase_h

#import <GNUstepBase/GSVersionMacros.h>
#import <Foundation/NSString.h>

#if	defined(__cplusplus)
extern "C" {
#endif

#if	OS_API_VERSION(GS_API_NONE,GS_API_LATEST)

/**
 * Provides some additional (non-standard) utility methods.
 */
@interface NSString (GNUstepBase)

/**
 * Alternate way to invoke stringWithFormat if you have or wish
 * to build an explicit va_list structure.
 */
+ (id) stringWithFormat: (NSString*)format
	      arguments: (va_list)argList;

/**
 * Returns a string formed by removing the prefix string from the
 * receiver.  Raises an exception if the prefix is not present.
 */
- (NSString*) stringByDeletingPrefix: (NSString*)prefix;

/**
 * Returns a string formed by removing the suffix string from the
 * receiver.  Raises an exception if the suffix is not present.
 */
- (NSString*) stringByDeletingSuffix: (NSString*)suffix;

/**
 * Returns a string formed by removing leading white space from the
 * receiver.
 */
- (NSString*) stringByTrimmingLeadSpaces;

/**
 * Returns a string formed by removing trailing white space from the
 * receiver.
 */
- (NSString*) stringByTrimmingTailSpaces;

/**
 * Returns a string formed by removing both leading and trailing
 * white space from the receiver.
 */
- (NSString*) stringByTrimmingSpaces;

/**
 * Returns a string in which any (and all) occurrences of
 * replace in the receiver have been replaced with by.
 * Returns the receiver if replace
 * does not occur within the receiver.  NB. an empty string is
 * not considered to exist within the receiver.
 */
- (NSString*) stringByReplacingString: (NSString*)replace
			   withString: (NSString*)by;

/**
 * An obsolete name for -substringWithRange: ... deprecated.
 */
- (NSString*) substringFromRange: (NSRange)aRange;

@end

#endif	/* OS_API_VERSION */

#if	defined(__cplusplus)
}
#endif

#endif	/* INCLUDED_NSString_GNUstepBase_h */


text:
package com.yx.platform.model;

import java.io.Serializable;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.yx.platform.core.base.BaseModel;

/**
 * <p>
 * 邮件模版表
 * </p>
 */
@SuppressWarnings("serial")
@TableName("sys_email_template")
public class SysEmailTemplate extends BaseModel
{

    /**
     * 邮件名称
     */
    @TableField(value = "sender_name")
    private String senderName;

    /**
     * 发送邮件帐号
     */
    @TableField(value = " sender_account")
    private String senderAccount;

    /**
     * 排序号
     */
    @TableField(value = "sort_")
    private Integer sort;

    /**
     * 标题模版
     */
    @TableField(value = "title_")
    private String title;

    /**
     * 内容模板
     */
    @TableField(value = "template_")
    private String template;

    public String getSenderName()
    {
        return senderName;
    }

    public void setSenderName(String senderName)
    {
        this.senderName = senderName;
    }

    public String getSenderAccount()
    {
        return senderAccount;
    }

    public void setSenderAccount(String senderAccount)
    {
        this.senderAccount = senderAccount;
    }

    public Integer getSort()
    {
        return sort;
    }

    public void setSort(Integer sort)
    {
        this.sort = sort;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public String getTemplate()
    {
        return template;
    }

    public void setTemplate(String template)
    {
        this.template = template;
    }

    protected Serializable pkVal()
    {
        return getId();
    }
}