text:
(function() {
  console.log("'Allo from CoffeeScript!");

}).call(this);

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 51: 56 (1924)

#### Original name
Puccinia minuscula Arthur

### Remarks
null


text:
<?php

/**
 * Class to extract and validate Exif data from jpeg (and possibly tiff) files.
 * @ingroup Media
 */
class Exif {

	const BYTE      = 1;    //!< An 8-bit (1-byte) unsigned integer.
	const ASCII     = 2;    //!< An 8-bit byte containing one 7-bit ASCII code. The final byte is terminated with NULL.
	const SHORT     = 3;    //!< A 16-bit (2-byte) unsigned integer.
	const LONG      = 4;    //!< A 32-bit (4-byte) unsigned integer.
	const RATIONAL  = 5;    //!< Two LONGs. The first LONG is the numerator and the second LONG expresses the denominator
	const UNDEFINED = 7;    //!< An 8-bit byte that can take any value depending on the field definition
	const SLONG     = 9;    //!< A 32-bit (4-byte) signed integer (2's complement notation),
	const SRATIONAL = 10;   //!< Two SLONGs. The first SLONG is the numerator and the second SLONG is the denominator.
	const IGNORE    = -1;   // A fake value for things we don't want or don't support.

	//@{
	/* @var array
	 * @private
	 */

	/**
	 * Exif tags grouped by category, the tagname itself is the key and the type
	 * is the value, in the case of more than one possible value type they are
	 * separated by commas.
	 */
	var $mExifTags;

	/**
	 * The raw Exif data returned by exif_read_data()
	 */
	var $mRawExifData;

	/**
	 * A Filtered version of $mRawExifData that has been pruned of invalid
	 * tags and tags that contain content they shouldn't contain according
	 * to the Exif specification
	 */
	var $mFilteredExifData;

	/**
	 * Filtered and formatted Exif data, see FormatMetadata::getFormattedData()
	 */
	var $mFormattedExifData;

	//@}

	//@{
	/* @var string
	 * @private
	 */

	/**
	 * The file being processed
	 */
	var $file;

	/**
	 * The basename of the file being processed
	 */
	var $basename;

	/**
	 * The private log to log to, e.g. 'exif'
	 */
	var $log = false;

	/**
	 * The byte order of the file. Needed because php's
	 * extension doesn't fully process some obscure props.
	 */
	private $byteOrder;
	//@}

	/**
	 * Constructor
	 *
	 * @param $file String: filename.
	 * @param $byteOrder String Type of byte ordering either 'BE' (Big Endian) or 'LE' (Little Endian). Default ''.
	 * @todo FIXME: The following are broke:
	 * SubjectArea. Need to test the more obscure tags.
	 *
	 * DigitalZoomRatio = 0/0 is rejected. need to determine if that's valid.
	 * possibly should treat 0/0 = 0. need to read exif spec on that.
	 */
	function __construct( $file, $byteOrder = '' ) {
		/**
		 * Page numbers here refer to pages in the EXIF 2.2 standard
		 *
		 * Note, Exif::UNDEFINED is treated as a string, not as an array of bytes
		 * so don't put a count parameter for any UNDEFINED values.
		 *
		 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 specification
		 */
		$this->mExifTags = array(
			# TIFF Rev. 6.0 Attribute Information (p22)
			'IFD0' => array(
				# Tags relating to image structure
				'ImageWidth' => Exif::SHORT.','.Exif::LONG,		# Image width
				'ImageLength' => Exif::SHORT.','.Exif::LONG,		# Image height
				'BitsPerSample' => array( Exif::SHORT, 3 ),		# Number of bits per component
				# "When a primary image is JPEG compressed, this designation is not"
				# "necessary and is omitted." (p23)
				'Compression' => Exif::SHORT,				# Compression scheme #p23
				'PhotometricInterpretation' => Exif::SHORT,		# Pixel composition #p23
				'Orientation' => Exif::SHORT,				# Orientation of image #p24
				'SamplesPerPixel' => Exif::SHORT,			# Number of components
				'PlanarConfiguration' => Exif::SHORT,			# Image data arrangement #p24
				'YCbCrSubSampling' => array( Exif::SHORT, 2),		# Subsampling ratio of Y to C #p24
				'YCbCrPositioning' => Exif::SHORT,			# Y and C positioning #p24-25
				'XResolution' => Exif::RATIONAL,			# Image resolution in width direction
				'YResolution' => Exif::RATIONAL,			# Image resolution in height direction
				'ResolutionUnit' => Exif::SHORT,			# Unit of X and Y resolution #(p26)

				# Tags relating to recording offset
				'StripOffsets' => Exif::SHORT.','.Exif::LONG,			# Image data location
				'RowsPerStrip' => Exif::SHORT.','.Exif::LONG,			# Number of rows per strip
				'StripByteCounts' => Exif::SHORT.','.Exif::LONG,		# Bytes per compressed strip
				'JPEGInterchangeFormat' => Exif::SHORT.','.Exif::LONG,		# Offset to JPEG SOI
				'JPEGInterchangeFormatLength' => Exif::SHORT.','.Exif::LONG,	# Bytes of JPEG data

				# Tags relating to image data characteristics
				'TransferFunction' => Exif::IGNORE,			# Transfer function
				'WhitePoint' => array( Exif::RATIONAL, 2),		# White point chromaticity
				'PrimaryChromaticities' => array( Exif::RATIONAL, 6),	# Chromaticities of primarities
				'YCbCrCoefficients' => array( Exif::RATIONAL, 3),	# Color space transformation matrix coefficients #p27
				'ReferenceBlackWhite' => array( Exif::RATIONAL, 6),	# Pair of black and white reference values

				# Other tags
				'DateTime' => Exif::ASCII,				# File change date and time
				'ImageDescription' => Exif::ASCII,			# Image title
				'Make' => Exif::ASCII,					# Image input equipment manufacturer
				'Model' => Exif::ASCII,					# Image input equipment model
				'Software' => Exif::ASCII,				# Software used
				'Artist' => Exif::ASCII,				# Person who created the image
				'Copyright' => Exif::ASCII,				# Copyright holder
			),

			# Exif IFD Attribute Information (p30-31)
			'EXIF' => array(
				# TODO: NOTE: Nonexistence of this field is taken to mean nonconformance
				# to the EXIF 2.1 AND 2.2 standards
				'ExifVersion' =>  Exif::UNDEFINED,			# Exif version
				'FlashPixVersion' => Exif::UNDEFINED,			# Supported Flashpix version #p32

				# Tags relating to Image Data Characteristics
				'ColorSpace' => Exif::SHORT,				# Color space information #p32

				# Tags relating to image configuration
				'ComponentsConfiguration' => Exif::UNDEFINED,			# Meaning of each component #p33
				'CompressedBitsPerPixel' => Exif::RATIONAL,			# Image compression mode
				'PixelYDimension' => Exif::SHORT.','.Exif::LONG,		# Valid image width
				'PixelXDimension' => Exif::SHORT.','.Exif::LONG,		# Valid image height

				# Tags relating to related user information
				'MakerNote' => Exif::IGNORE,				# Manufacturer notes
				'UserComment' => Exif::UNDEFINED,			# User comments #p34

				# Tags relating to related file information
				'RelatedSoundFile' => Exif::ASCII,			# Related audio file

				# Tags relating to date and time
				'DateTimeOriginal' => Exif::ASCII,			# Date and time of original data generation #p36
				'DateTimeDigitized' => Exif::ASCII,			# Date and time of original data generation
				'SubSecTime' => Exif::ASCII,				# DateTime subseconds
				'SubSecTimeOriginal' => Exif::ASCII,			# DateTimeOriginal subseconds
				'SubSecTimeDigitized' => Exif::ASCII,			# DateTimeDigitized subseconds

				# Tags relating to picture-taking conditions (p31)
				'ExposureTime' => Exif::RATIONAL,			# Exposure time
				'FNumber' => Exif::RATIONAL,				# F Number
				'ExposureProgram' => Exif::SHORT,			# Exposure Program #p38
				'SpectralSensitivity' => Exif::ASCII,			# Spectral sensitivity
				'ISOSpeedRatings' => Exif::SHORT,			# ISO speed rating
				'OECF' => Exif::IGNORE,
				# Optoelectronic conversion factor. Note: We don't have support for this atm.
				'ShutterSpeedValue' => Exif::SRATIONAL,			# Shutter speed
				'ApertureValue' => Exif::RATIONAL,			# Aperture
				'BrightnessValue' => Exif::SRATIONAL,			# Brightness
				'ExposureBiasValue' => Exif::SRATIONAL,			# Exposure bias
				'MaxApertureValue' => Exif::RATIONAL,			# Maximum land aperture
				'SubjectDistance' => Exif::RATIONAL,			# Subject distance
				'MeteringMode' => Exif::SHORT,				# Metering mode #p40
				'LightSource' => Exif::SHORT,				# Light source #p40-41
				'Flash' => Exif::SHORT,					# Flash #p41-42
				'FocalLength' => Exif::RATIONAL,			# Lens focal length
				'SubjectArea' => array( Exif::SHORT, 4 ),		# Subject area
				'FlashEnergy' => Exif::RATIONAL,			# Flash energy
				'SpatialFrequencyResponse' => Exif::IGNORE,		# Spatial frequency response. Not supported atm.
				'FocalPlaneXResolution' => Exif::RATIONAL,		# Focal plane X resolution
				'FocalPlaneYResolution' => Exif::RATIONAL,		# Focal plane Y resolution
				'FocalPlaneResolutionUnit' => Exif::SHORT,		# Focal plane resolution unit #p46
				'SubjectLocation' => array( Exif::SHORT, 2),		# Subject location
				'ExposureIndex' => Exif::RATIONAL,			# Exposure index
				'SensingMethod' => Exif::SHORT,				# Sensing method #p46
				'FileSource' => Exif::UNDEFINED,			# File source #p47
				'SceneType' => Exif::UNDEFINED,				# Scene type #p47
				'CFAPattern' => Exif::IGNORE,				# CFA pattern. not supported atm.
				'CustomRendered' => Exif::SHORT,			# Custom image processing #p48
				'ExposureMode' => Exif::SHORT,				# Exposure mode #p48
				'WhiteBalance' => Exif::SHORT,				# White Balance #p49
				'DigitalZoomRatio' => Exif::RATIONAL,			# Digital zoom ration
				'FocalLengthIn35mmFilm' => Exif::SHORT,			# Focal length in 35 mm film
				'SceneCaptureType' => Exif::SHORT,			# Scene capture type #p49
				'GainControl' => Exif::SHORT,				# Scene control #p49-50
				'Contrast' => Exif::SHORT,				# Contrast #p50
				'Saturation' => Exif::SHORT,				# Saturation #p50
				'Sharpness' => Exif::SHORT,				# Sharpness #p50
				'DeviceSettingDescription' => Exif::IGNORE,
				# Device settings description. This could maybe be supported. Need to find an
				# example file that uses this to see if it has stuff of interest in it.
				'SubjectDistanceRange' => Exif::SHORT,			# Subject distance range #p51

				'ImageUniqueID' => Exif::ASCII,				# Unique image ID
			),

			# GPS Attribute Information (p52)
			'GPS' => array(
				'GPSVersion' => Exif::UNDEFINED,
				# Should be an array of 4 Exif::BYTE's. However php treats it as an undefined
				# Note exif standard calls this GPSVersionID, but php doesn't like the id suffix
				'GPSLatitudeRef' => Exif::ASCII,			# North or South Latitude #p52-53
				'GPSLatitude' => array( Exif::RATIONAL, 3 ),		# Latitude
				'GPSLongitudeRef' => Exif::ASCII,			# East or West Longitude #p53
				'GPSLongitude' => array( Exif::RATIONAL, 3),		# Longitude
				'GPSAltitudeRef' => Exif::UNDEFINED,
				# Altitude reference. Note, the exif standard says this should be an EXIF::Byte,
				# but php seems to disagree.
				'GPSAltitude' => Exif::RATIONAL,			# Altitude
				'GPSTimeStamp' => array( Exif::RATIONAL, 3),		# GPS time (atomic clock)
				'GPSSatellites' => Exif::ASCII,				# Satellites used for measurement
				'GPSStatus' => Exif::ASCII,				# Receiver status #p54
				'GPSMeasureMode' => Exif::ASCII,			# Measurement mode #p54-55
				'GPSDOP' => Exif::RATIONAL,				# Measurement precision
				'GPSSpeedRef' => Exif::ASCII,				# Speed unit #p55
				'GPSSpeed' => Exif::RATIONAL,				# Speed of GPS receiver
				'GPSTrackRef' => Exif::ASCII,				# Reference for direction of movement #p55
				'GPSTrack' => Exif::RATIONAL,				# Direction of movement
				'GPSImgDirectionRef' => Exif::ASCII,			# Reference for direction of image #p56
				'GPSImgDirection' => Exif::RATIONAL,			# Direction of image
				'GPSMapDatum' => Exif::ASCII,				# Geodetic survey data used
				'GPSDestLatitudeRef' => Exif::ASCII,			# Reference for latitude of destination #p56
				'GPSDestLatitude' => array( Exif::RATIONAL, 3 ),	# Latitude destination
				'GPSDestLongitudeRef' => Exif::ASCII,			# Reference for longitude of destination #p57
				'GPSDestLongitude' => array( Exif::RATIONAL, 3 ),	# Longitude of destination
				'GPSDestBearingRef' => Exif::ASCII,			# Reference for bearing of destination #p57
				'GPSDestBearing' => Exif::RATIONAL,			# Bearing of destination
				'GPSDestDistanceRef' => Exif::ASCII,			# Reference for distance to destination #p57-58
				'GPSDestDistance' => Exif::RATIONAL,			# Distance to destination
				'GPSProcessingMethod' => Exif::UNDEFINED,		# Name of GPS processing method
				'GPSAreaInformation' => Exif::UNDEFINED,		# Name of GPS area
				'GPSDateStamp' => Exif::ASCII,				# GPS date
				'GPSDifferential' => Exif::SHORT,			# GPS differential correction
			),
		);

		$this->file = $file;
		$this->basename = wfBaseName( $this->file );
		if ( $byteOrder === 'BE' || $byteOrder === 'LE' ) {
			$this->byteOrder = $byteOrder;
		} else {
			// Only give a warning for b/c, since originally we didn't
			// require this. The number of things affected by this is
			// rather small.
			wfWarn( 'Exif class did not have byte order specified. '
			 . 'Some properties may be decoded incorrectly.' );
			$this->byteOrder = 'BE'; // BE seems about twice as popular as LE in jpg's.
		}

		$this->debugFile( $this->basename, __FUNCTION__, true );
		if( function_exists( 'exif_read_data' ) ) {
			wfSuppressWarnings();
			$data = exif_read_data( $this->file, 0, true );
			wfRestoreWarnings();
		} else {
			throw new MWException( "Internal error: exif_read_data not present. \$wgShowEXIF may be incorrectly set or not checked by an extension." );
		}
		/**
		 * exif_read_data() will return false on invalid input, such as
		 * when somebody uploads a file called something.jpeg
		 * containing random gibberish.
		 */
		$this->mRawExifData = $data ? $data : array();
		$this->makeFilteredData();
		$this->collapseData();
		$this->debugFile( __FUNCTION__, false );
	}

	/**
	 * Make $this->mFilteredExifData
	 */
	function makeFilteredData() {
		$this->mFilteredExifData = Array();

		foreach ( array_keys( $this->mRawExifData ) as $section ) {
			if ( !in_array( $section, array_keys( $this->mExifTags ) ) ) {
				$this->debug( $section , __FUNCTION__, "'$section' is not a valid Exif section" );
				continue;
			}

			foreach ( array_keys( $this->mRawExifData[$section] ) as $tag ) {
				if ( !in_array( $tag, array_keys( $this->mExifTags[$section] ) ) ) {
					$this->debug( $tag, __FUNCTION__, "'$tag' is not a valid tag in '$section'" );
					continue;
				}

				$this->mFilteredExifData[$tag] = $this->mRawExifData[$section][$tag];
				// This is ok, as the tags in the different sections do not conflict.
				// except in computed and thumbnail section, which we don't use.

				$value = $this->mRawExifData[$section][$tag];
				if ( !$this->validate( $section, $tag, $value ) ) {
					$this->debug( $value, __FUNCTION__, "'$tag' contained invalid data" );
					unset( $this->mFilteredExifData[$tag] );
				}
			}
		}
	}

	/**
	* Collapse some fields together.
	* This converts some fields from exif form, to a more friendly form.
	* For example GPS latitude to a single number.
	*
	* The rationale behind this is that we're storing data, not presenting to the user
	* For example a longitude is a single number describing how far away you are from
	* the prime meridian. Well it might be nice to split it up into minutes and seconds
	* for the user, it doesn't really make sense to split a single number into 4 parts
	* for storage. (degrees, minutes, second, direction vs single floating point number).
	*
	* Other things this might do (not really sure if they make sense or not):
	* Dates -> mediawiki date format.
	* convert values that can be in different units to be in one standardized unit.
	*
	* As an alternative approach, some of this could be done in the validate phase
	* if we make up our own types like Exif::DATE.
	*/
	function collapseData( ) {

		$this->exifGPStoNumber( 'GPSLatitude' );
		$this->exifGPStoNumber( 'GPSDestLatitude' );
		$this->exifGPStoNumber( 'GPSLongitude' );
		$this->exifGPStoNumber( 'GPSDestLongitude' );

		if ( isset( $this->mFilteredExifData['GPSAltitude'] ) && isset( $this->mFilteredExifData['GPSAltitudeRef'] ) ) {
			if ( $this->mFilteredExifData['GPSAltitudeRef'] === "\1" ) {
				$this->mFilteredExifData['GPSAltitude'] *= - 1;
			}
			unset( $this->mFilteredExifData['GPSAltitudeRef'] );
		}

		$this->exifPropToOrd( 'FileSource' );
		$this->exifPropToOrd( 'SceneType' );

		$this->charCodeString( 'UserComment' );
		$this->charCodeString( 'GPSProcessingMethod');
		$this->charCodeString( 'GPSAreaInformation' );

		//ComponentsConfiguration should really be an array instead of a string...
		//This turns a string of binary numbers into an array of numbers.

		if ( isset ( $this->mFilteredExifData['ComponentsConfiguration'] ) ) {
			$val = $this->mFilteredExifData['ComponentsConfiguration'];
			$ccVals = array();
			for ($i = 0; $i < strlen($val); $i++) {
				$ccVals[$i] = ord( substr($val, $i, 1) );
			}
			$ccVals['_type'] = 'ol'; //this is for formatting later.
			$this->mFilteredExifData['ComponentsConfiguration'] = $ccVals;
		}

		//GPSVersion(ID) is treated as the wrong type by php exif support.
		//Go through each byte turning it into a version string.
		//For example: "\x02\x02\x00\x00" -> "2.2.0.0"

		//Also change exif tag name from GPSVersion (what php exif thinks it is)
		//to GPSVersionID (what the exif standard thinks it is).

		if ( isset ( $this->mFilteredExifData['GPSVersion'] ) ) {
			$val = $this->mFilteredExifData['GPSVersion'];
			$newVal = '';
			for ($i = 0; $i < strlen($val); $i++) {
				if ( $i !== 0 ) {
					$newVal .= '.';
				}
				$newVal .= ord( substr($val, $i, 1) );
			}
			if ( $this->byteOrder === 'LE' ) {
				// Need to reverse the string
				$newVal2 = '';
				for ( $i = strlen( $newVal ) - 1; $i >= 0; $i-- ) {
					$newVal2 .= substr( $newVal, $i, 1 );
				}
				$this->mFilteredExifData['GPSVersionID'] = $newVal2;
			} else {
				$this->mFilteredExifData['GPSVersionID'] = $newVal;
			}
			unset( $this->mFilteredExifData['GPSVersion'] );
		}

	}
	/**
	* Do userComment tags and similar. See pg. 34 of exif standard.
	* basically first 8 bytes is charset, rest is value.
	* This has not been tested on any shift-JIS strings.
	* @param $prop String prop name.
	*/
	private function charCodeString ( $prop ) {
		if ( isset( $this->mFilteredExifData[$prop] ) ) {

			if ( strlen($this->mFilteredExifData[$prop]) <= 8 ) {
				//invalid. Must be at least 9 bytes long.

				$this->debug( $this->mFilteredExifData[$prop] , __FUNCTION__, false );
				unset($this->mFilteredExifData[$prop]);
				return;
			}
			$charCode = substr( $this->mFilteredExifData[$prop], 0, 8);
			$val = substr( $this->mFilteredExifData[$prop], 8);

			switch ($charCode) {
				case "\x4A\x49\x53\x00\x00\x00\x00\x00":
					//JIS
					$charset = "Shift-JIS";
					break;
				case "UNICODE\x00":
					$charset = "UTF-16" . $this->byteOrder;
					break;
				default: //ascii or undefined.
					$charset = "";
					break;
			}
			// This could possibly check to see if iconv is really installed
			// or if we're using the compatibility wrapper in globalFunctions.php
			if ($charset) {
				wfSuppressWarnings();
				$val = iconv($charset, 'UTF-8//IGNORE', $val);
				wfRestoreWarnings();
			} else {
				// if valid utf-8, assume that, otherwise assume windows-1252
				$valCopy = $val;
				UtfNormal::quickIsNFCVerify( $valCopy ); //validates $valCopy.
				if ( $valCopy !== $val ) {
					wfSuppressWarnings();
					$val = iconv('Windows-1252', 'UTF-8//IGNORE', $val);
					wfRestoreWarnings();
				}
			}

			//trim and check to make sure not only whitespace.
			$val = trim($val);
			if ( strlen( $val ) === 0 ) {
				//only whitespace.
				$this->debug( $this->mFilteredExifData[$prop] , __FUNCTION__, "$prop: Is only whitespace" );
				unset($this->mFilteredExifData[$prop]);
				return;
			}

			//all's good.
			$this->mFilteredExifData[$prop] = $val;
		}
	}
	/**
	* Convert an Exif::UNDEFINED from a raw binary string
	* to its value. This is sometimes needed depending on
	* the type of UNDEFINED field
	* @param $prop String name of property
	*/
	private function exifPropToOrd ( $prop ) {
		if ( isset( $this->mFilteredExifData[$prop] ) ) {
			$this->mFilteredExifData[$prop] = ord( $this->mFilteredExifData[$prop] );
		}
	}
	/**
	* Convert gps in exif form to a single floating point number
	* for example 10 degress 20`40`` S -> -10.34444
	* @param String $prop a gps coordinate exif tag name (like GPSLongitude)
	*/
	private function exifGPStoNumber ( $prop ) {
		$loc =& $this->mFilteredExifData[$prop];
		$dir =& $this->mFilteredExifData[$prop . 'Ref'];
		$res = false;

		if ( isset( $loc ) && isset( $dir ) && ( $dir === 'N' || $dir === 'S' || $dir === 'E' || $dir === 'W' ) ) {
			list( $num, $denom ) = explode( '/', $loc[0] );
			$res = $num / $denom;
			list( $num, $denom ) = explode( '/', $loc[1] );
			$res += ( $num / $denom ) * ( 1 / 60 );
			list( $num, $denom ) = explode( '/', $loc[2] );
			$res += ( $num / $denom ) * ( 1 / 3600 );

			if ( $dir === 'S' || $dir === 'W' ) {
				$res *= - 1; // make negative
			}
		}

		// update the exif records.

		if ( $res !== false ) { // using !== as $res could potentially be 0
			$this->mFilteredExifData[$prop] = $res;
			unset( $this->mFilteredExifData[$prop . 'Ref'] );
		} else { // if invalid
			unset( $this->mFilteredExifData[$prop] );
			unset( $this->mFilteredExifData[$prop . 'Ref'] );
		}
	}

	/**
	 * Use FormatMetadata to create formatted values for display to user
	 * (is this ever used?)
	 *
	 * @deprecated since 1.18
	 */
	function makeFormattedData( ) {
		wfDeprecated( __METHOD__, '1.18' );
		$this->mFormattedExifData = FormatMetadata::getFormattedData(
			$this->mFilteredExifData );
	}
	/**#@-*/

	/**#@+
	 * @return array
	 */
	/**
	 * Get $this->mRawExifData
	 */
	function getData() {
		return $this->mRawExifData;
	}

	/**
	 * Get $this->mFilteredExifData
	 */
	function getFilteredData() {
		return $this->mFilteredExifData;
	}

	/**
	 * Get $this->mFormattedExifData
	 *
	 * This returns the data for display to user.
	 * Its unclear if this is ever used.
	 *
	 * @deprecated since 1.18
	 */
	function getFormattedData() {
		wfDeprecated( __METHOD__, '1.18' );
		if (!$this->mFormattedExifData) {
			$this->makeFormattedData();
		}
		return $this->mFormattedExifData;
	}
	/**#@-*/

	/**
	 * The version of the output format
	 *
	 * Before the actual metadata information is saved in the database we
	 * strip some of it since we don't want to save things like thumbnails
	 * which usually accompany Exif data. This value gets saved in the
	 * database along with the actual Exif data, and if the version in the
	 * database doesn't equal the value returned by this function the Exif
	 * data is regenerated.
	 *
	 * @return int
	 */
	public static function version() {
		return 2; // We don't need no bloddy constants!
	}

	/**#@+
	 * Validates if a tag value is of the type it should be according to the Exif spec
	 *
	 * @private
	 *
	 * @param $in Mixed: the input value to check
	 * @return bool
	 */
	private function isByte( $in ) {
		if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 255 ) {
			$this->debug( $in, __FUNCTION__, true );
			return true;
		} else {
			$this->debug( $in, __FUNCTION__, false );
			return false;
		}
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isASCII( $in ) {
		if ( is_array( $in ) ) {
			return false;
		}

		if ( preg_match( "/[^\x0a\x20-\x7e]/", $in ) ) {
			$this->debug( $in, __FUNCTION__, 'found a character not in our whitelist' );
			return false;
		}

		if ( preg_match( '/^\s*$/', $in ) ) {
			$this->debug( $in, __FUNCTION__, 'input consisted solely of whitespace' );
			return false;
		}

		return true;
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isShort( $in ) {
		if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 65536 ) {
			$this->debug( $in, __FUNCTION__, true );
			return true;
		} else {
			$this->debug( $in, __FUNCTION__, false );
			return false;
		}
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isLong( $in ) {
		if ( !is_array( $in ) && sprintf('%d', $in) == $in && $in >= 0 && $in <= 4294967296 ) {
			$this->debug( $in, __FUNCTION__, true );
			return true;
		} else {
			$this->debug( $in, __FUNCTION__, false );
			return false;
		}
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isRational( $in ) {
		$m = array();
		if ( !is_array( $in ) && @preg_match( '/^(\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m ) ) { # Avoid division by zero
			return $this->isLong( $m[1] ) && $this->isLong( $m[2] );
		} else {
			$this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
			return false;
		}
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isUndefined( $in ) {
		$this->debug( $in, __FUNCTION__, true );
		return true;
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isSlong( $in ) {
		if ( $this->isLong( abs( $in ) ) ) {
			$this->debug( $in, __FUNCTION__, true );
			return true;
		} else {
			$this->debug( $in, __FUNCTION__, false );
			return false;
		}
	}

	/**
	 * @param $in
	 * @return bool
	 */
	private function isSrational( $in ) {
		$m = array();
		if ( !is_array( $in ) && preg_match( '/^(-?\d+)\/(\d+[1-9]|[1-9]\d*)$/', $in, $m ) ) { # Avoid division by zero
			return $this->isSlong( $m[0] ) && $this->isSlong( $m[1] );
		} else {
			$this->debug( $in, __FUNCTION__, 'fed a non-fraction value' );
			return false;
		}
	}
	/**#@-*/

	/**
	 * Validates if a tag has a legal value according to the Exif spec
	 *
	 * @private
	 * @param $section String: section where tag is located.
	 * @param $tag String: the tag to check.
	 * @param $val Mixed: the value of the tag.
	 * @param $recursive Boolean: true if called recursively for array types.
	 * @return bool
	 */
	private function validate( $section, $tag, $val, $recursive = false ) {
		$debug = "tag is '$tag'";
		$etype = $this->mExifTags[$section][$tag];
		$ecount = 1;
		if( is_array( $etype ) ) {
			list( $etype, $ecount ) = $etype;
			if ( $recursive )
				$ecount = 1; // checking individual elements
		}
		$count = count( $val );
		if( $ecount != $count ) {
			$this->debug( $val, __FUNCTION__, "Expected $ecount elements for $tag but got $count" );
			return false;
		}
		if( $count > 1 ) {
			foreach( $val as $v ) {
				if( !$this->validate( $section, $tag, $v, true ) ) {
					return false;
				}
			}
			return true;
		}
		// Does not work if not typecast
		switch( (string)$etype ) {
			case (string)Exif::BYTE:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isByte( $val );
			case (string)Exif::ASCII:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isASCII( $val );
			case (string)Exif::SHORT:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isShort( $val );
			case (string)Exif::LONG:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isLong( $val );
			case (string)Exif::RATIONAL:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isRational( $val );
			case (string)Exif::UNDEFINED:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isUndefined( $val );
			case (string)Exif::SLONG:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isSlong( $val );
			case (string)Exif::SRATIONAL:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isSrational( $val );
			case (string)Exif::SHORT.','.Exif::LONG:
				$this->debug( $val, __FUNCTION__, $debug );
				return $this->isShort( $val ) || $this->isLong( $val );
			case (string)Exif::IGNORE:
				$this->debug( $val, __FUNCTION__, $debug );
				return false;
			default:
				$this->debug( $val, __FUNCTION__, "The tag '$tag' is unknown" );
				return false;
		}
	}

	/**
	 * Convenience function for debugging output
	 *
	 * @private
	 *
	 * @param $in Mixed:
	 * @param $fname String:
	 * @param $action Mixed: , default NULL.
	 */
	private function debug( $in, $fname, $action = null ) {
		if ( !$this->log ) {
			return;
		}
		$type = gettype( $in );
		$class = ucfirst( __CLASS__ );
		if ( $type === 'array' ) {
			$in = print_r( $in, true );
		}

		if ( $action === true ) {
			wfDebugLog( $this->log, "$class::$fname: accepted: '$in' (type: $type)\n");
		} elseif ( $action === false ) {
			wfDebugLog( $this->log, "$class::$fname: rejected: '$in' (type: $type)\n");
		} elseif ( $action === null ) {
			wfDebugLog( $this->log, "$class::$fname: input was: '$in' (type: $type)\n");
		} else {
			wfDebugLog( $this->log, "$class::$fname: $action (type: $type; content: '$in')\n");
		}
	}

	/**
	 * Convenience function for debugging output
	 *
	 * @private
	 *
	 * @param $fname String: the name of the function calling this function
	 * @param $io Boolean: Specify whether we're beginning or ending
	 */
	private function debugFile( $fname, $io ) {
		if ( !$this->log ) {
			return;
		}
		$class = ucfirst( __CLASS__ );
		if ( $io ) {
			wfDebugLog( $this->log, "$class::$fname: begin processing: '{$this->basename}'\n" );
		} else {
			wfDebugLog( $this->log, "$class::$fname: end processing: '{$this->basename}'\n" );
		}
	}
}


text:
"""Models for the aps_production app."""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import timedelta
from django.utils.translation import ugettext_lazy as _

class Error(models.Model):
    """
    An actual error, that occurred

    :order_run: on which order run this error occurred
    :error_bin: which error bin this belongs to
    :quantity: how often this error occurred during the run
    :comment: additional notes

    """
    order_run = models.ForeignKey(
        'aps_production.OrderRun',
        verbose_name=_('order run'),
        related_name='errors',
    )

    error_bin = models.ForeignKey(
        'aps_production.ErrorBin',
        verbose_name=_('error bin'),
        related_name='errors',
    )

    quantity = models.PositiveIntegerField(
        verbose_name=_('quantity'),
    )

    comment = models.TextField(
        verbose_name=_('comment'),
        blank=True,
    )

class ErrorBin(models.Model):
    """
    Master data containing all possible errors

    :technology: the technology the error is related to
    :error_code: an identifier for this error
    :description: a further description about this error
    :picture: ???

    """
    technology = models.ForeignKey(
        'aps_bom.Technology',
        verbose_name=_('technology'),
        related_name='error_bins',
    )

    error_code = models.CharField(
        verbose_name=_('error code'),
        max_length=64,
    )

    description = models.TextField(
        verbose_name=_('description'),
        blank=True,
    )

    picture = models.ImageField(
        verbose_name=_('picture'),
        blank=True, null=True,
        upload_to='error_bin_pictures',
    )

    class Meta:
        ordering = ('error_code', )

@python_2_unicode_compatible
class Order(models.Model):
    """
    An order placed by a customer.

    :order_number: unique string identifier for this order
    :company: the company, that placed the order
    :date_created: the date, this order was created
    :customer_po_number: ???
    :customer_po_date: ???

    """
    order_number = models.CharField(
        verbose_name=_('order number'),
        max_length=64,
        unique=True,
    )

    company = models.ForeignKey(
        'aps_bom.Company',
        verbose_name=_('company'),
        related_name='orders',
    )

    date_created = models.DateTimeField(
        verbose_name=_('date created'),
        auto_now_add=True,
    )

    customer_po_number = models.CharField(
        verbose_name=_('customer po number'),
        max_length=30,
    )

    customer_po_date = models.DateTimeField(
        verbose_name=_('customer po date'),
    )

    def __str__(self):
        return self.order_number

    class Meta:
        ordering = ('order_number', )

class OrderLine(models.Model):
    """
    Represents one line of an ``Order``.

    :order: The order this line belongs to.
    :line_no: the line number as entered by the planner
    :product: the product, this line is about
    :quantity_ordered: how many of this product, the customer orders
    :date_requested: when the customer requested the product

    computed:
    :date_shipped: When *all* items are shipped
    :date_delivered: The date of the last shipment plus the days it needs to
      ship to the customer

    """
    order = models.ForeignKey(
        Order,
        verbose_name=_('order'),
        related_name='order_lines',
    )

    line_no = models.CharField(
        verbose_name=_('line no'),
        max_length=4,
    )

    product = models.ForeignKey(
        'aps_bom.Product',
        verbose_name=_('product'),
        related_name='order_lines',
    )

    quantity_ordered = models.PositiveIntegerField(
        verbose_name=_('quantity ordered'),
    )

    date_requested = models.DateTimeField(
        verbose_name=_('date requested'),
    )

    @property
    def date_shipped(self):

        shipments = Shipment.objects.filter(
            order_run__in=self.order_runs.all(),
            # order_run__is_open=False,
        )
        if not shipments or shipments.filter(order_run__is_open=True).exists():
            return None
        # if the sum of all shipped items for this line is equal to all
        # actually produced items, we can consider it fully shipped
        if shipments.aggregate(models.Sum('quantity'))['quantity__sum'] == (
            self.order_runs.all().aggregate(models.Sum('quantity_out'))[
                'quantity_out__sum'
            ]
        ):
            return shipments.order_by('-date_shipped')[0].date_shipped
        return None

    @property
    def date_delivered(self):
        shipped = self.date_shipped
        shipping_days = self.order.company.shipping_days
        if not shipped or not shipping_days:
            return None
        return self.date_shipped + timedelta(
            days=self.order.company.shipping_days)

    class Meta:
        ordering = ('order', 'line_no')
        unique_together = ('order', 'line_no')

class OrderRun(models.Model):
    """
    One production run for a line of an order.

    :order_line: the order line, for which this run is run
    :run_number: the identifying number of this run
    :parent: reference to another order run
    :ipn: what IPN this goes under
    :quantity_started: what number of items we start the run with
    :quantity_dest_test: how many items have been destroyed in tests
    :quantity_out: how many items this run yielded. This plus the items
      destroyed in tests subtracted from the quantity we started with, equals
      the amount of items lost through errors.
    :is_open: if the run is still in progress. Defaults to True
    :comment: comments on this run for additional notes

    """
    order_line = models.ForeignKey(
        OrderLine,
        verbose_name=_('order line'),
        related_name='order_runs',
    )

    run_number = models.CharField(
        verbose_name=_('run number'),
        max_length=64,
    )

    parent = models.ForeignKey(
        'self',
        verbose_name=_('parent'),
        related_name='order_runs',
        blank=True, null=True,
    )

    ipn = models.ForeignKey(
        'aps_bom.IPN',
        verbose_name=_('ipn'),
        related_name='order_runs',
    )

    quantity_started = models.PositiveIntegerField(
        verbose_name=_('quantity started'),
    )

    quantity_dest_out = models.PositiveIntegerField(
        verbose_name=_('quantity dest out'),
        blank=True, null=True,
    )

    quantity_out = models.PositiveIntegerField(
        verbose_name=_('quantity out'),
        blank=True, null=True,
    )

    is_open = models.BooleanField(
        verbose_name=_('Is open'),
        default=True,
    )

    comment = models.TextField(
        verbose_name=_('comment'),
        blank=True,
    )

class Shipment(models.Model):
    """
    Stores data about when an order run is shipped

    :order_run: the ``OrderRun`` this shipment belongs to
    :quantity: how many items were shipped
    :date_shipped: when it was shipped

    """
    order_run = models.ForeignKey(
        OrderRun,
        verbose_name=_('order run'),
        related_name='shipments',
    )

    quantity = models.PositiveIntegerField(
        verbose_name=_('quantity'),
    )

    date_shipped = models.DateTimeField(
        verbose_name=_('date shipped'),
    )


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>TableSqlMethodOption | etcsv</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="../assets/css/main.css">

                <input type="checkbox" id="tsd-filter-inherited" checked />
                Inherited

                <input type="checkbox" id="tsd-filter-private" checked />
                Private

                <input type="checkbox" id="tsd-filter-only-exported" />
                Only exported

            etcsv

        etcsv

        TableSqlMethodOption

Interface TableSqlMethodOption

TableSqlMethodOption

version

0.2.0

since

0.2.0

Index

Properties

db

fields

relations

table

Properties

public db: string

Defined in etcsv.ts:486

public fields: Array<string>

Defined in etcsv.ts:488

public relations: RelationOption[]

Defined in etcsv.ts:489

public table: string

Defined in etcsv.ts:487

    Globals

    etcsv

                    baseDir

                    fs

                    iconv

                    moment

                    parent

                    path

                    RelationOption

                    TableSqlMethodOption

                    db

                    fields

                    relations

                    table

                    CSV

                    Record

                    Relation

                    SQL

                    Table

                    imports


text:
import os
import re
import time
import errno
import signal
import socket
import classad
import unittest

class TestConfig(unittest.TestCase):

    def setUp(self):
        os.environ["_condor_FOO"] = "BAR"
        htcondor.reload_config()

    def test_config(self):
        self.assertEquals(htcondor.param["FOO"], "BAR")

    def test_reconfig(self):
        htcondor.param["FOO"] = "BAZ"
        self.assertEquals(htcondor.param["FOO"], "BAZ")
        os.environ["_condor_FOO"] = "1"
        htcondor.reload_config()
        self.assertEquals(htcondor.param["FOO"], "1")

class TestVersion(unittest.TestCase):

    def setUp(self):
        fd = os.popen("condor_version")
        self.lines = []
        for line in fd.readlines():
            self.lines.append(line.strip())
        if fd.close():
            raise RuntimeError("Unable to invoke condor_version")

    def test_version(self):
        self.assertEquals(htcondor.version(), self.lines[0])

    def test_platform(self):
        self.assertEquals(htcondor.platform(), self.lines[1])

def makedirs_ignore_exist(directory):
    try:
        os.makedirs(directory)
    except OSError, oe:
        if oe.errno != errno.EEXIST:
            raise

def remove_ignore_missing(file):
    try:
        os.unlink(file)
    except OSError, oe:
        if oe.errno != errno.ENOENT:
            raise

# Bootstrap condor
testdir = os.path.join(os.getcwd(), "tests_tmp")
logdir = os.path.join(testdir, "log")
makedirs_ignore_exist(testdir)
makedirs_ignore_exist(logdir)
config_file = os.path.join(testdir, "condor_config")
open(config_file, "w").close()
os.environ["CONDOR_CONFIG"] = config_file
os.environ["_condor_TOOL_LOG"] = os.path.join(logdir, "ToolLog")
import htcondor

class TestWithDaemons(unittest.TestCase):

    def setUp(self):
        self.pid = -1
        os.environ["_condor_MASTER"] = os.path.join(os.getcwd(), "../condor_master.V6/condor_master")
        os.environ["_condor_COLLECTOR"] = os.path.join(os.getcwd(), "../condor_collector.V6/condor_collector")
        os.environ["_condor_SCHEDD"] = os.path.join(os.getcwd(), "../condor_schedd.V6/condor_schedd")
        os.environ["_condor_PROCD"] = os.path.join(os.getcwd(), "../condor_procd/condor_procd")
        os.environ["_condor_STARTD"] = os.path.join(os.getcwd(), "../condor_startd.V6/condor_startd")
        os.environ["_condor_STARTER"] = os.path.join(os.getcwd(), "../condor_starter.V6.1/condor_starter")
        os.environ["_condor_NEGOTIATOR"] = os.path.join(os.getcwd(), "../condor_negotiator.V6/condor_negotiator")
        os.environ["_condor_SHADOW"] = os.path.join(os.getcwd(), "../condor_shadow.V6.1/condor_shadow")
        os.environ["_condor_CONDOR_HOST"] = socket.getfqdn()
        os.environ["_condor_LOCAL_DIR"] = testdir
        os.environ["_condor_LOG"] =  '$(LOCAL_DIR)/log'
        os.environ["_condor_LOCK"] = '$(LOCAL_DIR)/lock'
        os.environ["_condor_RUN"] = '$(LOCAL_DIR)/run'
        os.environ["_condor_COLLECTOR_NAME"] = "python_classad_tests"
        os.environ["_condor_SCHEDD_NAME"] = "python_classad_tests"
        os.environ["_condor_MASTER_ADDRESS_FILE"] = "$(LOG)/.master_address"
        os.environ["_condor_COLLECTOR_ADDRESS_FILE"] = "$(LOG)/.collector_address"
        os.environ["_condor_SCHEDD_ADDRESS_FILE"] = "$(LOG)/.schedd_address"
        os.environ["_condor_STARTD_ADDRESS_FILE"] = "$(LOG)/.startd_address"
        os.environ["_condor_NEGOTIATOR_ADDRESS_FILE"] = "$(LOG)/.negotiator_address"
        # Various required attributes for the startd
        os.environ["_condor_START"] = "TRUE"
        os.environ["_condor_SUSPEND"] = "FALSE"
        os.environ["_condor_CONTINUE"] = "TRUE"
        os.environ["_condor_PREEMPT"] = "FALSE"
        os.environ["_condor_KILL"] = "FALSE"
        os.environ["_condor_WANT_SUSPEND"] = "FALSE"
        os.environ["_condor_WANT_VACATE"] = "FALSE"
        os.environ["_condor_MachineMaxVacateTime"] = "5"
        htcondor.reload_config()
        htcondor.SecMan().invalidateAllSessions()

    def launch_daemons(self, daemons=["MASTER", "COLLECTOR"]):
        makedirs_ignore_exist(htcondor.param["LOG"])
        makedirs_ignore_exist(htcondor.param["LOCK"])
        makedirs_ignore_exist(htcondor.param["EXECUTE"])
        makedirs_ignore_exist(htcondor.param["SPOOL"])
        makedirs_ignore_exist(htcondor.param["RUN"])
        remove_ignore_missing(htcondor.param["MASTER_ADDRESS_FILE"])
        remove_ignore_missing(htcondor.param["COLLECTOR_ADDRESS_FILE"])
        remove_ignore_missing(htcondor.param["SCHEDD_ADDRESS_FILE"])
        if "COLLECTOR" in daemons:
            os.environ["_condor_PORT"] = "9622"
            os.environ["_condor_COLLECTOR_ARGS"] = "-port $(PORT)"
            os.environ["_condor_COLLECTOR_HOST"] = "$(CONDOR_HOST):$(PORT)"
        if 'MASTER' not in daemons:
            daemons.append('MASTER')
        os.environ["_condor_DAEMON_LIST"] = ", ".join(daemons)
        htcondor.reload_config()
        self.pid = os.fork()
        if not self.pid:
            try:
                try:
                    os.execvp("condor_master", ["condor_master", "-f"])
                except Exception, e:
                    print str(e)
            finally:
                os._exit(1)
        for daemon in daemons:
            self.waitLocalDaemon(daemon)

    def tearDown(self):
        if self.pid > 1:
            os.kill(self.pid, signal.SIGQUIT)
            pid, exit_status = os.waitpid(self.pid, 0)
            self.assertTrue(os.WIFEXITED(exit_status))
            code = os.WEXITSTATUS(exit_status)
            self.assertEquals(code, 0)

    def waitLocalDaemon(self, daemon, timeout=5):
        address_file = htcondor.param[daemon + "_ADDRESS_FILE"]
        for i in range(timeout):
            if os.path.exists(address_file):
                return
            time.sleep(1)
        if not os.path.exists(address_file):
            raise RuntimeError("Waiting for daemon %s timed out." % daemon)

    def waitRemoteDaemon(self, dtype, dname, pool=None, timeout=5):
        if pool:
            coll = htcondor.Collector(pool)
        else:
            coll = htcondor.Collector()
        for i in range(timeout):
            try:
                return coll.locate(dtype, dname)
            except Exception:
                pass
            time.sleep(1)
        return coll.locate(dtype, dname)

    def testDaemon(self):
        self.launch_daemons(["COLLECTOR"])

    def testLocate(self):
        self.launch_daemons(["COLLECTOR"])
        coll = htcondor.Collector()
        coll_ad = coll.locate(htcondor.DaemonTypes.Collector)
        self.assertTrue("MyAddress" in coll_ad)
        self.assertEquals(coll_ad["Name"].split(":")[-1], os.environ["_condor_PORT"])

    def testRemoteLocate(self):
        self.launch_daemons(["COLLECTOR"])
        coll = htcondor.Collector()
        coll_ad = coll.locate(htcondor.DaemonTypes.Collector)
        remote_ad = self.waitRemoteDaemon(htcondor.DaemonTypes.Collector, "%s@%s" % (htcondor.param["COLLECTOR_NAME"], htcondor.param["CONDOR_HOST"]))
        self.assertEquals(remote_ad["MyAddress"], coll_ad["MyAddress"])

    def testScheddLocate(self):
        self.launch_daemons(["SCHEDD", "COLLECTOR"])
        coll = htcondor.Collector()
        name = "%s@%s" % (htcondor.param["SCHEDD_NAME"], htcondor.param["CONDOR_HOST"])
        schedd_ad = self.waitRemoteDaemon(htcondor.DaemonTypes.Schedd, name, timeout=10)
        self.assertEquals(schedd_ad["Name"], name)

    def testCollectorAdvertise(self):
        self.launch_daemons(["COLLECTOR"])
        coll = htcondor.Collector()
        now = time.time()
        ad = classad.ClassAd('[MyType="GenericAd"; Name="Foo"; Foo=1; Bar=%f; Baz="foo"]' % now)
        coll.advertise([ad])
        for i in range(5):
            ads = coll.query(htcondor.AdTypes.Any, 'Name =?= "Foo"', ["Bar"])
            if ads: break
            time.sleep(1)
        self.assertEquals(len(ads), 1)
        self.assertEquals(ads[0]["Bar"], now)
        self.assertTrue("Foo" not in ads[0])

    def testScheddSubmit(self):
        self.launch_daemons(["SCHEDD", "COLLECTOR", "STARTD", "NEGOTIATOR"])
        output_file = os.path.join(testdir, "test.out")
        if os.path.exists(output_file):
            os.unlink(output_file)
        schedd = htcondor.Schedd()
        ad = classad.parse(open("tests/submit.ad"))
        ads = []
        cluster = schedd.submit(ad, 1, False, ads)
        #print ads[0]
        for i in range(60):
            ads = schedd.query("ClusterId == %d" % cluster, ["JobStatus"])
            #print ads
            if len(ads) == 0:
                break
            if i % 2 == 0:
                schedd.reschedule()
            time.sleep(1)
        self.assertEquals(open(output_file).read(), "hello world\n");

    def testScheddSubmitSpool(self):
        self.launch_daemons(["SCHEDD", "COLLECTOR", "STARTD", "NEGOTIATOR"])
        output_file = os.path.join(testdir, "test.out")
        if os.path.exists(output_file):
            os.unlink(output_file)
        schedd = htcondor.Schedd()
        ad = classad.parse(open("tests/submit.ad"))
        result_ads = []
        cluster = schedd.submit(ad, 1, True, result_ads)
        #print result_ads[0]
        schedd.spool(result_ads)
        for i in range(60):
            ads = schedd.query("ClusterId == %d" % cluster, ["JobStatus"])
            #print ads
            self.assertEquals(len(ads), 1)
            if ads[0]["JobStatus"] == 4:
                break
            if i % 5 == 0:
                schedd.reschedule()
            time.sleep(1)
        schedd.retrieve("ClusterId == %d" % cluster)
        #print "Final status:", schedd.query("ClusterId == %d" % cluster)[0];
        schedd.act(htcondor.JobAction.Remove, ["%d.0" % cluster])
        ads = schedd.query("ClusterId == %d" % cluster, ["JobStatus"])
        self.assertEquals(len(ads), 0)
        self.assertEquals(open(output_file).read(), "hello world\n");

    def testPing(self):
        self.launch_daemons(["COLLECTOR"])
        coll = htcondor.Collector()
        coll_ad = coll.locate(htcondor.DaemonTypes.Collector)
        self.assertTrue("MyAddress" in coll_ad)
        secman = htcondor.SecMan()
        authz_ad = secman.ping(coll_ad, "WRITE")
        self.assertTrue("AuthCommand" in authz_ad)
        self.assertEquals(authz_ad['AuthCommand'], 60021)
        self.assertTrue("AuthorizationSucceeded" in authz_ad)
        self.assertTrue(authz_ad['AuthorizationSucceeded'])

        authz_ad = secman.ping(coll_ad["MyAddress"], "WRITE")
        self.assertTrue("AuthCommand" in authz_ad)
        self.assertEquals(authz_ad['AuthCommand'], 60021)
        self.assertTrue("AuthorizationSucceeded" in authz_ad)
        self.assertTrue(authz_ad['AuthorizationSucceeded'])

        authz_ad = secman.ping(coll_ad["MyAddress"])
        self.assertTrue("AuthCommand" in authz_ad)
        self.assertEquals(authz_ad['AuthCommand'], 60021)
        self.assertTrue("AuthorizationSucceeded" in authz_ad)
        self.assertTrue(authz_ad['AuthorizationSucceeded'])

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


text:
import logging
import retrying

import sdk_cmd
import sdk_hosts

from security import kerberos

LOG = logging.getLogger(__name__)

USERS = ["client", "authorized", "unauthorized", "super"]

def get_service_principals(service_name: str, realm: str, custom_domain: str = None, health_check: bool = False) -> list:
    """
    Sets up the appropriate principals needed for a kerberized deployment of Kafka.
    :return: A list of said principals
    """
    primaries = ["kafka"]

    if health_check:
        primaries.append("kafka-health-check-client")

    tasks = ["kafka-0-broker", "kafka-1-broker", "kafka-2-broker"]

    if custom_domain:
        instances = map(
            lambda task: sdk_hosts.custom_host(service_name, task, custom_domain), tasks
        )
    else:
        instances = map(lambda task: sdk_hosts.autoip_host(service_name, task), tasks)

    principals = kerberos.generate_principal_list(primaries, instances, realm)
    principals.extend(kerberos.generate_principal_list(USERS, [None], realm))

    return principals

def wait_for_brokers(client: str, brokers: list):
    """
    Run bootstrap on the specified client to resolve the list of brokers
    """
    LOG.info("Running bootstrap to wait for DNS resolution")
    bootstrap_cmd = [
        "/opt/bootstrap",
        "-print-env=false",
        "-template=false",
        "-install-certs=false",
        "--self-resolve=false",
        "-resolve-hosts",
        ",".join(brokers),
    ]
    bootstrap_output = sdk_cmd.marathon_task_exec(client, " ".join(bootstrap_cmd))
    LOG.info(bootstrap_output)
    assert "SDK Bootstrap successful" in " ".join(str(bo) for bo in bootstrap_output)
    return True

def is_not_authorized(output: str) -> bool:
    return "Not authorized to access" in output

def get_kerberos_client_properties(ssl_enabled: bool) -> list:

    protocol = "SASL_SSL" if ssl_enabled else "SASL_PLAINTEXT"

    return [
        "security.protocol={protocol}".format(protocol=protocol),
        "sasl.mechanism=GSSAPI",
        "sasl.kerberos.service.name=kafka",
    ]

def get_ssl_client_properties(cn: str, has_kerberos: bool) -> list:

    if has_kerberos:
        client_properties = []
    else:
        client_properties = ["security.protocol=SSL"]

    client_properties.extend(
        [
            "ssl.truststore.location = {cn}_truststore.jks".format(cn=cn),
            "ssl.truststore.password = changeit",
            "ssl.keystore.location = {cn}_keystore.jks".format(cn=cn),
            "ssl.keystore.password = changeit",
        ]
    )

    return client_properties

def write_client_properties(id: str, task: str, lines: list) -> str:
    """Write a client properties file containing the specified lines"""

    output_file = "{id}-client.properties".format(id=id)

    LOG.info("Generating %s", output_file)
    output = sdk_cmd.create_task_text_file(task, output_file, lines)
    LOG.info(output)

    return output_file

def write_jaas_config_file(primary: str, task: str, krb5: object) -> str:
    output_file = "{primary}-client-jaas.config".format(primary=primary)

    LOG.info("Generating %s", output_file)

    # TODO: use kafka_client keytab path
    jaas_file_contents = [
        "KafkaClient {",
        "    com.sun.security.auth.module.Krb5LoginModule required",
        "    doNotPrompt=true",
        "    useTicketCache=true",
        '    principal=\\"{primary}@{realm}\\"'.format(primary=primary, realm=krb5.get_realm()),
        "    useKeyTab=true",
        '    serviceName=\\"kafka\\"',
        '    keyTab=\\"/tmp/kafkaconfig/kafka-client.keytab\\"',
        "    client=true;",
        "};",
    ]

    output = sdk_cmd.create_task_text_file(task, output_file, jaas_file_contents)
    LOG.info(output)

    return output_file

def setup_krb5_env(primary: str, task: str, krb5: object) -> str:
    env_setup_string = (
        'export KAFKA_OPTS=\\"'
        "-Djava.security.auth.login.config={} "
        "-Djava.security.krb5.conf={}"
        '\\"'.format(
            write_jaas_config_file(primary, task, krb5),
            kerberos.write_krb5_config_file(task, "krb5.config", krb5),
        )
    )
    LOG.info("Setting environment to %s", env_setup_string)
    return env_setup_string

def get_bash_command(cmd: str, environment: str) -> str:
    env_str = "{} && ".format(environment) if environment else ""

    return 'bash -c "{}{}"'.format(env_str, cmd)

def write_to_topic(
    cn: str,
    task: str,
    topic: str,
    message: str,
    client_properties: list = [],
    environment: str = None,
    broker_list: str = r"\$KAFKA_BROKER_LIST",
) -> bool:

    client_properties_file = write_client_properties(cn, task, client_properties)

    cmd_list = [
        "echo",
        message,
        "|",
        "kafka-console-producer",
        "--topic",
        topic,
        "--producer.config",
        client_properties_file,
        "--broker-list",
        broker_list,
    ]
    cmd = " ".join(str(c) for c in cmd_list)
    write_cmd = get_bash_command(cmd, environment)

    def write_failed(output) -> bool:
        LOG.info("Checking write output: %s", output)
        rc = output[0]
        stderr = output[2]

        if "TOPIC_AUTHORIZATION_FAILED" in stderr:
            LOG.info("Skipping retry - Authorization error: %s", stderr)
            return False
        if rc:
            LOG.error("Write failed with non-zero return code")
            return True
        if "UNKNOWN_TOPIC_OR_PARTITION" in stderr:
            LOG.error("Write failed due to stderr: UNKNOWN_TOPIC_OR_PARTITION")
            return True
        if "LEADER_NOT_AVAILABLE" in stderr and "ERROR Error when sending message" in stderr:
            LOG.error("Write failed due to stderr: LEADER_NOT_AVAILABLE")
            return True

        LOG.info("Output check passed")

        return False

    @retrying.retry(
        wait_exponential_multiplier=1000,
        wait_exponential_max=60 * 1000,
        retry_on_result=write_failed,
    )
    def write_wrapper():
        LOG.info("Running: %s", write_cmd)
        rc, stdout, stderr = sdk_cmd.marathon_task_exec(task, write_cmd)
        LOG.info("rc=%s\nstdout=%s\nstderr=%s\n", rc, stdout, stderr)

        return rc, stdout, stderr

    rc, stdout, stderr = write_wrapper()

    rc_success = rc == 0
    stdout_success = ">>" in stdout
    stderr_success = not is_not_authorized(stderr)

    return rc_success and stdout_success and stderr_success

def read_from_topic(
    cn: str,
    task: str,
    topic: str,
    messages: int,
    client_properties: list = [],
    environment: str = None,
    broker_list: str = r"\$KAFKA_BROKER_LIST",
) -> str:

    client_properties_file = write_client_properties(cn, task, client_properties)

    cmd_list = [
        "kafka-console-consumer",
        "--topic",
        topic,
        "--consumer.config",
        client_properties_file,
        "--bootstrap-server",
        broker_list,
        "--from-beginning",
        "--max-messages",
        messages,
        "--timeout-ms",
        60000,
    ]

    cmd = " ".join(str(c) for c in cmd_list)
    read_cmd = get_bash_command(cmd, environment)

    def read_failed(output) -> bool:
        LOG.info("Checking read output: %s", output)
        rc = output[0]
        stderr = output[2]

        if "TOPIC_AUTHORIZATION_FAILED" in stderr:
            LOG.info("Skipping retry - Authorization error: %s", stderr)
            return False
        if rc:
            LOG.error("Read failed with non-zero return code")
            return True
        if "kafka.consumer.ConsumerTimeoutException" in stderr:
            return True

        LOG.info("Output check passed")

        return False

    @retrying.retry(
        wait_exponential_multiplier=1000,
        wait_exponential_max=60 * 1000,
        retry_on_result=read_failed,
    )
    def read_wrapper():
        LOG.info("Running: %s", read_cmd)
        rc, stdout, stderr = sdk_cmd.marathon_task_exec(task, read_cmd)
        LOG.info("rc=%s\nstdout=%s\nstderr=%s\n", rc, stdout, stderr)

        return rc, stdout, stderr

    output = read_wrapper()

    if "TOPIC_AUTHORIZATION_FAILED" not in output[2]:
        # skip asserting rc code when authorization failed
        assert output[0] == 0
    return " ".join(str(o) for o in output)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Application_MySchool_VS2008
{
    public partial class Ajout_clients_Eleves : Form
    {
        private String lib_matiere;
        private int id_matiere;

        public Ajout_clients_Eleves()
        {
            InitializeComponent();
            FillCombo();
        }

        void FillCombo()
        {
            try
            {
                Ctes.command.CommandText = "select * from matiere ";
                Ctes.strConnectWeb.Open();

                Ctes.dr = Ctes.command.ExecuteReader();

                while (Ctes.dr.Read())
                {

                    lib_matiere = Ctes.dr.GetString("lib_matiere");
                    cbmatElv.Items.Add(lib_matiere);
                }

            }

            catch (Exception ex)
            { MessageBox.Show(ex.Message); }

            finally { Ctes.dr.Close(); Ctes.strConnectWeb.Close(); }

        }

        private void btnQuitter_Click(object sender, EventArgs e)
        {
            DialogResult dialog = MessageBox.Show("Vous voulez quittez l'application ?", "Exit", MessageBoxButtons.YesNo);
            if (dialog == DialogResult.Yes)
            {
                Application.Exit();
            }
            if (dialog == DialogResult.No)
            {

            }
        }

        private void bRetourAcc_Click(object sender, EventArgs e)
        {
            Accueil acc = new Accueil();
            this.Hide();
            acc.Show();
        }

        private void Ajout_clients_Eleves_Load(object sender, EventArgs e)
        {

        }

        private void BvallidCli_Click(object sender, EventArgs e)
        {

            try
            {
                Ctes.command.CommandText = "insert into client (civ_cli,nom_cli,prenom_cli,mobile_cli,fixe_cli,email_cli,connu_cli,remarques_cli,quartier_cli,adresse_cli,date_inscription_cli,login_cli,password_cli,ville_cli) values (@civ_cli,@nom_cli,@prenom_cli,@mobile_cli,@fixe_cli,@email_cli,@connu_cli,@remarques_cli,@quartier_cli,@adresse_cli,@date_inscription_cli,@nom_cli '" + 123 + "' ,@nom_cli '" + 123 + "' ,@ville_cli)";
                Ctes.command.Parameters.Clear();
                Ctes.command.Parameters.AddWithValue("@civ_cli",cbCivlCli.Text);
                Ctes.command.Parameters.AddWithValue("@nom_cli", tnomCli.Text);

               Ctes.command.Parameters.AddWithValue("@prenom_cli", tprenomCli.Text);
                Ctes.command.Parameters.AddWithValue("@mobile_cli", tTel1Cli.Text);

                Ctes.command.Parameters.AddWithValue("@fixe_cli", ttel2Cli.Text);
                Ctes.command.Parameters.AddWithValue("@email_cli", tEmailCli.Text);

                Ctes.command.Parameters.AddWithValue("@connu_cli", tConnucli.Text);

                Ctes.command.Parameters.AddWithValue("@remarques_cli", tRmqCli.Text);
                Ctes.command.Parameters.AddWithValue("@quartier_cli", tQuatCli.Text);

                Ctes.command.Parameters.AddWithValue("@adresse_cli", tAdressCli.Text);
                Ctes.command.Parameters.AddWithValue("@date_inscription_cli",tDateInsc.Text);

                Ctes.command.Parameters.AddWithValue("@ville_cli", cbVilleCli.Text);

                Ctes.strConnectWeb.Open();

                Ctes.command.ExecuteNonQuery();
                //Ctes.command.CommandText = "update client set civ_cli='" + cbCivlCli.Text + "',nom_cli='" + tnomCli.Text + "',prenom_cli='" + tprenomCli.Text + "',mobile_cli='" + tTel1Cli.Text + "',
                //fixe_cli='" + ttel2Cli.Text + "',email_cli='" + tEmailCli.Text + "',connu_cli='" + tConnucli.Text + "',remarques_cli='" + tRmqCli.Text + "',quartier_cli='" + tQuatCli.Text + "' ,adresse_cli='" + tAdressCli.Text + "',date_inscription_cli='" + tDateInsc.Text + "',login_cli='"+tnomCli.Text+"''"++"'  ";
                cbCivlCli.Text = "";
                tnomCli.Text = "";
                tprenomCli.Text = "";
                cbVilleCli.Text = "";
                tAdressCli.Text = "";
                tQuatCli.Text = "";
                tTel1Cli.Text = "";
                ttel2Cli.Text = "";
                tEmailCli.Text = "";
                tConnucli.Text = "";
                tRmqCli.Text = "";
                tDateInsc.Text = "";

                    MessageBox.Show("Client Bien Ajouter");
                    Ctes.command.CommandText = "select id_client,nom_cli from client where nom_cli=@nom_cli ";

                   Ctes.dr= Ctes.command.ExecuteReader();
                   if (Ctes.dr.Read())
                   {
                       lIDcli.Text = Ctes.dr[0].ToString();
                       lnomCli.Text = Ctes.dr[1].ToString();
                   }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally {  Ctes.dr.Close();Ctes.strConnectWeb.Close(); }

        }

        private void bcherchCli_Click(object sender, EventArgs e)
        {
            //-------------------------------Recherche  Client----------------------------

            try
            {
                string req = "";
                if (tIDcli.Text != "" & tnomcliV.Text == "")
                {

                    req = "select id_client,nom_cli from client where id_client='" + tIDcli.Text + "'";
                }
                if (tIDcli.Text == "" & tnomcliV.Text != "")
                {

                    req = "select id_client,nom_cli from client where nom_cli='" + tnomcliV.Text + "'";
                }
                if (tIDcli.Text != "" & tnomcliV.Text != "")
                {

                    req = "select id_client,nom_cli from client where nom_cli='" + tnomcliV.Text + "' and id_client='" + tIDcli.Text + "'";
                }
                Ctes.command.CommandText = req;

                Ctes.strConnectWeb.Open();
                Ctes.dr=Ctes.command.ExecuteReader();
                if (Ctes.dr.Read())
                {
                    lIDcli.Text = Ctes.dr[0].ToString();
                    lnomCli.Text = Ctes.dr[1].ToString();
                }
                else { MessageBox.Show("** Client introuvable ! **"); }

            }
            catch (Exception)
            {

                MessageBox.Show("catch"); ;
            }
            finally { Ctes.dr.Close() ;Ctes.strConnectWeb.Close(); }

        }

        private void bValidElv_Click(object sender, EventArgs e)
        {

            try
            {
                Ctes.command.CommandText =
 "insert into eleve (idclient,nom_ele,prenom_ele,hf_ele,niveau_ele,systeme_ele,etablissement_ele,tel_ele,age_ele,dispo_lundi_ele,dispo_mardi_ele,dispo_mercredi_ele,dispo_jeudi_ele,dispo_vendredi_ele,dispo_samedi_ele,dispo_dimanche_ele,nbr_heures_seance,nbr_heures_semaine,remarques_ele) values(@idclient,@nom_ele,@prenom_ele,@hf_ele,@niveau_ele,@systeme_ele,@etablissement_ele,@tel_ele,@age_ele,@dispo_lundi_ele,@dispo_mardi_ele,@dispo_mercredi_ele,@dispo_jeudi_ele,@dispo_vendredi_ele,@dispo_samedi_ele,@dispo_dimanche_ele,@nbr_heures_seance,@nbr_heures_semaine,@remarques_ele)";
                Ctes.command.Parameters.Clear();
                Ctes.command.Parameters.AddWithValue("@idclient", lIDcli.Text);
                Ctes.command.Parameters.AddWithValue("@nom_ele", tNonElev.Text);
                Ctes.command.Parameters.AddWithValue("@prenom_ele", TprenomElv.Text);
                Ctes.command.Parameters.AddWithValue("@hf_ele", cbHFelv.Text);
                Ctes.command.Parameters.AddWithValue("@niveau_ele", tNivElev.Text);
                Ctes.command.Parameters.AddWithValue("@systeme_ele", tSystmElve.Text);
                Ctes.command.Parameters.AddWithValue("@etablissement_ele", tEtabElv.Text);
                Ctes.command.Parameters.AddWithValue("@tel_ele", tTelElv.Text);
                Ctes.command.Parameters.AddWithValue("@age_ele", tAgeElv.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_lundi_ele", tLun.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_mardi_ele", tMar.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_mercredi_ele", tMer.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_jeudi_ele", tJeu.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_vendredi_ele", tVen.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_samedi_ele", tSam.Text);
                Ctes.command.Parameters.AddWithValue("@dispo_dimanche_ele", tDim.Text);
                Ctes.command.Parameters.AddWithValue("@nbr_heures_seance", tNbrHscé.Text);
                Ctes.command.Parameters.AddWithValue("@nbr_heures_semaine", tNbrHsem.Text);
                Ctes.command.Parameters.AddWithValue("@remarques_ele", tRqElv.Text);

                Ctes.strConnectWeb.Open();
               Ctes.command.ExecuteNonQuery();

                tnomcliV.Text = "";
                tNonElev.Text = "";
                TprenomElv.Text = "";
                cbHFelv.Text = "";
                tNivElev.Text = "";
                tSystmElve.Text = "";
                tEtabElv.Text = "";
                tTelElv.Text = "";
                tAgeElv.Text = "";
                tLun.Text = "";
                tMar.Text = "";
                tMer.Text = "";
                tJeu.Text = "";
                tVen.Text = "";
                tSam.Text = "";
                tDim.Text = "";
                tNbrHscé.Text = "";
                tNbrHsem.Text = "";
                tRqElv.Text = "";
                if (Ctes.strConnectWeb != null)
                {
                    MessageBox.Show(" ***Eleve Bien Ajouter*** ");
                }
                else
                {
                    MessageBox.Show("***Vous devez saisir un Eleve***");
                }
                Ctes.command.CommandText = "select id_eleve,idclient,nom_ele,prenom_ele from eleve where idclient='" + lIDcli .Text+ "' and    prenom_ele=@prenom_ele and nom_ele=@nom_ele  ";

                Ctes.dr=Ctes.command.ExecuteReader();
                if (Ctes.dr.Read())
                {
                   lIDelveVnt.Text = Ctes.dr[0].ToString();
                    lIDcliElvVnt.Text= Ctes.dr[1].ToString();
                  lNomElvVent.Text= Ctes.dr[2].ToString();
                    lPrenomElevVent.Text = Ctes.dr[3].ToString();
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally { Ctes.dr.Close(); Ctes.strConnectWeb.Close(); }

        }

        private void bValdVente_Click(object sender, EventArgs e)
        {

            try
            {
                Ctes.command.CommandText =
 "insert into vente (idclient,ideleve,pu,nbr_tickets,mode_paiement,premier_ticket,dernier_ticket,renouvellement,paye,remarque) values(@idclient,@ideleve,@pu,@nbr_tickets,@mode_paiement,@premier_ticket,@dernier_ticket,@renouvellement,@paye,@remarque)";
                Ctes.command.Parameters.Clear();
                Ctes.command.Parameters.AddWithValue("@idclient", lIDcliElvVnt.Text);
                Ctes.command.Parameters.AddWithValue("@ideleve", lIDelveVnt.Text);
                Ctes.command.Parameters.AddWithValue("@pu",tPU.Text);
                Ctes.command.Parameters.AddWithValue("@nbr_tickets", tNbrTicks.Text);
                Ctes.command.Parameters.AddWithValue("@mode_paiement", cbModepaiCli.Text);
                Ctes.command.Parameters.AddWithValue("@premier_ticket", tPmTk.Text);
                Ctes.command.Parameters.AddWithValue("@dernier_ticket", tDerntk.Text);
                Ctes.command.Parameters.AddWithValue("@renouvellement", cbRenouvl.Text);
                Ctes.command.Parameters.AddWithValue("@paye", cbPaye.Text);
                Ctes.command.Parameters.AddWithValue("@remarque", tRmqVent);

                Ctes.strConnectWeb.Open();
                Ctes.command.ExecuteNonQuery();
                tNbrTicks.Text = "";
                tPU.Text = "";
                cbModepaiCli.Text = "";
                tPmTk.Text = "";
                tDerntk.Text = "";
                cbRenouvl.Text = "";
                cbPaye.Text = "";

                if (Ctes.strConnectWeb != null)
                {
                    MessageBox.Show(" ***Vente Bien Ajouter*** ");
                }
                else
                {
                    MessageBox.Show("***Vous devez saisir un Eleve***");
                }
                Ctes.command.CommandText = "select id_eleve,nom_ele,prenom_ele  from eleve where id_eleve='" + lIDelveVnt.Text + "'   ";

                Ctes.dr = Ctes.command.ExecuteReader();
                if (Ctes.dr.Read())
                {
                    lIdElMat.Text = Ctes.dr[0].ToString();

             }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally { Ctes.dr.Close();Ctes.strConnectWeb.Close(); }

        }

        private void bValidMatireElv_Click(object sender, EventArgs e)
        {

            try
            {

                Ctes.command.CommandText="select id_matiere from matiere where lib_matiere='"+cbmatElv.Text+"' ";
                Ctes.strConnectWeb.Open();
                Ctes.dr = Ctes.command.ExecuteReader();
                if (Ctes.dr.Read())
                {

                    id_matiere = Ctes.dr.GetInt16("id_matiere");

                }
            }catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally { Ctes.dr.Close(); Ctes.strConnectWeb.Close(); }

            try
            {
                Ctes.command.CommandText ="insert into eleve_matiere (ideleve,idmatiere,note,type_cours,remarque ) values(@ideleve,@idmatiere,@note,@type_cours,@remarque)";
                Ctes.command.Parameters.Clear();

                Ctes.command.Parameters.AddWithValue("@ideleve", lIdElMat.Text);
                Ctes.command.Parameters.AddWithValue("@idmatiere", id_matiere);
                Ctes.command.Parameters.AddWithValue("@note", tNotmat.Text);
                Ctes.command.Parameters.AddWithValue("@type_cours", cbTypCours.Text);
                Ctes.command.Parameters.AddWithValue("@remarque", tRmQMatElv.Text);

                Ctes.strConnectWeb.Open();
                Ctes.command.ExecuteNonQuery();
                cbmatElv.Text = "";
                tNotmat.Text = "";
                tRmQMatElv.Text = "";
                cbTypCours.Text = "";
                cbActivElv.Text = "";
                if (Ctes.dr != null)
                {
                    MessageBox.Show(" ***Matiere Eleve Bien Ajouter*** ");
                }
                else
                {
                    MessageBox.Show("***Vous devez saisir un Eleve***");
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally { Ctes.dr.Close(); Ctes.strConnectWeb.Close(); }

        }

        private void bafficher_Click(object sender, EventArgs e)
        {

            string constring = "SERVER=localhost;DATABASE=myschool_dbsite;UID=root;PASSWORD=nabil;Allow Zero Datetime=true;CharacterSet = latin1;default command timeout=30;";
            MySqlConnection conDataBase = new MySqlConnection(constring);
            MySqlCommand cmdDataBase = new MySqlCommand("select el.ideleve, m.lib_matiere,el.note,el.remarque from matiere m , eleve_matiere el where el.ideleve = " + lIdElMat.Text + " and m.id_matiere=el.idmatiere", conDataBase);

            try
            {
                MySqlDataAdapter sda = new MySqlDataAdapter();
                sda.SelectCommand = cmdDataBase;
                DataTable dbdataset = new DataTable();
                sda.Fill(dbdataset);
                BindingSource bSource = new BindingSource();

                bSource.DataSource = dbdataset;
                dataGridView1.DataSource = bSource;
                sda.Update(dbdataset);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void cbmatElv_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }

        private void tnomcliV_TextChanged(object sender, EventArgs e)
        {

        }

    }
}


text:
package libkbfs

import (
	"fmt"
	"sync"
	"time"

	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/keybase1"
	"golang.org/x/net/context"
)

type onlineStatusTracker struct {
	cancel   func()
	config   Config
	onChange func()
	vlog     *libkb.VDebugLog

	lock          sync.RWMutex
	currentStatus keybase1.KbfsOnlineStatus
	userIsLooking map[string]bool

	userIn  chan struct{}
	userOut chan struct{}

	wg *sync.WaitGroup
}

const ostTryingStateTimeout = 4 * time.Second

type ostState int

const (
	_ ostState = iota
	// We are connected to the mdserver, and user is looking at the Fs tab.
	ostOnlineUserIn
	// We are connected to the mdserver, and user is not looking at the Fs tab.
	ostOnlineUserOut
	// User is looking at the Fs tab. We are not connected to the mdserver, but
	// we are showing a "trying" state in GUI. This usually lasts for
	// ostTryingStateTimeout.
	ostTryingUserIn
	// User is not looking at the Fs tab. We are not connected to the mdserver,
	// but we are telling GUI a "trying" state.
	ostTryingUserOut
	// User is looking at the Fs tab. We are disconnected from the mdserver and
	// are telling GUI so.
	ostOfflineUserIn
	// User is not looking at the Fs tab. We are disconnected from the mdserver
	// and are telling GUI so.
	//
	// Note that we can only go to ostOfflineUserOut from ostOfflineUserIn, but
	// not from any other state. This is because when user is out we don't fast
	// forward. Even if user has got good connection, we might still show as
	// offline until user navigates into the Fs tab which triggers a fast
	// forward and get us connected. If we were to show this state, user would
	// see an offline screen flash for a second before actually getting
	// connected every time they come back to the Fs tab with a previous bad
	// (or lack of) connection, or even from backgrounded app.  So instead, in
	// this case we just use the trying state which shows a slim (less
	// invasive) banner saying we are trying to reconnect.  On the other hand,
	// if user has seen the transition into offline, and user has remained
	// disconnected, it'd be weird for them to see a "trying" state every time
	// they switch away and back into the Fs tab. So in this case just keep the
	// offline state, which is what ostOfflineUserOut is for.
	ostOfflineUserOut
)

func (s ostState) String() string {
	switch s {
	case ostOnlineUserIn:
		return "online-userIn"
	case ostOnlineUserOut:
		return "online-userOut"
	case ostTryingUserIn:
		return "trying-userIn"
	case ostTryingUserOut:
		return "trying-userOut"
	case ostOfflineUserIn:
		return "offline-userIn"
	case ostOfflineUserOut:
		return "offline-userOut"
	default:
		panic("unknown state")
	}
}

func (s ostState) getOnlineStatus() keybase1.KbfsOnlineStatus {
	switch s {
	case ostOnlineUserIn:
		return keybase1.KbfsOnlineStatus_ONLINE
	case ostOnlineUserOut:
		return keybase1.KbfsOnlineStatus_ONLINE
	case ostTryingUserIn:
		return keybase1.KbfsOnlineStatus_TRYING
	case ostTryingUserOut:
		return keybase1.KbfsOnlineStatus_TRYING
	case ostOfflineUserIn:
		return keybase1.KbfsOnlineStatus_OFFLINE
	case ostOfflineUserOut:
		return keybase1.KbfsOnlineStatus_OFFLINE
	default:
		panic("unknown state")
	}
}

// ostSideEffect is a type for side effects that happens as a result of
// transitions happening inside the FSM. These side effects describe what
// should happen, but the FSM doesn't directly do them. The caller of outFsm
// should make sure those actions are carried out.
type ostSideEffect int

const (
	// ostResetTimer describes a side effect where the timer for transitioning
	// from a "trying" state into a "offline" state should be reset and
	// started.
	ostResetTimer ostSideEffect = iota
	// ostStopTimer describes a side effect where the timer for transitioning
	// from a "trying" state into a "offline" state should be stopped.
	ostStopTimer
	// ostFastForward describes a side effect where we should fast forward the
	// reconnecting backoff timer and attempt to connect to the mdserver right
	// away.
	ostFastForward
)

func ostFsm(
	ctx context.Context,
	wg *sync.WaitGroup,
	vlog *libkb.VDebugLog,
	initialState ostState,
	// sideEffects carries events about side effects caused by the FSM
	// transitions. Caller should handle these effects and make things actually
	// happen.
	sideEffects chan<- ostSideEffect,
	// onlineStatusUpdates carries a special side effect for the caller to know
	// when the onlineStatus changes.
	onlineStatusUpdates chan<- keybase1.KbfsOnlineStatus,
	// userIn is used to signify the FSM that user has just started looking at
	// the Fs tab.
	userIn <-chan struct{},
	// userOut is used to signify the FSM that user has just switched away from
	// the Fs tab.
	userOut <-chan struct{},
	// tryingTimerUp is used to signify the FSM that the timer for
	// transitioning from a "trying" state to "offline" state is up.
	tryingTimerUp <-chan struct{},
	// connected is used to signify the FSM that we've just connected to the
	// mdserver.
	connected <-chan struct{},
	// disconnected is used to signify the FSM that we've just lost connection to
	// the mdserver.
	disconnected <-chan struct{},
) {
	defer wg.Done()

	select {
	case <-ctx.Done():
		return
	default:
	}
	vlog.CLogf(ctx, libkb.VLog1, "ostFsm initialState=%s", initialState)

	state := initialState
	for {
		previousState := state

		switch state {
		case ostOnlineUserIn:
			select {
			case <-userIn:
			case <-userOut:
				state = ostOnlineUserOut
			case <-tryingTimerUp:
			case <-connected:
			case <-disconnected:
				state = ostTryingUserIn
				sideEffects <- ostFastForward
				sideEffects <- ostResetTimer

			case <-ctx.Done():
				return
			}
		case ostOnlineUserOut:
			select {
			case <-userIn:
				state = ostOnlineUserIn
			case <-userOut:
			case <-tryingTimerUp:
			case <-connected:
			case <-disconnected:
				state = ostTryingUserOut
				// Don't start a timer as we don't want to transition into
				// offline from trying when user is out. See comment for
				// ostOfflineUserOut above.

			case <-ctx.Done():
				return
			}
		case ostTryingUserIn:
			select {
			case <-userIn:
			case <-userOut:
				state = ostTryingUserOut
				// Stop the timer as we don't transition into offline when
				// user is not looking.
				sideEffects <- ostStopTimer
			case <-tryingTimerUp:
				state = ostOfflineUserIn
			case <-connected:
				state = ostOnlineUserIn
			case <-disconnected:

			case <-ctx.Done():
				return
			}
		case ostTryingUserOut:
			select {
			case <-userIn:
				state = ostTryingUserIn
				sideEffects <- ostFastForward
				sideEffects <- ostResetTimer
			case <-userOut:
			case <-tryingTimerUp:
				// Don't transition into ostOfflineUserOut. See comment for
				// offlienUserOut above.
			case <-connected:
				state = ostOnlineUserOut
			case <-disconnected:

			case <-ctx.Done():
				return
			}
		case ostOfflineUserIn:
			select {
			case <-userIn:
			case <-userOut:
				state = ostOfflineUserOut
			case <-tryingTimerUp:
			case <-connected:
				state = ostOnlineUserIn
			case <-disconnected:

			case <-ctx.Done():
				return
			}
		case ostOfflineUserOut:
			select {
			case <-userIn:
				state = ostOfflineUserIn
				// Trigger fast forward but don't transition into "trying", to
				// avoid flip-flopping.
				sideEffects <- ostFastForward
			case <-userOut:
			case <-tryingTimerUp:
			case <-connected:
				state = ostOnlineUserOut
			case <-disconnected:

			case <-ctx.Done():
				return
			}

		}

		if previousState != state {
			vlog.CLogf(ctx, libkb.VLog1, "ostFsm state=%s", state)
			onlineStatus := state.getOnlineStatus()
			if previousState.getOnlineStatus() != onlineStatus {
				select {
				case onlineStatusUpdates <- onlineStatus:
				case <-ctx.Done():
					return
				}
			}
		}
	}
}

func (ost *onlineStatusTracker) updateOnlineStatus(onlineStatus keybase1.KbfsOnlineStatus) {
	ost.lock.Lock()
	ost.currentStatus = onlineStatus
	ost.lock.Unlock()
	ost.onChange()
}

func (ost *onlineStatusTracker) run(ctx context.Context) {
	defer ost.wg.Done()

	for ost.config.KBFSOps() == nil {
		time.Sleep(100 * time.Millisecond)
	}

	tryingStateTimer := time.NewTimer(time.Hour)
	tryingStateTimer.Stop()

	sideEffects := make(chan ostSideEffect)
	onlineStatusUpdates := make(chan keybase1.KbfsOnlineStatus)
	tryingTimerUp := make(chan struct{})
	connected := make(chan struct{})
	disconnected := make(chan struct{})

	serviceErrors, invalidateChan := ost.config.KBFSOps().
		StatusOfServices()

	initialState := ostOfflineUserOut
	if serviceErrors[MDServiceName] == nil {
		initialState = ostOnlineUserOut
	}

	ost.wg.Add(1)
	go ostFsm(ctx, ost.wg, ost.vlog,
		initialState, sideEffects, onlineStatusUpdates,
		ost.userIn, ost.userOut, tryingTimerUp, connected, disconnected)

	ost.wg.Add(1)
	// mdserver connection status watch routine
	go func() {
		defer ost.wg.Done()
		invalidateChan := invalidateChan
		var serviceErrors map[string]error
		for {
			select {
			case <-invalidateChan:
				serviceErrors, invalidateChan = ost.config.KBFSOps().
					StatusOfServices()
				if serviceErrors[MDServiceName] == nil {
					connected <- struct{}{}
				} else {
					disconnected <- struct{}{}
				}
			case <-ctx.Done():
				return
			}
		}
	}()

	for {
		select {
		case <-tryingStateTimer.C:
			tryingTimerUp <- struct{}{}
		case sideEffect := <-sideEffects:
			switch sideEffect {
			case ostResetTimer:
				if !tryingStateTimer.Stop() {
					select {
					case <-tryingStateTimer.C:
					default:
					}
				}
				tryingStateTimer.Reset(ostTryingStateTimeout)
			case ostStopTimer:
				if !tryingStateTimer.Stop() {
					<-tryingStateTimer.C
					select {
					case <-tryingStateTimer.C:
					default:
					}
				}
			case ostFastForward:
				// This requires holding a lock and may block sometimes.
				go ost.config.MDServer().FastForwardBackoff()
			default:
				panic(fmt.Sprintf("unknown side effect %d", sideEffect))
			}
		case onlineStatus := <-onlineStatusUpdates:
			ost.updateOnlineStatus(onlineStatus)
			ost.vlog.CLogf(ctx, libkb.VLog1, "ost onlineStatus=%d", onlineStatus)
		case <-ctx.Done():
			return
		}
	}
}

// TODO: we now have clientID in the subscriptionManager so it's not necessary
// anymore for onlineStatusTracker to track it.

func (ost *onlineStatusTracker) userInOut(clientID string, clientIsIn bool) {
	ost.lock.Lock()
	wasIn := len(ost.userIsLooking) != 0
	if clientIsIn {
		ost.userIsLooking[clientID] = true
	} else {
		delete(ost.userIsLooking, clientID)
	}
	isIn := len(ost.userIsLooking) != 0
	ost.lock.Unlock()

	if wasIn && !isIn {
		ost.userOut <- struct{}{}
	}

	if !wasIn && isIn {
		ost.userIn <- struct{}{}
	}
}

// UserIn tells the onlineStatusTracker that user is looking at the Fs tab in
// GUI. When user is looking at the Fs tab, the underlying RPC fast forwards
// any backoff timer for reconnecting to the mdserver.
func (ost *onlineStatusTracker) UserIn(ctx context.Context, clientID string) {
	ost.userInOut(clientID, true)
	ost.vlog.CLogf(ctx, libkb.VLog1, "UserIn clientID=%s", clientID)
}

// UserOut tells the onlineStatusTracker that user is not looking at the Fs
// tab in GUI anymore.  GUI.
func (ost *onlineStatusTracker) UserOut(ctx context.Context, clientID string) {
	ost.userInOut(clientID, false)
	ost.vlog.CLogf(ctx, libkb.VLog1, "UserOut clientID=%s", clientID)
}

// GetOnlineStatus implements the OnlineStatusTracker interface.
func (ost *onlineStatusTracker) GetOnlineStatus() keybase1.KbfsOnlineStatus {
	ost.lock.RLock()
	defer ost.lock.RUnlock()
	return ost.currentStatus
}

func newOnlineStatusTracker(
	config Config, onChange func()) *onlineStatusTracker {
	ctx, cancel := context.WithCancel(context.Background())
	log := config.MakeLogger("onlineStatusTracker")
	ost := &onlineStatusTracker{
		cancel:        cancel,
		config:        config,
		onChange:      onChange,
		currentStatus: keybase1.KbfsOnlineStatus_ONLINE,
		vlog:          config.MakeVLogger(log),
		userIsLooking: make(map[string]bool),
		userIn:        make(chan struct{}),
		userOut:       make(chan struct{}),
		wg:            &sync.WaitGroup{},
	}

	ost.wg.Add(1)
	go ost.run(ctx)

	return ost
}

func (ost *onlineStatusTracker) shutdown() {
	ost.cancel()
	ost.wg.Wait()
}