text:
import {DomUtils} from "../domParsers/domUtils";

import * as Log from "../logging/log";

import {Constants} from "../constants";
import {Status} from "./status";

import {ClipperStateProp} from "./clipperState";
import {ComponentBase} from "./componentBase";
import {Clipper} from "./frontEndGlobals";

export interface Point {
	x: number;
	y: number;
};

interface RegionSelectorState {
	firstPoint?: Point;
	secondPoint?: Point;
	selectionInProgress?: boolean;
	winWidth?: number;
	winHeight?: number;
}

class RegionSelectorClass extends ComponentBase<RegionSelectorState, ClipperStateProp> {
	private devicePixelRatio: number = 1;

	private resizeHandler = this.handleResize.bind(this);

	getInitialState(): RegionSelectorState {
		return {
			selectionInProgress: false,
			winHeight: window.innerHeight,
			winWidth: window.innerWidth
		};
	}

	constructor(props: ClipperStateProp) {
		super(props);
		this.resetState();

		window.addEventListener("resize", this.resizeHandler);
	}

	private onunload() {
		window.removeEventListener("resize", this.resizeHandler);
	}

	/**
	 * Start the selection process over
	 */
	private resetState() {
		this.setState({ firstPoint: undefined, secondPoint: undefined, selectionInProgress: false });
		this.props.clipperState.setState({ regionResult: { status: Status.NotStarted, data: this.props.clipperState.regionResult.data } });
	}

	/**
	 * Define the starting point for the selection
	 */
	private startSelection(point: Point) {
		if (this.props.clipperState.regionResult.status !== Status.InProgress) {
			this.setState({ firstPoint: point, secondPoint: undefined, selectionInProgress: true });
			this.props.clipperState.setState({ regionResult: { status: Status.InProgress, data: this.props.clipperState.regionResult.data } });
		}
	}

	/**
	 * The selection is complete
	 */
	private completeSelection(dataUrl: string) {
		let regionList = this.props.clipperState.regionResult.data;
		if (!regionList) {
			regionList = [];
		}
		regionList.push(dataUrl);
		this.props.clipperState.setState({ regionResult: { status: Status.Succeeded, data: regionList } });
	}

	/**
	 * They are selecting, update the second point
	 */
	private moveSelection(point: Point) {
		this.setState({ secondPoint: point });
	}

	/**
	 * Define the ending point, and notify the main UI
	 */
	private stopSelection(point: Point) {
		if (this.state.selectionInProgress) {
			if (!this.state.firstPoint || !this.state.secondPoint || this.state.firstPoint.x === this.state.secondPoint.x || this.state.firstPoint.y === this.state.secondPoint.y) {
				// Nothing to clip, start over
				this.resetState();
			} else {
				this.setState({ secondPoint: point, selectionInProgress: false });
				// Get the image immediately
				this.startRegionClip();
			}
		}
	}

	private mouseDownHandler(e: MouseEvent) {
		// Prevent default "dragging" which sometimes occurs
		e.preventDefault();
		this.startSelection({ x: e.pageX, y: e.pageY });
	}

	private mouseMoveHandler(e: MouseEvent) {
		if (this.state.selectionInProgress) {
			if (e.buttons === 0) {
				// They let go of the mouse while outside the window, stop the selection where they went out
				this.stopSelection(this.state.secondPoint);
				return;
			}

			this.moveSelection({ x: e.pageX, y: e.pageY });
		}
	}

	private mouseUpHandler(e: MouseEvent) {
		this.stopSelection({ x: e.pageX, y: e.pageY });
	}

	private touchStartHandler(e: TouchEvent) {
		let eventPoint = e.changedTouches[0];
		this.startSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
	}

	private touchMoveHandler(e: TouchEvent) {
		if (this.state.selectionInProgress) {
			let eventPoint = e.changedTouches[0];
			this.moveSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
			e.preventDefault();
		}
	}

	private touchEndHandler(e: TouchEvent) {
		let eventPoint = e.changedTouches[0];
		this.stopSelection({ x: eventPoint.clientX, y: eventPoint.clientY });
	}

	private handleResize() {
		this.setState({ winHeight: window.innerHeight, winWidth: window.innerWidth });
	}

	/**
	 * Update all of the frames and elements according to the selection
	 */
	private updateVisualElements() {
		let outerFrame: HTMLCanvasElement = this.refs.outerFrame as HTMLCanvasElement;
		if (!outerFrame) {
			return;
		}

		let xMin: number;
		let yMin: number;
		let xMax: number;
		let yMax: number;

		if (!this.state.firstPoint || !this.state.secondPoint) {
			xMin = 0;
			yMin = 0;
			xMax = 0;
			yMax = 0;
		} else {
			xMin = Math.min(this.state.firstPoint.x, this.state.secondPoint.x);
			yMin = Math.min(this.state.firstPoint.y, this.state.secondPoint.y);
			xMax = Math.max(this.state.firstPoint.x, this.state.secondPoint.x);
			yMax = Math.max(this.state.firstPoint.y, this.state.secondPoint.y);

			let innerFrame: HTMLCanvasElement = this.refs.innerFrame as HTMLCanvasElement;
			if (innerFrame) {
				// We don't worry about -1 values as they simply go offscreen neatly
				let borderWidth = 1;
				innerFrame.style.top = yMin - borderWidth + "px";
				innerFrame.style.left = xMin - borderWidth + "px";
				innerFrame.style.height = yMax - yMin + "px";
				innerFrame.style.width = xMax - xMin + "px";
			}
		}

		let winWidth = this.state.winWidth;
		let winHeight = this.state.winHeight;

		let context = outerFrame.getContext("2d");
		context.canvas.width = winWidth;
		context.canvas.height = winHeight;

		context.beginPath();
		context.fillStyle = "black";
		context.fillRect(0, 0, xMin, winHeight);
		context.fillRect(xMin, 0, xMax - xMin, yMin);
		context.fillRect(xMax, 0, winWidth - xMax, winHeight);
		context.fillRect(xMin, yMax, xMax - xMin, winHeight - yMax);
	}

	/**
	 * Get the browser to capture a screenshot, and save off the portion they selected (which may be compressed until it's below
	 * the maximum allowed size)
	 */
	private startRegionClip() {
		// Firefox reports this value incorrectly if this iframe is hidden, so store it now since we know we're visible
		this.devicePixelRatio = window.devicePixelRatio;

		let regionSelectionProcessingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionProcessing);
		let regionSelectionCapturingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionCapturing);
		regionSelectionCapturingEvent.setCustomProperty(Log.PropertyName.Custom.Width, Math.abs(this.state.firstPoint.x - this.state.secondPoint.x));
		regionSelectionCapturingEvent.setCustomProperty(Log.PropertyName.Custom.Height, Math.abs(this.state.firstPoint.y - this.state.secondPoint.y));

		Clipper.getExtensionCommunicator().callRemoteFunction(Constants.FunctionKeys.takeTabScreenshot, {
			callback: (dataUrl: string) => {
				Clipper.logger.logEvent(regionSelectionCapturingEvent);
				this.saveCompressedSelectionToState(dataUrl).then((canvas) => {
					regionSelectionProcessingEvent.setCustomProperty(Log.PropertyName.Custom.Width, canvas.width);
					regionSelectionProcessingEvent.setCustomProperty(Log.PropertyName.Custom.Height, canvas.height);
					Clipper.logger.logEvent(regionSelectionProcessingEvent);
				});
			}
		});
	}

	/**
	 * Given a base image in url form, captures the sub-image defined by the state's first and second points, compresses it if
	 * necessary, then saves it to state if the process was successful
	 */
	private saveCompressedSelectionToState(baseDataUrl: string): Promise<HTMLCanvasElement> {
		return this.createSelectionAsCanvas(baseDataUrl).then((canvas) => {
			let compressedSelection = this.getCompressedDataUrl(canvas);
			this.completeSelection(compressedSelection);
			return Promise.resolve(canvas);
		}).catch((error: Error) => {
			Clipper.logger.logFailure(Log.Failure.Label.RegionSelectionProcessing, Log.Failure.Type.Unexpected,
				{ error: error.message });
			this.resetState();
			return Promise.reject(error);
		});
	}

	/**
	 * Given a base image in url form, creates a canvas containing the sub-image defined by the state's first and second points
	 */
	private createSelectionAsCanvas(baseDataUrl: string): Promise<HTMLCanvasElement> {
		if (!baseDataUrl) {
			return Promise.reject(new Error("baseDataUrl should be a non-empty string, but was: " + baseDataUrl));
		}

		if (!this.state.firstPoint || !this.state.secondPoint) {
			return Promise.reject(new Error("Expected the two points to be set, but they were not"));
		}

		return new Promise<HTMLCanvasElement>((resolve) => {
			let regionSelectionLoadingEvent = new Log.Event.BaseEvent(Log.Event.Label.RegionSelectionLoading);
			let img: HTMLImageElement = new Image();

			img.onload = () => {
				Clipper.logger.logEvent(regionSelectionLoadingEvent);

				let xMin = Math.min(this.state.firstPoint.x, this.state.secondPoint.x);
				let yMin = Math.min(this.state.firstPoint.y, this.state.secondPoint.y);
				let xMax = Math.min(img.width, Math.max(this.state.firstPoint.x, this.state.secondPoint.x));
				let yMax = Math.min(img.height, Math.max(this.state.firstPoint.y, this.state.secondPoint.y));

				let destinationOffsetX = 0;
				let destinationOffsetY = 0;
				let width = (xMax - xMin);
				let height = (yMax - yMin);
				let sourceOffsetX = xMin * this.devicePixelRatio;
				let sourceOffsetY = yMin * this.devicePixelRatio;
				let sourceWidth = (xMax - xMin) * this.devicePixelRatio;
				let sourceHeight = (yMax - yMin) * this.devicePixelRatio;

				let canvas: HTMLCanvasElement = document.createElement("canvas") as HTMLCanvasElement;
				canvas.width = width;
				canvas.height = height;
				let ctx: CanvasRenderingContext2D = canvas.getContext("2d");
				ctx.drawImage(img, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, destinationOffsetX, destinationOffsetY, width, height);

				resolve(canvas);
			};

			img.src = baseDataUrl;
		});
	}

	/*
	 * Converts the canvas to a Base64 encoded URI, compressing it by lowering its quality if above the maxBytes threshold
	 */
	private getCompressedDataUrl(node: Node): string {
		let compressEvent = new Log.Event.BaseEvent(Log.Event.Label.CompressRegionSelection);

		let canvas: HTMLCanvasElement = node as HTMLCanvasElement;

		// First, see if the best quality PNG will work.
		let dataUrl: string = canvas.toDataURL("image/png");
		compressEvent.setCustomProperty(Log.PropertyName.Custom.InitialDataUrlLength, dataUrl.length);

		dataUrl = DomUtils.adjustImageQualityIfNecessary(canvas, dataUrl);

		compressEvent.setCustomProperty(Log.PropertyName.Custom.FinalDataUrlLength, dataUrl.length);
		Clipper.logger.logEvent(compressEvent);

		return dataUrl;
	}

	private getInnerFrame() {
		if (this.state.secondPoint) {
			return

;
		}

		return undefined;
	}

	render() {
		let innerFrameElement = this.getInnerFrame();

		return (

				<canvas id={Constants.Ids.outerFrame} {...this.ref(Constants.Ids.outerFrame)}></canvas>
				{innerFrameElement}

		);
	}
}

let component = RegionSelectorClass.componentize();
export {component as RegionSelector};


text:
<?php

/** @file
* @brief
*/

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access directly to this file");
}

/// TODO extends it from CommonDBChild
abstract class CommonITILTask  extends CommonDBTM {

   // From CommonDBTM
   public $auto_message_on_action = false;

   function getItilObjectItemType() {
      return str_replace('Task','',$this->getType());
   }

   function canViewPrivates() {
      return false;
   }

   function canEditAll() {
      return false;
   }

   /**
    * Get the item associated with the current object.
    *
    * @since version 0.84
    *
    * @return object of the concerned item or false on error
   **/
   function getItem() {

      if ($item = getItemForItemtype($this->getItilObjectItemType())) {
         if ($item->getFromDB($this->fields[$item->getForeignKeyField()])) {
            return $item;
         }
     }
     return false;
   }

   /**
    * can read the parent ITIL Object ?
    *
    * @return boolean
   **/
   function canReadITILItem() {

      $itemtype = $this->getItilObjectItemType();
      $item     = new $itemtype();
      if (!$item->can($this->getField($item->getForeignKeyField()), READ)) {
         return false;
      }
      return true;
   }

   /**
    * can update the parent ITIL Object ?
    *
    * @since version 0.85
    *
    * @return boolean
   **/
   function canUpdateITILItem() {

      $itemtype = $this->getItilObjectItemType();
      $item     = new $itemtype();
      if (!$item->can($this->getField($item->getForeignKeyField()), UPDATE)) {
         return false;
      }
      return true;
   }

   /**
    * Name of the type
    *
    * @param $nb : number of item in the type (default 0)
   **/
   static function getTypeName($nb=0) {
      return _n('Task', 'Tasks', $nb);

   }

   /**
    * @since version 0.84
    *
    * @param $field
    * @param $values
    * @param $options   array
   **/
   static function getSpecificValueToDisplay($field, $values, array $options=array()) {

      if (!is_array($values)) {
         $values = array($field => $values);
      }

      switch ($field) {
         case 'state' :
            return Planning::getState($values[$field]);
      }
      return parent::getSpecificValueToDisplay($field, $values, $options);
   }

   /**
    * @since version 0.84
    *
    * @param $field
    * @param $name            (default '')
    * @param $values          (default '')
    * @param $options   array
    *
    * @return string
   **/
   static function getSpecificValueToSelect($field, $name='', $values='', array $options=array()) {

      if (!is_array($values)) {
         $values = array($field => $values);
      }
      $options['display'] = false;

      switch ($field) {
         case 'state':
            return Planning::dropdownState($name, $values[$field], false);
      }
      return parent::getSpecificValueToSelect($field, $name, $values, $options);
   }

   function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {

      if (($item->getType() == $this->getItilObjectItemType())
          && $this->canView()) {
         $nb = 0;
         if ($_SESSION['glpishow_count_on_tabs']) {
            $restrict = "`".$item->getForeignKeyField()."` = '".$item->getID()."'";

            if ($this->maybePrivate()
                && !$this->canViewPrivates()) {
               $restrict .= " AND (`is_private` = '0'
                                   OR `users_id` = '" . Session::getLoginUserID() . "') ";
            }
            $nb = countElementsInTable($this->getTable(), $restrict);
         }
         return self::createTabEntry(self::getTypeName(Session::getPluralNumber()), $nb);
      }
      return '';
   }

   static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {

      $itemtype = $item->getType().'Task';
      if ($task = getItemForItemtype($itemtype)) {
         $task->showSummary($item);
         return true;
      }
   }

   function post_deleteFromDB() {
      global $CFG_GLPI;

      $itemtype = $this->getItilObjectItemType();
      $item     = new $itemtype();
      $item->getFromDB($this->fields[$item->getForeignKeyField()]);
      $item->updateActiontime($this->fields[$item->getForeignKeyField()]);
      $item->updateDateMod($this->fields[$item->getForeignKeyField()]);

      // Add log entry in the ITIL object
      $changes[0] = 0;
      $changes[1] = '';
      $changes[2] = $this->fields['id'];
      Log::history($this->getField($item->getForeignKeyField()), $this->getItilObjectItemType(),
                   $changes, $this->getType(), Log::HISTORY_DELETE_SUBITEM);

      if ($CFG_GLPI["use_mailing"]) {
         $options = array('task_id'             => $this->fields["id"],
                           // Force is_private with data / not available
                          'is_private'          => $this->isPrivate(),
                          // Pass users values
                          'task_users_id'       => $this->fields['users_id'],
                          'task_users_id_tech'  => $this->fields['users_id_tech']);
         NotificationEvent::raiseEvent('delete_task', $item, $options);
      }
   }

   function prepareInputForUpdate($input) {

      Toolbox::manageBeginAndEndPlanDates($input['plan']);

      if (isset($input['_planningrecall'])) {
         PlanningRecall::manageDatas($input['_planningrecall']);
      }

//      $input["actiontime"] = $input["hour"]*HOUR_TIMESTAMP+$input["minute"]*MINUTE_TIMESTAMP;

      if (isset($input['update'])
          && ($uid = Session::getLoginUserID())) { // Change from task form
         $input["users_id"] = $uid;
      }

      $itemtype      = $this->getItilObjectItemType();
      $input["_job"] = new $itemtype();

      if (!$input["_job"]->getFromDB($input[$input["_job"]->getForeignKeyField()])) {
         return false;
      }

      if (isset($input["plan"])) {
         $input["begin"]         = $input['plan']["begin"];
         $input["end"]           = $input['plan']["end"];

         $timestart              = strtotime($input["begin"]);
         $timeend                = strtotime($input["end"]);
         $input["actiontime"]    = $timeend-$timestart;

         unset($input["plan"]);

         if (!$this->test_valid_date($input)) {
            Session::addMessageAfterRedirect(__('Error in entering dates. The starting date is later than the ending date'),
                                             false, ERROR);
            return false;
         }
         Planning::checkAlreadyPlanned($input["users_id_tech"], $input["begin"], $input["end"],
                                       array($this->getType() => array($input["id"])));

         $calendars_id = Entity::getUsedConfig('calendars_id', $input["_job"]->fields['entities_id']);
         $calendar     = new Calendar();

         // Using calendar
         if (($calendars_id > 0)
             && $calendar->getFromDB($calendars_id)) {
            if (!$calendar->isAWorkingHour(strtotime($input["begin"]))) {
               Session::addMessageAfterRedirect(__('Start of the selected timeframe is not a working hour.'),
                                                false, ERROR);
            }
            if (!$calendar->isAWorkingHour(strtotime($input["end"]))) {
               Session::addMessageAfterRedirect(__('End of the selected timeframe is not a working hour.'),
                                                false, ERROR);
            }
         }
      }

      return $input;
   }

   function post_updateItem($history=1) {
      global $CFG_GLPI;

      if (in_array("begin",$this->updates)) {
         PlanningRecall::managePlanningUpdates($this->getType(), $this->getID(),
                                               $this->fields["begin"]);
      }

      $update_done = false;
      $itemtype    = $this->getItilObjectItemType();
      $item        = new $itemtype();

      if ($item->getFromDB($this->fields[$item->getForeignKeyField()])) {
         $item->updateDateMod($this->fields[$item->getForeignKeyField()]);

         if (count($this->updates)) {
            $update_done = true;

            if (in_array("actiontime",$this->updates)) {
               $item->updateActionTime($this->input[$item->getForeignKeyField()]);
            }

            // change ticket status (from splitted button)
            $itemtype = $this->getItilObjectItemType();
            $this->input['_job'] = new $itemtype();
            if (!$this->input['_job']->getFromDB($this->input[$this->input['_job']->getForeignKeyField()])) {
               return false;
            }
            if (isset($this->input['_status'])
                && ($this->input['_status'] != $this->input['_job']->fields['status'])) {
                $update['status']        = $this->input['_status'];
                $update['id']            = $this->input['_job']->fields['id'];
                $update['_disablenotif'] = true;
                $this->input['_job']->update($update);
             }

            if (!empty($this->fields['begin'])
                && $item->isStatusExists(CommonITILObject::PLANNED)
                && (($item->fields["status"] == CommonITILObject::INCOMING)
                     || ($item->fields["status"] == CommonITILObject::ASSIGNED))) {

               $input2['id']            = $item->getID();
               $input2['status']        = CommonITILObject::PLANNED;
               $input2['_disablenotif'] = true;
               $item->update($input2);
            }

            if ($CFG_GLPI["use_mailing"]) {
               $options = array('task_id'    => $this->fields["id"],
                                'is_private' => $this->isPrivate());
               NotificationEvent::raiseEvent('update_task', $item, $options);
            }

         }
      }

      if ($update_done) {
         // Add log entry in the ITIL object
         $changes[0] = 0;
         $changes[1] = '';
         $changes[2] = $this->fields['id'];
         Log::history($this->getField($item->getForeignKeyField()), $itemtype, $changes,
                      $this->getType(), Log::HISTORY_UPDATE_SUBITEM);
      }
   }

   function prepareInputForAdd($input) {

      $itemtype = $this->getItilObjectItemType();

      Toolbox::manageBeginAndEndPlanDates($input['plan']);

      if (isset($input["plan"])) {
         $input["begin"]         = $input['plan']["begin"];
         $input["end"]           = $input['plan']["end"];

         $timestart              = strtotime($input["begin"]);
         $timeend                = strtotime($input["end"]);
         $input["actiontime"]    = $timeend-$timestart;

         unset($input["plan"]);
         if (!$this->test_valid_date($input)) {
            Session::addMessageAfterRedirect(__('Error in entering dates. The starting date is later than the ending date'),
                                             false, ERROR);
            return false;
         }
      }

      $input["_job"] = new $itemtype();

      if (!$input["_job"]->getFromDB($input[$input["_job"]->getForeignKeyField()])) {
         return false;
      }

      // Pass old assign From object in case of assign change
      if (isset($input["_old_assign"])) {
         $input["_job"]->fields["_old_assign"] = $input["_old_assign"];
      }

      if (!isset($input["users_id"])
          && ($uid = Session::getLoginUserID())) {
         $input["users_id"] = $uid;
      }

      if (!isset($input["date"])) {
         $input["date"] = $_SESSION["glpi_currenttime"];
      }
      if (!isset($input["is_private"])) {
         $input['is_private'] = 0;
      }

      // Manage File attached (from mailgate)
      // Pass filename if set to ticket
      if (isset($input['_filename'])) {
         $input["_job"]->input['_filename'] = $input['_filename'];
      }
      // Add docs without notif
      $docadded = $input["_job"]->addFiles(0,1);

      return $input;
   }

   function post_addItem() {
      global $CFG_GLPI;

      if (isset($this->input['_planningrecall'])) {
         $this->input['_planningrecall']['items_id'] = $this->fields['id'];
         PlanningRecall::manageDatas($this->input['_planningrecall']);
      }

      $donotif = $CFG_GLPI["use_mailing"];

      if (isset($this->fields["begin"]) && !empty($this->fields["begin"])) {
         Planning::checkAlreadyPlanned($this->fields["users_id_tech"], $this->fields["begin"],
                                       $this->fields["end"],
                                       array($this->getType() => array($this->fields["id"])));

         $calendars_id = Entity::getUsedConfig('calendars_id', $this->input["_job"]->fields['entities_id']);
         $calendar     = new Calendar();

         // Using calendar
         if (($calendars_id > 0)
             && $calendar->getFromDB($calendars_id)) {
            if (!$calendar->isAWorkingHour(strtotime($this->fields["begin"]))) {
               Session::addMessageAfterRedirect(__('Start of the selected timeframe is not a working hour.'),
                                                false, ERROR);
            }
            if (!$calendar->isAWorkingHour(strtotime($this->fields["end"]))) {
               Session::addMessageAfterRedirect(__('End of the selected timeframe is not a working hour.'),
                                                false, ERROR);
            }
         }
      }

//       if (isset($this->input["_no_notif"]) && $this->input["_no_notif"]) {
//          $donotif = false;
//       }

      $this->input["_job"]->updateDateMod($this->input[$this->input["_job"]->getForeignKeyField()]);

      if (isset($this->input["actiontime"]) && ($this->input["actiontime"] > 0)) {
         $this->input["_job"]->updateActionTime($this->input[$this->input["_job"]->getForeignKeyField()]);
      }

     //change status only if input change
     if (isset($this->input['_status'])
         && ($this->input['_status'] != $this->input['_job']->fields['status'])) {
         $update['status']        = $this->input['_status'];
         $update['id']            = $this->input['_job']->fields['id'];
         $update['_disablenotif'] = true;
         $this->input['_job']->update($update);
      }

      if (!empty($this->fields['begin'])
          && $this->input["_job"]->isStatusExists(CommonITILObject::PLANNED)
          && (($this->input["_job"]->fields["status"] == CommonITILObject::INCOMING)
              || ($this->input["_job"]->fields["status"] == CommonITILObject::ASSIGNED))) {

         $input2['id']            = $this->input["_job"]->getID();
         $input2['status']        = CommonITILObject::PLANNED;
         $input2['_disablenotif'] = true;
         $this->input["_job"]->update($input2);
      }

      if ($donotif) {
         $options = array('task_id'    => $this->fields["id"],
                          'is_private' => $this->isPrivate());
         NotificationEvent::raiseEvent('add_task', $this->input["_job"], $options);
      }

      // Add log entry in the ITIL object
      $changes[0] = 0;
      $changes[1] = '';
      $changes[2] = $this->fields['id'];
      Log::history($this->getField($this->input["_job"]->getForeignKeyField()),
                   $this->input["_job"]->getTYpe(), $changes, $this->getType(),
                   Log::HISTORY_ADD_SUBITEM);
   }

   function post_getEmpty() {

      if ($this->maybePrivate()
          && isset($_SESSION['glpitask_private']) && $_SESSION['glpitask_private']) {

         $this->fields['is_private'] = 1;
      }
      // Default is todo
      $this->fields['state'] = Planning::TODO;
      if (isset($_SESSION['glpitask_state'])) {

         $this->fields['state'] = $_SESSION['glpitask_state'];
      }
   }

   /**
    * @see CommonDBTM::cleanDBonPurge()
    *
    * @since version 0.84
   **/
   function cleanDBonPurge() {

      $class = new PlanningRecall();
      $class->cleanDBonItemDelete($this->getType(), $this->fields['id']);
   }

   // SPECIFIC FUNCTIONS

   /**
    * @see CommonDBTM::getRawName()
    *
    * @since version 0.85
   **/
   function getRawName() {

      if (isset($this->fields['taskcategories_id'])) {
         if ($this->fields['taskcategories_id']) {
            return Dropdown::getDropdownName('glpi_taskcategories',
                                             $this->fields['taskcategories_id']);
         }
         return $this->getTypeName(1);
      }
      return '';
   }

   function getSearchOptions() {

      $tab                    = array();
      $tab['common']          = __('Characteristics');

      $tab[1]['table']        = $this->getTable();
      $tab[1]['field']        = 'content';
      $tab[1]['name']         = __('Description');
      $tab[1]['datatype']     = 'text';

      $tab[2]['table']        = 'glpi_taskcategories';
      $tab[2]['field']        = 'name';
      $tab[2]['name']         = _n('Task category', 'Task categories', 1);
      $tab[2]['forcegroupby'] = true;
      $tab[2]['datatype']     = 'dropdown';

      $tab[3]['table']        = $this->getTable();
      $tab[3]['field']        = 'date';
      $tab[3]['name']         = __('Date');
      $tab[3]['datatype']     = 'datetime';

      if ($this->maybePrivate()) {
         $tab[4]['table']    = $this->getTable();
         $tab[4]['field']    = 'is_private';
         $tab[4]['name']     = __('Public followup');
         $tab[4]['datatype'] = 'bool';
      }

      $tab[5]['table']        = 'glpi_users';
      $tab[5]['field']        = 'name';
      $tab[5]['name']         = __('Technician');
      $tab[5]['datatype']     = 'dropdown';
      $tab[5]['right']        = 'own_ticket';

      $tab[6]['table']         = $this->getTable();
      $tab[6]['field']         = 'actiontime';
      $tab[6]['name']          = __('Total duration');
      $tab[6]['datatype']      = 'actiontime';
      $tab[6]['massiveaction'] = false;

      $tab[7]['table']         = $this->getTable();
      $tab[7]['field']         = 'state';
      $tab[7]['name']          = __('Status');
      $tab[7]['datatype']      = 'specific';

      return $tab;
   }

   /**
    * @since version 0.85
   **/
   static function getSearchOptionsToAdd() {

      $task                      = new static();

      $tab                       = array();

      $tab['task']               = _n('Task', 'Tasks', Session::getPluralNumber());

      $tab[26]['table']          = static::getTable();
      $tab[26]['field']          = 'content';
      $tab[26]['name']           = __('Description');
      $tab[26]['datatype']       = 'text';
      $tab[26]['forcegroupby']   = true;
      $tab[26]['splititems']     = true;
      $tab[26]['massiveaction']  = false;
      $tab[26]['joinparams']     = array('jointype' => 'child');

      $tab[28]['table']          = static::getTable();
      $tab[28]['field']          = 'id';
      $tab[28]['name']           = _x('quantity', 'Number of tasks');
      $tab[28]['forcegroupby']   = true;
      $tab[28]['usehaving']      = true;
      $tab[28]['datatype']       = 'count';
      $tab[28]['massiveaction']  = false;
      $tab[28]['joinparams']     = array('jointype' => 'child');

      $tab[20]['table']          = 'glpi_taskcategories';
      $tab[20]['field']          = 'name';
      $tab[20]['datatype']       = 'dropdown';
      $tab[20]['name']           = __('Task category');
      $tab[20]['forcegroupby']   = true;
      $tab[20]['splititems']     = true;
      $tab[20]['massiveaction']  = false;
      $tab[20]['joinparams']     = array('beforejoin'
                                          => array('table'      => static::getTable(),
                                                   'joinparams' => array('jointype' => 'child')));

      if ($task->maybePrivate()) {
         $tab[92]['table']          = static::getTable();
         $tab[92]['field']          = 'is_private';
         $tab[92]['name']           = __('Private task');
         $tab[92]['datatype']       = 'bool';
         $tab[92]['forcegroupby']   = true;
         $tab[92]['splititems']     = true;
         $tab[92]['massiveaction']  = false;
         $tab[92]['joinparams']     = array('jointype' => 'child');
      }

      $tab[94]['table']          = 'glpi_users';
      $tab[94]['field']          = 'name';
      $tab[94]['name']           = __('Writer');
      $tab[94]['datatype']       = 'itemlink';
      $tab[94]['right']          = 'all';
      $tab[94]['forcegroupby']   = true;
      $tab[94]['massiveaction']  = false;
      $tab[94]['joinparams']     = array('beforejoin'
                                          => array('table'      => static::getTable(),
                                                   'joinparams' => array('jointype' => 'child')));
      $tab[95]['table']          = 'glpi_users';
      $tab[95]['field']          = 'name';
      $tab[95]['linkfield']      = 'users_id_tech';
      $tab[95]['name']           = __('Technician');
      $tab[95]['datatype']       = 'itemlink';
      $tab[95]['right']          = 'own_ticket';
      $tab[95]['forcegroupby']   = true;
      $tab[95]['massiveaction']  = false;
      $tab[95]['joinparams']     = array('beforejoin'
                                          => array('table'      => static::getTable(),
                                                   'joinparams' => array('jointype'  => 'child')));

      $tab[96]['table']          = static::getTable();
      $tab[96]['field']          = 'actiontime';
      $tab[96]['name']           = __('Duration');
      $tab[96]['datatype']       = 'timestamp';
      $tab[96]['massiveaction']  = false;
      $tab[96]['forcegroupby']   = true;
      $tab[96]['joinparams']     = array('jointype' => 'child');

      $tab[97]['table']          = static::getTable();
      $tab[97]['field']          = 'date';
      $tab[97]['name']           = __('Date');
      $tab[97]['datatype']       = 'datetime';
      $tab[97]['massiveaction']  = false;
      $tab[97]['forcegroupby']   = true;
      $tab[97]['joinparams']     = array('jointype' => 'child');

      $tab[33]['table']          = static::getTable();
      $tab[33]['field']          = 'state';
      $tab[33]['name']           = __('Status');
      $tab[33]['datatype']       = 'specific';
      $tab[33]['searchtype']     = 'equals';
      $tab[33]['searchequalsonfield'] = true;
      $tab[33]['massiveaction']  = false;
      $tab[33]['forcegroupby']   = true;
      $tab[33]['joinparams']     = array('jointype' => 'child');

      return $tab;
   }

   /**
    * Current dates are valid ? begin before end
    *
    * @param $input
    *
    *@return boolean
   **/
   function test_valid_date($input) {

      return (!empty($input["begin"])
              && !empty($input["end"])
              && (strtotime($input["begin"]) < strtotime($input["end"])));
   }

   /**
    * Populate the planning with planned tasks
    *
    * @param $itemtype  itemtype
    * @param $options   array    of options must contains :
    *    - who ID of the user (0 = undefined)
    *    - who_group ID of the group of users (0 = undefined)
    *    - begin Date
    *    - end Date
    *
    * @return array of planning item
   **/
   static function genericPopulatePlanning($itemtype, $options=array()) {
      global $DB, $CFG_GLPI;

      $interv = array();

      if (!isset($options['begin']) || ($options['begin'] == 'NULL')
          || !isset($options['end']) || ($options['end'] == 'NULL')) {
         return $interv;
      }

      if (!$item = getItemForItemtype($itemtype)) {
         return;
      }
      $parentitemtype = $item->getItilObjectItemType();
      if (!$parentitem = getItemForItemtype($parentitemtype)) {
         return;
      }

      $who       = $options['who'];
      $who_group = $options['who_group'];
      $begin     = $options['begin'];
      $end       = $options['end'];

      // Get items to print
      $ASSIGN = "";

      if ($who_group === "mine") {
         if (count($_SESSION["glpigroups"])) {
            $groups = implode("','",$_SESSION['glpigroups']);
            $ASSIGN = "`".$item->getTable()."`.`users_id_tech`
                           IN (SELECT DISTINCT `users_id`
                               FROM `glpi_groups_users`
                               INNER JOIN `glpi_groups`
                                  ON (`glpi_groups_users`.`groups_id` = `glpi_groups`.`id`)
                               WHERE `glpi_groups_users`.`groups_id` IN ('$groups')
                                     AND `glpi_groups`.`is_assign`)
                                     AND ";
         } else { // Only personal ones
            $ASSIGN = "`".$item->getTable()."`.`users_id_tech` = '$who'
                       AND ";
         }

      } else {
         if ($who > 0) {
            $ASSIGN = "`".$item->getTable()."`.`users_id_tech` = '$who'
                       AND ";
         }

         if ($who_group > 0) {
            $ASSIGN = "`".$item->getTable()."`.`users_id_tech` IN (SELECT `users_id`
                                                                   FROM `glpi_groups_users`
                                                                   WHERE `groups_id` = '$who_group')
                                                                         AND ";
         }
      }
      if (empty($ASSIGN)) {
         $ASSIGN = "`".$item->getTable()."`.`users_id_tech`
                        IN (SELECT DISTINCT `glpi_profiles_users`.`users_id`
                            FROM `glpi_profiles`
                            LEFT JOIN `glpi_profiles_users`
                                 ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`)
                            WHERE `glpi_profiles`.`interface` = 'central' ".
                                  getEntitiesRestrictRequest("AND", "glpi_profiles_users", '',
                                                             $_SESSION["glpiactive_entity"], 1).")
                     AND ";
      }

      $addrestrict = '';
      if ($parentitem->maybeDeleted()) {
         $addrestrict = 'AND NOT `'.$parentitem->getTable().'`.`is_deleted`';
      }

      $query = "SELECT `".$item->getTable()."`.*
                FROM `".$item->getTable()."`
                INNER JOIN `".$parentitem->getTable()."`
                  ON (`".$parentitem->getTable()."`.`id` = `".$item->getTable()."`.`".$parentitem->getForeignKeyField()."`)
                WHERE $ASSIGN
                      '$begin' < `".$item->getTable()."`.`end`
                      AND '$end' > `".$item->getTable()."`.`begin`
                      $addrestrict
                ORDER BY `".$item->getTable()."`.`begin`";

      $result = $DB->query($query);

      $interv = array();

      if ($DB->numrows($result) > 0) {
         for ($i=0 ; $data=$DB->fetch_assoc($result) ; $i++) {
            if ($item->getFromDB($data["id"])) {
               if ($parentitem->getFromDBwithData($item->fields[$parentitem->getForeignKeyField()],0)) {
                  $key = $data["begin"]."$$$".$i;
                  // Do not check entity here because webcal used non authenticated access
//                  if (Session::haveAccessToEntity($item->fields["entities_id"])) {
                     $interv[$key]['itemtype']  = $itemtype;
                     $interv[$data["begin"]."$$$".$i]["url"]
                                                = $CFG_GLPI["url_base"]."/index.php?redirect=".
                                                   $parentitemtype."_".
                                                   $item->fields[$parentitem->getForeignKeyField()];

                     $interv[$key][$item->getForeignKeyField()] = $data["id"];
                     $interv[$key]["id"]                        = $data["id"];
                     if (isset($data["state"])) {
                        $interv[$key]["state"]                  = $data["state"];
                     }
                     $interv[$key][$parentitem->getForeignKeyField()]
                                                     = $item->fields[$parentitem->getForeignKeyField()];
                     $interv[$key]["users_id"]       = $data["users_id"];
                     $interv[$key]["users_id_tech"]  = $data["users_id_tech"];

                     if (strcmp($begin,$data["begin"]) > 0) {
                        $interv[$key]["begin"] = $begin;
                     } else {
                        $interv[$key]["begin"] = $data["begin"];
                     }

                     if (strcmp($end,$data["end"]) < 0) {
                        $interv[$key]["end"] = $end;
                     } else {
                        $interv[$key]["end"] = $data["end"];
                     }

                     $interv[$key]["name"]     = $parentitem->fields["name"];
                     $interv[$key]["content"]  = Html::resume_text($parentitem->fields["content"],
                                                                   $CFG_GLPI["cut"]);
                     $interv[$key]["status"]   = $parentitem->fields["status"];
                     $interv[$key]["priority"] = $parentitem->fields["priority"];

                     /// Specific for tickets
                     $interv[$key]["device"] = '';
                     if (isset($parentitem->hardwaredatas) && !empty($parentitem->hardwaredatas)) {
                        foreach($parentitem->hardwaredatas as $hardwaredata){
                           $interv[$key]["device"][$hardwaredata->fields['id']] = ($hardwaredata
                                                      ? $hardwaredata->getName() :'');
                        }
                        $interv[$key]["device"] = implode("<br>", $interv[$key]["device"]);
                     }
//                  }
               }
            }
         }
      }
      return $interv;
   }

   /**
    * Display a Planning Item
    *
    * @param $itemtype  itemtype
    * @param $val       Array    of the item to display
    *
    * @return Already planned information
   **/
   static function genericGetAlreadyPlannedInformation($itemtype, array $val) {
      global $CFG_GLPI;

      if ($item = getItemForItemtype($itemtype)) {
         $objectitemtype = $item->getItilObjectItemType();

         //TRANS: %1$s is a type, %2$$ is a date, %3$s is a date
         $out  = sprintf(__('%1$s: from %2$s to %3$s:'), $item->getTypeName(1),
                         Html::convDateTime($val["begin"]), Html::convDateTime($val["end"]));
         $out .= "<br><a href='".Toolbox::getItemTypeFormURL($objectitemtype)."?id=".
                       $val[getForeignKeyFieldForItemType($objectitemtype)]."&forcetab=".$itemtype."$1'>";
         $out .= Html::resume_text($val["name"],80).'</a>';

         return $out;
      }
   }

   /**
    * Display a Planning Item
    *
    * @param $itemtype  itemtype
    * @param $val       Array of the item to display
    * @param $who             ID of the user (0 if all)
    * @param $type            position of the item in the time block (in, through, begin or end)
    *                         (default '')
    * @param $complete        complete display (more details) (default 0)
    *
    * @return Nothing (display function)
   **/
   static function genericDisplayPlanningItem($itemtype, array $val, $who, $type="", $complete=0) {
      global $CFG_GLPI;

      $rand      = mt_rand();
      $styleText = "";
      if (isset($val["state"])) {
         switch ($val["state"]) {
            case 2 : // Done
               $styleText = "color:#747474;";
               break;
         }
      }

      $parenttype = str_replace('Task','',$itemtype);
      if ($parent = getItemForItemtype($parenttype)) {
         $parenttype_fk = $parent->getForeignKeyField();
      } else {
         return;
      }

      echo "<img src='".$CFG_GLPI["root_doc"]."/pics/rdv_interv.png' alt='' title=\"".
             Html::entities_deep($parent->getTypeName(1))."\">  ";
      echo "<img src='".$parent->getStatusIconURL($val["status"])."' alt='".
             Html::entities_deep($parent->getStatus($val["status"]))."' title=\"".
             Html::entities_deep($parent->getStatus($val["status"]))."\">";
      echo " <a id='content_tracking_".$val["id"].$rand."'
                   href='".Toolbox::getItemTypeFormURL($parenttype)."?id=".$val[$parenttype_fk]."'
                   style='$styleText'>";

      switch ($type) {
         case "in" :
            //TRANS: %1$s is the start time of a planned item, %2$s is the end
            printf(__('From %1$s to %2$s :'),
                   date("H:i",strtotime($val["begin"])), date("H:i",strtotime($val["end"]))) ;
            break;

         case "through" :
            break;

         case "begin" :
            //TRANS: %s is the start time of a planned item
            printf(__('Start at %s:'), date("H:i", strtotime($val["begin"]))) ;
            break;

         case "end" :
            //TRANS: %s is the end time of a planned item
            printf(__('End at %s:'), date("H:i", strtotime($val["end"]))) ;
            break;
      }

      echo "<br>";
      //TRANS: %1$s is name of the item, %2$d is its ID
      printf(__('%1$s (#%2$d)'), Html::resume_text($val["name"],80), $val[$parenttype_fk]);

      if (!empty($val["device"])) {
         echo "<br>".$val["device"];
      }

      if ($who <= 0) { // show tech for "show all and show group"
         echo "<br>";
         //TRANS: %s is user name
         printf(__('By %s'), getUserName($val["users_id_tech"]));
      }

      echo "</a>";

      $recall = '';
      if (isset($val[getForeignKeyFieldForItemType($itemtype)])
          && PlanningRecall::isAvailable()) {
         $pr = new PlanningRecall();
         if ($pr->getFromDBForItemAndUser($val['itemtype'],
                                          $val[getForeignKeyFieldForItemType($itemtype)],
                                          Session::getLoginUserID())) {
            $recall = "<br><span class='b'>".sprintf(__('Recall on %s'),
                                                     Html::convDateTime($pr->fields['when'])).
                      "<span>";
         }
      }

      if ($complete) {
         echo "<br><span class='b'>";
         if (isset($val["state"])) {
            echo Planning::getState($val["state"])."<br>";
         }
         echo sprintf(__('%1$s: %2$s'), __('Priority'), $parent->getPriorityName($val["priority"]));
         echo "<br>".__('Description')."</span><br>".$val["content"];
         echo $recall;

      } else {
         $content = "<div class='b'>";
         if (isset($val["state"])) {
            $content .= Planning::getState($val["state"])."<br>";
         }
         $content .= sprintf(__('%1$s: %2$s'), __('Priority'), $parent->getPriorityName($val["priority"])).
                    "<br>".__('Description')."</div>".
                    Html::entity_decode_deep($val["content"].$recall);
         Html::showToolTip($content, array('applyto' => "content_tracking_".$val["id"].$rand));
      }
   }

   /**
    * @param $item         CommonITILObject
    * @param $rand
    * @param $showprivate  (false by default)
   **/
   function showInObjectSumnary(CommonITILObject $item, $rand, $showprivate=false) {
      global $DB, $CFG_GLPI;

      $canedit = $this->canEdit($this->fields['id']);

      echo "<tr class='tab_bg_";
      if ($this->maybePrivate()
          && ($this->fields['is_private'] == 1)) {
         echo "4' ";
      } else {
         echo "2' ";
      }

      if ($canedit) {
         echo "style='cursor:pointer' onClick=\"viewEditTask".$item->fields['id'].
               $this->fields['id']."$rand();\"";
      }

      echo " id='viewfollowup" . $this->fields[$item->getForeignKeyField()] . $this->fields["id"] .
            "$rand'>";

      echo "<td>";
      switch ($this->fields['state']) {
         case Planning::INFO :
            echo Html::image($CFG_GLPI['root_doc']."/pics/faqedit.png",
                             array('title' =>_n('Information', 'Information', 1)));
            break;

         case Planning::TODO :
            if (empty($this->fields['begin'])) {
               echo Html::image($CFG_GLPI['root_doc']."/pics/redbutton.png",
                                array('title' => __('To do')));
            } else {
               echo Html::image($CFG_GLPI['root_doc']."/pics/rdv.png",
                                array('title' => __('Planned')));
            }
            break;

         case Planning::DONE :
            echo Html::image($CFG_GLPI['root_doc']."/pics/greenbutton.png",
                             array('title' => __('Done')));
            break;
      }
      echo "</td>";

      echo "<td>";
      $typename = $this->getTypeName(1);
      if ($this->fields['taskcategories_id']) {
         printf(__('%1$s - %2$s'), $typename,
                Dropdown::getDropdownName('glpi_taskcategories',
                                          $this->fields['taskcategories_id']));
      } else {
         echo $typename;
      }
      echo "</td>";

      echo "<td>";
      if ($canedit) {
         echo "\n<script type='text/javascript' >\n";
         echo "function viewEditTask" . $item->fields['id'] . $this->fields["id"] . "$rand() {\n";
         $params = array('type'       => $this->getType(),
                         'parenttype' => $item->getType(),
                         $item->getForeignKeyField()
                                      => $this->fields[$item->getForeignKeyField()],
                         'id'         => $this->fields["id"]);
         Ajax::updateItemJsCode("viewfollowup" . $item->fields['id'] . "$rand",
                                $CFG_GLPI["root_doc"]."/ajax/viewsubitem.php", $params);
         echo "};";
         echo "</script>\n";
      }
      //else echo "--no--";
      echo Html::convDateTime($this->fields["date"]) . "</td>";
      echo "<td class='left'>" . nl2br($this->fields["content"]) . "</td>";
      echo "<td>";
      echo Html::timestampToString($this->fields["actiontime"], 0);

      echo "</td>";
      echo "<td>" . getUserName($this->fields["users_id"]) . "</td>";
      if ($this->maybePrivate() && $showprivate) {
         echo "<td>".Dropdown::getYesNo($this->fields["is_private"])."</td>";
      }

      echo "<td>";

      if (empty($this->fields["begin"])) {
         if (isset($this->fields["state"])) {
            echo Planning::getState($this->fields["state"])."<br>";
         }
         if ($this->fields["users_id_tech"]) {
            echo sprintf('%1$s %2$s',__('By'),getUserName($this->fields["users_id_tech"]));
         } else {
            _e('None');
         }
      } else {
         echo "<table width='100%'>";
         if (isset($this->fields["state"])) {
            echo "<tr><td>"._x('item', 'State')."</td><td>";
            echo Planning::getState($this->fields["state"])."</td></tr>";
         }
         echo "<tr><td>".__('Begin')."</td><td>";
         echo Html::convDateTime($this->fields["begin"])."</td></tr>";
         echo "<tr><td>".__('End')."</td><td>";
         echo Html::convDateTime($this->fields["end"])."</td></tr>";
         echo "<tr><td>".__('By')."</td><td>";
         echo getUserName($this->fields["users_id_tech"])."</td></tr>";
         if (PlanningRecall::isAvailable()
             && $_SESSION["glpiactiveprofile"]["interface"] == "central") {
            echo "<tr><td>"._x('Planning','Reminder')."</td><td>";
            PlanningRecall::specificForm(array('itemtype' => $this->getType(),
                                               'items_id' => $this->fields["id"]));

            echo "</td></tr>";
         }
         echo "</table>";
      }
      echo "</td>";

      echo "</tr>\n";
   }

   /** form for Task
    *
    * @param $ID        Integer : Id of the task
    * @param $options   array
    *     -  parent Object : the object
   **/
   function showForm($ID, $options=array()) {
      global $DB, $CFG_GLPI;

      if (isset($options['parent']) && !empty($options['parent'])) {
         $item = $options['parent'];
      }

      $fkfield = $item->getForeignKeyField();

      if ($ID > 0) {
         $this->check($ID, READ);
      } else {
         // Create item
         $options[$fkfield] = $item->getField('id');
         $this->check(-1, CREATE, $options);
      }

      $rand = mt_rand();
      $this->showFormHeader($options);

      $canplan = (!$item->isStatusExists(CommonITILObject::PLANNED)
                  || $item->isAllowedStatus($item->fields['status'], CommonITILObject::PLANNED));

      $rowspan = 3 ;
      if ($this->maybePrivate()) {
         $rowspan++;
      }
      if (isset($this->fields["state"])) {
         $rowspan++;
      }
      echo "<tr class='tab_bg_1'>";
      echo "<td rowspan='$rowspan' class='middle'>".__('Description')."</td>";
      echo "<td class='center middle' rowspan='$rowspan'>".
           "<textarea id ='content$rand' name='content' cols='50' rows='$rowspan'>"
           .$this->fields["content"].
           "</textarea>";
      echo Html::scriptBlock("$(document).ready(function() { $('#content$rand').autogrow(); });");
      echo "</td>";
      if ($ID > 0) {
         echo "<td>".__('Date')."</td>";
         echo "<td>";
         Html::showDateTimeField("date", array('value'      => $this->fields["date"],
                                               'timestep'   => 1,
                                               'maybeempty' => false));
      } else {
         echo "<td colspan='2'> ";
      }
      echo "<input type='hidden' name='$fkfield' value='".$this->fields[$fkfield]."'>";
      echo "</td></tr>\n";

      echo "<tr class='tab_bg_1'>";
      echo "<td>".__('Category')."</td><td>";
      TaskCategory::dropdown(array('value'  => $this->fields["taskcategories_id"],
                                   'entity' => $item->fields["entities_id"]));
      echo "</td></tr>\n";

      if (isset($this->fields["state"])) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>".__('Status')."</td><td>";
         Planning::dropdownState("state", $this->fields["state"]);
         echo "</td></tr>\n";
      }

      if ($this->maybePrivate()) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>".__('Private')."</td>";
         echo "<td>";
         Dropdown::showYesNo('is_private',$this->fields["is_private"]);
         echo "</td>";
         echo "</tr>";
      }

      echo "<tr class='tab_bg_1'>";
      echo "<td>". __('Duration')."</td><td>";

      $toadd = array();
      for ($i=9 ; $i<=100 ; $i++) {
         $toadd[] = $i*HOUR_TIMESTAMP;
      }

      Dropdown::showTimeStamp("actiontime", array('min'             => 0,
                                                  'max'             => 8*HOUR_TIMESTAMP,
                                                  'value'           => $this->fields["actiontime"],
                                                  'addfirstminutes' => true,
                                                  'inhours'         => true,
                                                  'toadd'           => $toadd));

      echo "</td></tr>\n";

      if ($ID <= 0) {
         Document_Item::showSimpleAddForItem($item);
      }

      echo "<tr class='tab_bg_1'>";
      echo "<td>".__('By');
      echo " <a href='#' onClick=\"".Html::jsGetElementbyID('planningcheck'.$rand).".dialog('open');\">";
      echo "<img src='".$CFG_GLPI["root_doc"]."/pics/reservation-3.png'
             title=\"".__s('Availability')."\" alt=\"".__s('Availability')."\"
             class='calendrier'>";
      echo "</a>";
      Ajax::createIframeModalWindow('planningcheck'.$rand,
                                    $CFG_GLPI["root_doc"].
                                          "/front/planning.php?checkavailability=checkavailability".
                                          "&itemtype=".$item->getType()."&$fkfield=".$item->getID(),
                                    array('title'  => __('Availability')));

      echo "</td>";
      echo "<td class='center'>";
      $rand_user          = mt_rand();
      $params             = array('name'   => "users_id_tech",
                                  'value'  => (($ID > -1)
                                                ?$this->fields["users_id_tech"]
                                                :Session::getLoginUserID()),
                                  'right'  => "own_ticket",
                                  'rand'   => $rand_user,
                                  'entity' => $item->fields["entities_id"]);

      $params['toupdate'] = array('value_fieldname'
                                              => 'users_id',
                                  'to_update' => "user_available$rand_user",
                                  'url'       => $CFG_GLPI["root_doc"]."/ajax/planningcheck.php");

      User::dropdown($params);
      echo "</td>\n";
      if ($canplan) {
         echo "<td>".__('Planning')."</td>";
      }
      echo "<td>";

      if (!empty($this->fields["begin"])) {

         if (Session::haveRight('planning', Planning::READMY)) {
            echo "<script type='text/javascript' >\n";
            echo "function showPlan".$ID."() {\n";
            echo Html::jsHide('plan');
            $params = array('form'      => 'followups',
                            'users_id'  => $this->fields["users_id_tech"],
                            'id'        => $this->fields["id"],
                            'begin'     => $this->fields["begin"],
                            'end'       => $this->fields["end"],
                            'rand_user' => $rand_user,
                            'entity'    => $item->fields["entities_id"],
                            'itemtype'  => $this->getType(),
                            'items_id'  => $this->getID());
            Ajax::updateItemJsCode('viewplan', $CFG_GLPI["root_doc"] . "/ajax/planning.php",
                                   $params);
            echo "}";
            echo "</script>\n";
            echo "<div id='plan' onClick='showPlan".$ID."()'>\n";
            echo "<span class='showplan'>";
         }

         if (isset($this->fields["state"])) {
            echo Planning::getState($this->fields["state"])."<br>";
         }
         printf(__('From %1$s to %2$s'), Html::convDateTime($this->fields["begin"]),
                Html::convDateTime($this->fields["end"]));
         echo "<br>".getUserName($this->fields["users_id_tech"]);

         if (Session::haveRight('planning', Planning::READMY)) {
            echo "</span>";
            echo "</div>\n";
            echo "<div id='viewplan'></div>\n";
         }

      } else {
         if ($canplan) {
            echo "<script type='text/javascript' >\n";
            echo "function showPlanUpdate() {\n";
            echo Html::jsHide('plan');
            $params = array('form'     => 'followups',
                            'entity'   => $_SESSION["glpiactive_entity"],
                            'rand_user' => $rand_user,
                            'itemtype' => $this->getType(),
                            'items_id' => $this->getID());
            Ajax::updateItemJsCode('viewplan', $CFG_GLPI["root_doc"]."/ajax/planning.php", $params);
            echo "};";
            echo "</script>";

            if ($canplan) {
               echo "<div id='plan'  onClick='showPlanUpdate()'>\n";
               echo "<span class='vsubmit'>".__('Plan this task')."</span>";
               echo "</div>\n";
               echo "<div id='viewplan'></div>\n";
            }
         } else {
            _e('None');
         }
      }

      echo "</td></tr>";

      if (!empty($this->fields["begin"])
          && PlanningRecall::isAvailable()) {

         echo "<tr class='tab_bg_1'><td>"._x('Planning','Reminder')."</td><td class='center'>";
         PlanningRecall::dropdown(array('itemtype' => $this->getType(),
                                        'items_id' => $this->getID()));
         echo "</td></tr>";
      }

      $this->showFormButtons($options);

      return true;
   }

   /**
    * Show the current task sumnary
    *
    * @param $item   CommonITILObject
   **/
   function showSummary(CommonITILObject $item) {
      global $DB, $CFG_GLPI;

      if (!static::canView()) {
         return false;
      }

      $tID = $item->fields['id'];

      // Display existing Followups
      $showprivate = $this->canViewPrivates();
      $caneditall  = $this->canEditAll();
      $tmp         = array($item->getForeignKeyField() => $tID);
      $canadd      = $this->can(-1, CREATE, $tmp);

      $RESTRICT = "";
      if ($this->maybePrivate() && !$showprivate) {
         $RESTRICT = " AND (`is_private` = '0'
                            OR `users_id` ='" . Session::getLoginUserID() . "') ";
      }

      $query = "SELECT `id`, `date`
                FROM `".$this->getTable()."`
                WHERE `".$item->getForeignKeyField()."` = '$tID'
                      $RESTRICT
                ORDER BY `date` DESC";
      $result = $DB->query($query);

      $rand = mt_rand();

      if ($caneditall || $canadd) {
         echo "<div id='viewfollowup" . $tID . "$rand'></div>\n";
      }

      if ($canadd) {
         echo "<script type='text/javascript' >\n";
         echo "function viewAddTask" . $item->fields['id'] . "$rand() {\n";
         $params = array('type'                      => $this->getType(),
                         'parenttype'                => $item->getType(),
                         $item->getForeignKeyField() => $item->fields['id'],
                         'id'                        => -1);
         Ajax::updateItemJsCode("viewfollowup" . $item->fields['id'] . "$rand",
                                $CFG_GLPI["root_doc"]."/ajax/viewsubitem.php", $params);
         echo Html::jsHide('addbutton'.$item->fields['id'] . "$rand");
         echo "};";
         echo "</script>\n";
         if (!in_array($item->fields["status"],
               array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray()))) {
            echo "<div id='addbutton".$item->fields['id'] . "$rand' class='center firstbloc'>".
                 "<a class='vsubmit' href='javascript:viewAddTask".$item->fields['id']."$rand();'>";
            echo __('Add a new task')."</a></div>\n";
         }
      }

      if ($DB->numrows($result) == 0) {
         echo "<table class='tab_cadre_fixe'><tr class='tab_bg_2'><th>" . __('No task found.');
         echo "</th></tr></table>";
      } else {
         echo "<table class='tab_cadre_fixehov'>";

         $header = "<tr><th> </th><th>".__('Type')."</th><th>" . __('Date') . "</th>";
         $header .= "<th>" . __('Description') . "</th><th>" .  __('Duration') . "</th>";
         $header .= "<th>" . __('Writer') . "</th>";
         if ($this->maybePrivate() && $showprivate) {
            $header .= "<th>" . __('Private') . "</th>";
         }
         $header .= "<th>" . __('Planning') . "</th></tr>\n";
         echo $header;

         while ($data = $DB->fetch_assoc($result)) {
            if ($this->getFromDB($data['id'])) {
               $this->showInObjectSumnary($item, $rand, $showprivate);
            }
         }
         echo $header;
         echo "</table>";
      }
   }

   /**
    * Form for Ticket or Problem Task on Massive action
   **/
   function showFormMassiveAction() {

      echo " ".__('Category')." ";
      TaskCategory::dropdown();

      echo "<br>".__('Description')." ";
      echo "<textarea name='content' cols='50' rows='6'></textarea> ";

      if ($this->maybePrivate()) {
         echo "<input type='hidden' name='is_private' value='".$_SESSION['glpitask_private']."'>";
      }

       echo "<br>".__('Duration');

      $toadd = array();
      for ($i=9 ; $i<=100 ; $i++) {
         $toadd[] = $i*HOUR_TIMESTAMP;
      }

      Dropdown::showTimeStamp("actiontime", array('min'             => 0,
                                                  'max'             => 8*HOUR_TIMESTAMP,
                                                  'addfirstminutes' => true,
                                                  'inhours'         => true,
                                                  'toadd'           => $toadd));

      echo "<input type='submit' name='add' value=\""._sx('button', 'Add')."\" class='submit'>";
   }

}
?>

redpajama_set_name: RedPajamaGithub


text:
from __future__ import print_function

import unittest
import numpy
import paddle.fluid as fluid
import paddle.fluid.layers as layers
import paddle.fluid.core as core
from paddle.fluid.contrib.layers import basic_gru
from paddle.fluid.executor import Executor
from paddle.fluid import framework

import numpy as np

SIGMOID_THRESHOLD_MIN = -40.0
SIGMOID_THRESHOLD_MAX = 13.0
EXP_MAX_INPUT = 40.0

def sigmoid(x):
    y = np.copy(x)
    y[x < SIGMOID_THRESHOLD_MIN] = SIGMOID_THRESHOLD_MIN
    y[x > SIGMOID_THRESHOLD_MAX] = SIGMOID_THRESHOLD_MAX
    return 1. / (1. + np.exp(-y))

def tanh(x):
    y = -2. * x
    y[y > EXP_MAX_INPUT] = EXP_MAX_INPUT
    return (2. / (1. + np.exp(y))) - 1.

def gru_np(input,
           init_h,
           hidden_size,
           gate_weight,
           gate_bias,
           candidate_weight,
           candidate_bias,
           num_layers=1,
           batch_first=False,
           is_bidirect=False,
           sequence_length=None):
    def step(step_in, pre_hidden, gate_w, gate_b, candidate_w, candidate_b):
        concat_1 = np.concatenate([step_in, pre_hidden], 1)

        gate_input = np.matmul(concat_1, gate_w)
        gate_input += gate_b
        gate_input = sigmoid(gate_input)
        r, u = np.split(gate_input, indices_or_sections=2, axis=1)

        r_hidden = r * pre_hidden

        candidate = np.matmul(
            np.concatenate([step_in, pre_hidden], 1), candidate_w)

        candidate += candidate_b
        c = tanh(candidate)

        new_hidden = u * pre_hidden + (1 - u) * c

        return new_hidden

    if batch_first:
        input = np.tranpose(input, [1, 0, 2])

    batch_size = input.shape[1]
    mask = None
    if sequence_length is not None:
        max_seq_len = input.shape[0]

        mask = np.zeros([batch_size, max_seq_len])

        for i, len in enumerate(sequence_length):
            mask[i, :len] = 1.0

        mask = np.transpose(mask, [1, 0])

    direc_num = 1
    if is_bidirect:
        direc_num = 2
    if init_h:
        init_h = np.reshape(
            init_h, shape=[num_layers, direc_num, -1, hidden_size])
    else:
        init_h = np.zeros([num_layers, direc_num, batch_size, hidden_size])

    def get_single_direction_output(rnn_input, mask=None, direc_index=0):
        seq_len = rnn_input.shape[0]

        output = []
        # init pre hidden
        pre_hidden_array = []
        for i in range(num_layers):
            pre_hidden_array.append(init_h[i, direc_index])

        for i in range(seq_len):
            step_input = rnn_input[i]

            if mask is not None:
                step_mask = mask[i]
                step_mask = np.reshape(step_mask, [-1, 1])

            for i in range(num_layers):
                new_hidden = step(
                    step_input, pre_hidden_array[i],
                    gate_weight[direc_index * num_layers + i],
                    gate_bias[direc_index * num_layers + i],
                    candidate_weight[direc_index * num_layers + i],
                    candidate_bias[direc_index * num_layers + i])

                if mask is not None:
                    new_hidden = new_hidden * step_mask + (
                        1 - step_mask) * pre_hidden_array[i]

                pre_hidden_array[i] = new_hidden

                step_input = new_hidden
            output.append(step_input)
        rnn_out = np.concatenate(output, 0)
        rnn_out = np.reshape(rnn_out, [seq_len, -1, hidden_size])

        last_hidden_out = np.concatenate(pre_hidden_array, 0)
        last_hidden_out = np.reshape(last_hidden_out,
                                     [num_layers, -1, hidden_size])

        return rnn_out, last_hidden_out

    fw_rnn_out, fw_last_hidden = get_single_direction_output(
        input, mask, direc_index=0)

    if is_bidirect:
        bw_input = input[::-1]
        bw_mask = None
        if mask is not None:
            bw_mask = mask[::-1]

        bw_rnn_out, bw_last_hidden = get_single_direction_output(
            bw_input, bw_mask, direc_index=1)

        bw_rnn_out = bw_rnn_out[::-1]

        rnn_out = np.concatenate([fw_rnn_out, bw_rnn_out], 2)
        last_hidden = np.concatenate([fw_last_hidden, bw_last_hidden], 1)
        last_hidden = np.reshape(last_hidden,
                                 [num_layers * direc_num, -1, hidden_size])

        if batch_first:
            rnn_out = np.transpose(rnn_out, [1, 0, 2])

        return rnn_out, last_hidden
    else:
        rnn_out = fw_rnn_out
        last_hidden = fw_last_hidden

        if batch_first:
            rnn_out = np.transpose(rnn_out, [1, 0, 2])

        return rnn_out, last_hidden

class TestBasicGRUApi(unittest.TestCase):
    def setUp(self):
        self.hidden_size = 10
        self.batch_size = 5
        self.seq_len = 6
        self.num_layers = 2
        self.is_bidirect = True
        self.batch_first = False

    def test_run(self):
        x = layers.data(
            name='x',
            shape=[-1, self.batch_size, self.hidden_size],
            dtype='float32')
        sequence_length = layers.data(
            name="sequence_length", shape=[-1], dtype='float32')

        rnn_out, last_hidden = basic_gru( x, None, self.hidden_size, num_layers=self.num_layers, \
                batch_first = self.batch_first, bidirectional=self.is_bidirect, sequence_length=sequence_length )

        last_hidden.persisbale = True
        rnn_out.persisbale = True

        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
        else:
            place = core.CPUPlace()

        exe = Executor(place)
        exe.run(framework.default_startup_program())

        param_list = fluid.default_main_program().block(0).all_parameters()

        # process weight and bias
        gate_weight = []
        gate_bias = []
        candidate_weight = []
        candidate_bias = []

        for i in range(self.num_layers):
            gate_w_name = "basic_gru_layers_" + str(i) + "/BasicGRUUnit_0.w_0"
            gate_b_name = "basic_gru_layers_" + str(i) + "/BasicGRUUnit_0.b_0"
            candidate_w_name = "basic_gru_layers_" + str(
                i) + "/BasicGRUUnit_0.w_1"
            candidate_b_name = "basic_gru_layers_" + str(
                i) + "/BasicGRUUnit_0.b_1"

            gate_w = np.array(fluid.global_scope().find_var(gate_w_name)
                              .get_tensor())
            gate_w = np.random.uniform(
                -0.1, 0.1, size=gate_w.shape).astype('float32')
            fluid.global_scope().find_var(gate_w_name).get_tensor().set(gate_w,
                                                                        place)

            gate_b = np.array(fluid.global_scope().find_var(gate_b_name)
                              .get_tensor())
            gate_b = np.random.uniform(
                -0.1, 0.1, size=gate_b.shape).astype('float32')
            fluid.global_scope().find_var(gate_b_name).get_tensor().set(gate_b,
                                                                        place)

            candidate_w = np.array(fluid.global_scope().find_var(
                candidate_w_name).get_tensor())
            candidate_w = np.random.uniform(
                -0.1, 0.1, size=candidate_w.shape).astype('float32')
            fluid.global_scope().find_var(candidate_w_name).get_tensor().set(
                candidate_w, place)

            candidate_b = np.array(fluid.global_scope().find_var(
                candidate_b_name).get_tensor())
            candidate_b = np.random.uniform(
                -0.1, 0.1, size=candidate_b.shape).astype('float32')
            fluid.global_scope().find_var(candidate_b_name).get_tensor().set(
                candidate_b, place)

            gate_weight.append(gate_w)
            gate_bias.append(gate_b)
            candidate_weight.append(candidate_w)
            candidate_bias.append(candidate_b)

        if self.is_bidirect:
            for i in range(self.num_layers):
                gate_w_name = "basic_gru_reverse_layers_" + str(
                    i) + "/BasicGRUUnit_0.w_0"
                gate_b_name = "basic_gru_reverse_layers_" + str(
                    i) + "/BasicGRUUnit_0.b_0"
                candidate_w_name = "basic_gru_reverse_layers_" + str(
                    i) + "/BasicGRUUnit_0.w_1"
                candidate_b_name = "basic_gru_reverse_layers_" + str(
                    i) + "/BasicGRUUnit_0.b_1"

                gate_w = np.array(fluid.global_scope().find_var(gate_w_name)
                                  .get_tensor())
                gate_w = np.random.uniform(
                    -0.1, 0.1, size=gate_w.shape).astype('float32')
                fluid.global_scope().find_var(gate_w_name).get_tensor().set(
                    gate_w, place)

                gate_b = np.array(fluid.global_scope().find_var(gate_b_name)
                                  .get_tensor())
                gate_b = np.random.uniform(
                    -0.1, 0.1, size=gate_b.shape).astype('float32')
                fluid.global_scope().find_var(gate_b_name).get_tensor().set(
                    gate_b, place)

                candidate_w = np.array(fluid.global_scope().find_var(
                    candidate_w_name).get_tensor())
                candidate_w = np.random.uniform(
                    -0.1, 0.1, size=candidate_w.shape).astype('float32')
                fluid.global_scope().find_var(candidate_w_name).get_tensor(
                ).set(candidate_w, place)

                candidate_b = np.array(fluid.global_scope().find_var(
                    candidate_b_name).get_tensor())
                candidate_b = np.random.uniform(
                    -0.1, 0.1, size=candidate_b.shape).astype('float32')
                fluid.global_scope().find_var(candidate_b_name).get_tensor(
                ).set(candidate_b, place)

                gate_weight.append(gate_w)
                gate_bias.append(gate_b)
                candidate_weight.append(candidate_w)
                candidate_bias.append(candidate_b)

        step_input_np = np.random.uniform(-0.1, 0.1, (
            self.seq_len, self.batch_size, self.hidden_size)).astype('float32')
        sequence_length_np = np.random.randint(
            self.seq_len // 2, self.seq_len,
            size=(self.batch_size)).astype('int64')

        out = exe.run(
            feed={'x': step_input_np,
                  'sequence_length': sequence_length_np},
            fetch_list=[rnn_out, last_hidden])

        api_rnn_out = out[0]
        api_last_hidden = out[1]

        np_out = gru_np(
            step_input_np,
            None,
            self.hidden_size,
            gate_weight,
            gate_bias,
            candidate_weight,
            candidate_bias,
            num_layers=self.num_layers,
            batch_first=self.batch_first,
            is_bidirect=self.is_bidirect,
            sequence_length=sequence_length_np)

        self.assertTrue(np.allclose(api_rnn_out, np_out[0], rtol=1e-4, atol=0))

        self.assertTrue(
            np.allclose(
                api_last_hidden, np_out[1], rtol=1e-4, atol=0))

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


text:
namespace Quartz { namespace Ext { namespace WebTech {

struct Conf {
    static const QString CONF_DOMAIN;
    static const QString EDITOR_THEME;
    static const QString EDITOR_VLINE_NUM;
    static const QString EDITOR_SHOW_MINIMAP;
    static const QString EDITOR_SHOW_LINENUM;
};

template <typename T>
T conf(const QString& key, const T& def = {}) {
    return confman()->get<T>(key, def, Conf::CONF_DOMAIN);
}

// template<typename T>
// void setConf(const QString &key, const T& val)
//{
//    confman()->set<T>(key, val, Conf::CONF_DOMAIN);
//}

inline void setConf(const QString& key, const QVariant& value) {
    confman()->store(key, value, Conf::CONF_DOMAIN);
}

}}} // namespace Quartz::Ext::WebTech


text:
import {TestBed, waitForAsync} from '@angular/core/testing';
import {AppComponent} from './app.component';

describe('AppComponent', () => {
  beforeEach(waitForAsync(() => {
    TestBed
        .configureTestingModule({
          declarations: [AppComponent],
        })
        .compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'cli-hello-world-ivy-compat'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('cli-hello-world-ivy-compat');
  });

  it('should render title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('.content span').textContent)
        .toContain('cli-hello-world-ivy-compat app is running!');
  });
});


text:
/* MACHINE GENERATED FILE, DO NOT EDIT */

package org.lwjgl.opengles;

import org.lwjgl.*;
import java.nio.*;

public final class EXTTextureCompressionS3TC {

	/**
	 *  Accepted by the <internalformat> parameter of TexImage2D, CopyTexImage2D,
	 *  and CompressedTexImage2D and the <format> parameter of
	 *  CompressedTexSubImage2D:
	 */
	public static final int GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
		GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1,
		GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2,
		GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3;

	private EXTTextureCompressionS3TC() {}
}


text:
Toast-Swift
=============

[![Build Status](https://travis-ci.org/scalessec/Toast-Swift.svg?branch=master)](https://travis-ci.org/scalessec/Toast-Swift)
[![CocoaPods Version](https://img.shields.io/cocoapods/v/Toast-Swift.svg)](http://cocoadocs.org/docsets/Toast-Swift)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Toast-Swift is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code.

**Toast-Swift is a native Swift port of [Toast for iOS](https://github.com/scalessec/Toast "Toast for iOS").**

Screenshots
---------
![Toast-Swift Screenshots](toast_swift_screenshot.jpg)

Basic Examples
---------
```swift
// basic usage
self.view.makeToast("This is a piece of toast")

// toast with a specific duration and position
self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)

// toast presented with multiple options and with a completion closure
self.view.makeToast("This is a piece of toast", duration: 2.0, point: CGPoint(x: 110.0, y: 110.0), title: "Toast Title", image: UIImage(named: "toast.png")) { didTap in
    if didTap {
        print("completion from tap")
    } else {
        print("completion without tap")
    }
}

// display toast with an activity spinner
self.view.makeToastActivity(.center)

// display any view as toast
self.view.showToast(myView)

// immediately hides all toast views in self.view
self.view.hideAllToasts()
```

But wait, there's more!
---------
```swift
// create a new style
var style = ToastStyle()

// this is just one of many style options
style.messageColor = .blue

// present the toast with the new style
self.view.makeToast("This is a piece of toast", duration: 3.0, position: .bottom, style: style)

// or perhaps you want to use this style for all toasts going forward?
// just set the shared style and there's no need to provide the style again
ToastManager.shared.style = style
self.view.makeToast("This is a piece of toast") // now uses the shared style

// toggle "tap to dismiss" functionality
ToastManager.shared.isTapToDismissEnabled = true

// toggle queueing behavior
ToastManager.shared.isQueueEnabled = true
```

See the demo project for more examples.

Setup Instructions
------------------

[CocoaPods](http://cocoapods.org)
------------------

To integrate Toast-Swift into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
pod 'Toast-Swift', '~> 5.0.1'
```

and in your code add `import Toast_Swift`.

[Carthage](https://github.com/Carthage/Carthage)
------------------

To integrate Toast-Swift into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "scalessec/Toast-Swift" ~> 5.0.1
```

Run `carthage update` to build the framework and drag the built `ToastSwiftFramework.framework` into your Xcode project.

and in your code add `import ToastSwiftFramework`.

[Swift Package Manager](https://swift.org/package-manager/)
------------------

When using Xcode 11 or later, you can install `Toast` by going to your Project settings > `Swift Packages` and add the repository by providing the GitHub URL. Alternatively, you can go to `File` > `Swift Packages` > `Add Package Dependencies...`

Manually
------------------

1. Add `Toast.swift` to your project.
2. Grab yourself a cold 🍺.

Compatibility
------------------
* Version `5.x.x` requires Swift 5 and Xcode 10.2 (or newer versions of Xcode).
* Version `4.x.x` requires Swift 4.2 and Xcode 10.
* Version `3.x.x` requires Swift 4 and Xcode 9.
* Version `2.x.x` requires Swift 3 and Xcode 8.
* Version `1.4.x` requires Swift 2.2 and Xcode 7.3.
* Version `1.0.0` can be used with Swift 2.1 and earlier versions of Xcode.

MIT License
-----------
    Copyright (c) 2015-2019 Charles Scalesse.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package com.orange.oss.cloudfoundry.cscpi.boshregistry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

/**
 * bosh registry client see
 * https://github.com/cloudfoundry/bosh/blob/master/bosh
 * -registry/spec/unit/bosh/registry/api_controller_spec.rb
 *
 * @author poblin
 *
 */
public class BoshRegistryClientImpl implements BoshRegistryClient {

	private static Logger logger = LoggerFactory.getLogger(BoshRegistryClientImpl.class.getName());

	@Value("${cpi.registry.endpoint}")
	String endpoint;

	@Value("${cpi.registry.user}")
	String user;

	@Value("${cpi.registry.password}")
	String password;

	@Override
	public void put(String vm_id, String settings) {

		String uri = this.endpoint+"/instances/" + vm_id;
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.postForObject(uri, settings, String.class);

	}

	@Override
	public String get(String vm_id) {
		String uri = this.endpoint+"/instances/" + vm_id + "/settings";
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject(uri, String.class);
		return result;
	}

	@Override
	public String getRaw(String vm_id) {
		String uri = this.endpoint+"/instances/" + vm_id + "/rawsettings";
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.getForObject(uri, String.class);
		return result;
	}

	@Override
	public void delete(String vm_id) {
		String uri = this.endpoint+"instances/" + vm_id;
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.delete(uri);

	}

}


text:
.include <bsd.own.mk>

.if !defined(__MINIX)
CONFIGFILES=	daily.conf monthly.conf pkgpath.conf security.conf weekly.conf
.else
CONFIGFILES=	minix.rc.conf
.endif # !defined(__MINIX)
FILESDIR=	/etc/defaults
FILESMODE=	${NONBINMODE}

# Manage arch-specific rc.conf(5) file
CONFIGFILES+=	rc_conf
FILESNAME_rc_conf=	rc.conf
FILESBUILD_rc_conf=	yes

# If present, rc.conf.append is added to the end of the default rc.conf file
RCCONF_SRCS=	${.CURDIR}/rc.conf
.if exists(../etc.${MACHINE}/rc.conf.append)
RCCONF_SRCS+=	${.CURDIR}/../etc.${MACHINE}/rc.conf.append
.endif

rc_conf: ${RCCONF_SRCS}
	${_MKTARGET_CREATE}
	${TOOL_CAT} ${RCCONF_SRCS} > ${.TARGET}

.include <bsd.prog.mk>


text:
package task.service.lvs.repository;

import task.service.lvs.domain.Restaurant;
import org.springframework.stereotype.Repository;

@Repository
public interface RestaurantRepository extends BaseRepository<Restaurant, Integer>
{
    Restaurant findByName(String name);
}


text:
r302 '/bosh/bosh-errands.html', '/bosh/jobs.html'
r302 '/deploying/vsphere/cloud-foundry-example-manifest.html', '/deploying/vsphere/index.html'
r302 '/deploying/vcloud/cloud-foundry-example-manifest.html', '/deploying/vcloud/index.html'
r302 '/devguide/deploy-apps/api-endpoint.html', '/running/cf-api-endpoint.html'
r302 '/console/cf-api-endpoint.html', '/running/cf-api-endpoint.html'
r302 '/devguide/deploy-apps/sts.html', '/buildpacks/java/sts.html'


text:
/**
 * NodeBots Day - Sacramento
 *
 * Lesson 2: Operate a Servo
 */

// Pull in the Johnny Five Robotics & IoT library
var five = require('johnny-five');

// Initialize an object that provides a base interface to the physical Arduino Uno
var board = new five.Board();

// All device objects depend on an initialized and "ready" board object.
// This creates an "event listener" whose function is called once the board says
// that it is "ready" to receive input from our code.
board.on('ready', function() {
  // Most devices that connect to the Arduino Uno need three different
  // connections to the board:
  //
  // * Power (3.3v or 5v)
  // * Ground (GND)
  // * Data
  //
  // The Arduino Uno provides three different types of data connections:
  //
  // * Digital (pins 2 - 13)
  // * Digital Pulse-Width Modulation (or PWM, denoted by a "~", pins 3, 5,6, 9, 10, and 11)
  // * Analog (pins A0 - A5)
  //
  // We won't get into the differences between the 3 right now, but servo
  // conncetions require a digital connection. Using the provided lead wires, go
  // ahead and connect the servo to the Arduino Uno:
  //
  // * Connect the black wire to any GND on the Arduino
  // * Connect the red wire to the 3.3v or 5v connection on the Arduino
  // * Connect the orange wire to Digital Pin 9
  //
  // Let's tell Johnny Five about our servo and connection details:
  var servo = new five.Servo(9);

  // Now "sweep" the servo from 0 degrees to 180 degress and repeat.
  servo.sweep([45, 135]);

  // Finally, clean up after ourselves when we exit
  this.on('exit', function() {
    servo.stop();
  });

  // At this point, you should have a servo that is turning back and forth
  // infinitely.
  //
  // Using the documentation available on http://johnny-five.io/api/servo/#api,
  // see if you can program the servo to do the following this:
  //
  // * Initialize the servo at a specific position
  // * Sweep between 45 and 135 degrees
  // * Step through specific angles of your choosing
  //
  // NOTE: Some solutions may require a slightly more advanced configuration of
  // our Servo object, so be sure to read the Johnny Five documentation!
});


text:
using System.Collections.Generic;
using Loon.Utils;
namespace Loon.Core
{

    public class AssetManager
    {

        private static List<Asset> _assetList = new List<Asset>(
                CollectionUtils.INITIAL_CAPACITY);

        private static int _loadedIndex = 0;

        public static void Reset()
        {
            _loadedIndex = 0;
        }

        public static string GetCurrentAssetName()
        {
            if (_loadedIndex < _assetList.Count)
            {
                return _assetList[_loadedIndex].AssetName;
            }
            return "LoadComplete";
        }

        public static int GetPercentLoaded()
        {
            return ((100 * _loadedIndex) / _assetList.Count);
        }

        public static bool HasLoaded()
        {
            return (_loadedIndex >= _assetList.Count);
        }

        public static bool LoadAllAssets()
        {
            while (!LoadOneAsset())
            {
            }
            return true;
        }

        public static bool LoadOneAsset()
        {
            if (HasLoaded())
            {
                return true;
            }
            Asset asset = _assetList[_loadedIndex];
            if (asset != null)
            {
                asset.Load();
            }
            _loadedIndex++;
            return false;
        }

        public static void PrepareAsset(Asset asset)
        {
            if (asset != null)
            {
                CollectionUtils.Add(_assetList, asset);
            }
        }
    }
}


text:
package config

import (
	"circuit/load/config"
	"strings"
)

var (
	MapperHost     []string
	ReducerHost    []string
	AggregatorHost string
)

func init() {
	zk := config.Config.Zookeeper.Workers[0]
	switch {
	case strings.Index(zk, "datacenter") >= 0:
		MapperHost = []string{
			"host0.datacenter.net",
			"host0.datacenter.net",
			"host0.datacenter.net",
			"host0.datacenter.net",
			"host0.datacenter.net",
		}
		ReducerHost = []string{
			"host1.datacenter.net",
			"host1.datacenter.net",
			"host1.datacenter.net",
			"host1.datacenter.net",
			"host1.datacenter.net",
		}
		AggregatorHost = "host2.datacenter.net"

	case strings.Index(zk, "localhost") >= 0 || strings.Index(zk, "127.0.0.1") >= 0:
		MapperHost = []string{
			"localhost",
			"localhost",
			"localhost",
			"localhost",
			"localhost",
		}
		ReducerHost = []string{
			"localhost",
			"localhost",
			"localhost",
			"localhost",
			"localhost",
		}
		AggregatorHost = "localhost"
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.servicelinker.models;

import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** The authentication info. */
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "authType",
    defaultImpl = AuthInfoBase.class)
@JsonTypeName("AuthInfoBase")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "secret", value = SecretAuthInfo.class),
    @JsonSubTypes.Type(name = "userAssignedIdentity", value = UserAssignedIdentityAuthInfo.class),
    @JsonSubTypes.Type(name = "systemAssignedIdentity", value = SystemAssignedIdentityAuthInfo.class),
    @JsonSubTypes.Type(name = "servicePrincipalSecret", value = ServicePrincipalSecretAuthInfo.class),
    @JsonSubTypes.Type(name = "servicePrincipalCertificate", value = ServicePrincipalCertificateAuthInfo.class)
})
@Immutable
public class AuthInfoBase {
    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
namespace base {
class Pickle;
class PickleIterator;
}

struct PP_Flash_Menu;

namespace ppapi {
namespace proxy {

class PPAPI_PROXY_EXPORT SerializedFlashMenu {
 public:
  SerializedFlashMenu();
  ~SerializedFlashMenu();

  bool SetPPMenu(const PP_Flash_Menu* menu);

  const PP_Flash_Menu* pp_menu() const { return pp_menu_; }

  void WriteToMessage(base::Pickle* m) const;
  bool ReadFromMessage(const base::Pickle* m, base::PickleIterator* iter);

 private:
  const PP_Flash_Menu* pp_menu_;
  bool own_menu_;
  DISALLOW_COPY_AND_ASSIGN(SerializedFlashMenu);
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_SERIALIZED_FLASH_MENU_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
        >
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/font_background"
            >
        <TextView
                android:id="@+id/fence_radius_view_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="15sp"
                android:padding="3dp"
                android:layout_centerInParent="true"
                android:gravity="center"
                android:text="直径:100米" />
    </RelativeLayout>

</LinearLayout>


text:
layout: post
title:  Kickoff Meeting
loc: LLNL
category: meeting
---

Welcome to the XPDES consortium!
To learn more, checkout [this press release](http://computation.llnl.gov/newsroom/visualizing-complex-networks-planetary-scale).


text:
using UnityEngine;
using System.Collections;

public class Blink : MonoBehaviour
{

    void Start()
    {

        StartCoroutine(BlinkLoop());
    }

    private IEnumerator BlinkLoop()
    {
        while (true)
        {
            foreach (var r in GetComponentsInChildren<Renderer>())
            {
                r.enabled = false;
            }
            yield return new WaitForSeconds(0.15f);
            foreach (var r in GetComponentsInChildren<Renderer>())
            {
                r.enabled = true;
            }
            yield return new WaitForSeconds(Random.Range(1.5f, 3f));
        }
    }
}


text:
layout: post
title: 'Strength training'
date: 2022-05-23 20:2:43
author: multishiv19
comments: true
category: [workouts]
tags: [WeightTraining]
description: |
    Full body
---

## Activity Description
Full body


text:
{-# LANGUAGE Arrows #-}

module ShouldCompile where

-- variables bound inside the left argument of -< should be in scope

import Control.Arrow

f :: (Num b, Arrow a) => a b b
f = proc x -> arr (\y -> y-1) -< x

g :: (Num b, Arrow a) => a b b
g = proc x -> (proc y -> returnA -< y-1) -< x


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Emomentum extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	  function __construct() {
            parent::__construct(); //call the contructor
			$this->load->model('Team_model');
			$this->load->model('Home_model');
			$type = 4;
	  }
	public function index()
	{
		$this->load->view('home');
	}

	public function departments()
	{
		    $id = 8;
		$data['employee'] = $this->Team_model->getTeam($id);
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
		$this->load->view('departments',$data);
	}
	public function directors()
	{
		    $id = 8;
		$data['employee'] = $this->Team_model->getTeam($id);
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
		$this->load->view('directors',$data);
	}

	public function finance()
	{
		    $id = 9;
		$data['employee'] = $this->Team_model->getTeam($id);
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
		$this->load->view('finance',$data);
	}
	public function innovate()
	{
		$this->load->view('innovate');
	}
	public function gallery()
	{

		$this->load->view('gallery');
	}
	public function single_post()
	{
		$this->load->view('single_post');
	}
	function development(){
			$id = 1;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['otheremployee'] = $this->Team_model->getTeam($id);

			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			//$data['breadcrum'] = "Development";
			$this->load->view('development',$data);
		}

		function technical(){
			$id = 2;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			//$data['breadcrum'] = "Technical";
			$this->load->view('technical',$data);
		}
		function projects_and_consultancy(){
			$id = 3;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			//$data['breadcrum'] = "projects and consultancy";
			$this->load->view('projects',$data);
		}
		function sales(){
			$id = 4;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "sales";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('sales',$data);
		}
		function presales(){
			$id = 5;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "Pre Sales";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('presales',$data);
		}
		function marketing(){
			$id = 6;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "Marketing";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('marketing',$data);
		}
		function products(){
			$id = 7;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "Products and Partnership";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('products',$data);
		}

		function hr(){
			$id = 10;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "human Resource";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('hr',$data);
		}
		function risk(){
			$id = 11;
			$data['employee'] = $this->Team_model->getTeam($id);
			//$data['breadcrum'] = "Risk and Compliance";
			//$data['upcoming']=$this->Home_model->eventNews($type=4);
			$this->load->view('risk',$data);
		}

}


text:
package org.jetbrains.android.util;

import com.intellij.CommonBundle;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ResourceBundle;

/**
 * Messages bundle.
 *
 * @author Alexey Efimov
 */
public final class AndroidBundle {
  @NonNls
  private static final String BUNDLE_NAME = "messages.AndroidBundle";
  private static Reference<ResourceBundle> ourBundle;

  private static ResourceBundle getBundle() {
    ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle);
    if (bundle == null) {
      bundle = ResourceBundle.getBundle(BUNDLE_NAME);
      ourBundle = new SoftReference<ResourceBundle>(bundle);
    }
    return bundle;
  }

  private AndroidBundle() {
  }

  public static String message(@NotNull @PropertyKey(resourceBundle = BUNDLE_NAME) String key, @NotNull Object... params) {
    return CommonBundle.message(getBundle(), key, params);
  }
}