/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-
BMP SUPPORT (READING)
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-
197575
private function ImageCreateFromBMP($filename)
		# Author:     DHKold
		# Date:     The 15th of June 2005
		# Version:    2.0B
		# Purpose:    To create an image from a BMP file.
		# Param in:   BMP file to open.
		# Param out:  Return a resource like the other ImageCreateFrom functions
		# Reference:  http://us3.php.net/manual/en/function.imagecreate.php#53879
		# Bug fix:    Author:   domelca at terra dot es
		#       Date:   06 March 2008
		#       Fix:    Correct 16bit BMP support
		# Notes:
		#
	{

		//Ouverture du fichier en mode binaire
		if ( ! $f1 = fopen($filename, "rb"))
		{
			return false;
		}

		//1 : Chargement des ent�tes FICHIER
		$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1, 14));
		if ($FILE['file_type'] != 19778)
		{
			return false;
		}

		//2 : Chargement des ent�tes BMP
		$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' .
			'/Vcompression/Vsize_bitmap/Vhoriz_resolution' .
			'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1, 40));
		$BMP['colors'] = pow(2, $BMP['bits_per_pixel']);

		if ($BMP['size_bitmap'] == 0)
		{
			$BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
		}

		$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel'] / 8;
		$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
		$BMP['decal'] = ($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
		$BMP['decal'] -= floor($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
		$BMP['decal'] = 4 - (4 * $BMP['decal']);

		if ($BMP['decal'] == 4)
		{
			$BMP['decal'] = 0;
		}

		//3 : Chargement des couleurs de la palette
		$PALETTE = array();
		if ($BMP['colors'] < 16777216)
		{
			$PALETTE = unpack('V' . $BMP['colors'], fread($f1, $BMP['colors'] * 4));
		}

		//4 : Cr�ation de l'image
		$IMG = fread($f1, $BMP['size_bitmap']);
		$VIDE = chr(0);

		$res = imagecreatetruecolor($BMP['width'], $BMP['height']);
		$P = 0;
		$Y = $BMP['height'] - 1;
		while ($Y >= 0)
		{
			$X = 0;
			while ($X < $BMP['width'])
			{
				if ($BMP['bits_per_pixel'] == 24)
				{
					$COLOR = unpack("V", substr($IMG, $P, 3) . $VIDE);
				}
				elseif ($BMP['bits_per_pixel'] == 16)
				{

					/*
           * BMP 16bit fix
           * =================
           *
           * Ref: http://us3.php.net/manual/en/function.imagecreate.php#81604
           *
           * Notes:
           * "don't work with bmp 16 bits_per_pixel. change pixel
           * generator for this."
           *
           */

					// *** Original code (don't work)
					//$COLOR = unpack("n",substr($IMG,$P,2));
					//$COLOR[1] = $PALETTE[$COLOR[1]+1];

					$COLOR = unpack("v", substr($IMG, $P, 2));
					$blue = ($COLOR[1] & 0x001f) << 3;
					$green = ($COLOR[1] & 0x07e0) >> 3;
					$red = ($COLOR[1] & 0xf800) >> 8;
					$COLOR[1] = $red * 65536 + $green * 256 + $blue;

				}
				elseif ($BMP['bits_per_pixel'] == 8)
				{
					$COLOR = unpack("n", $VIDE . substr($IMG, $P, 1));
					$COLOR[1] = $PALETTE[ $COLOR[1] + 1 ];
				}
				elseif ($BMP['bits_per_pixel'] == 4)
				{
					$COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
					if (($P * 2) % 2 == 0)
					{
						$COLOR[1] = ($COLOR[1] >> 4);
					}
					else
					{
						$COLOR[1] = ($COLOR[1] & 0x0F);
					}
					$COLOR[1] = $PALETTE[ $COLOR[1] + 1 ];
				}
				elseif ($BMP['bits_per_pixel'] == 1)
				{
					$COLOR = unpack("n", $VIDE . substr($IMG, floor($P), 1));
					if (($P * 8) % 8 == 0)
					{
						$COLOR[1] = $COLOR[1] >> 7;
					}
					elseif (($P * 8) % 8 == 1)
					{
						$COLOR[1] = ($COLOR[1] & 0x40) >> 6;
					}
					elseif (($P * 8) % 8 == 2)
					{
						$COLOR[1] = ($COLOR[1] & 0x20) >> 5;
					}
					elseif (($P * 8) % 8 == 3)
					{
						$COLOR[1] = ($COLOR[1] & 0x10) >> 4;
					}
					elseif (($P * 8) % 8 == 4)
					{
						$COLOR[1] = ($COLOR[1] & 0x8) >> 3;
					}
					elseif (($P * 8) % 8 == 5)
					{
						$COLOR[1] = ($COLOR[1] & 0x4) >> 2;
					}
					elseif (($P * 8) % 8 == 6)
					{
						$COLOR[1] = ($COLOR[1] & 0x2) >> 1;
					}
					elseif (($P * 8) % 8 == 7)
					{
						$COLOR[1] = ($COLOR[1] & 0x1);
					}
					$COLOR[1] = $PALETTE[ $COLOR[1] + 1 ];
				}
				else
				{
					return false;
				}

				imagesetpixel($res, $X, $Y, $COLOR[1]);
				$X++;
				$P += $BMP['bytes_per_pixel'];
			}

			$Y--;
			$P += $BMP['decal'];
		}
		//Fermeture du fichier
		fclose($f1);

		return $res;
	}
1211158
static String dbgBuffer(ByteBuffer b, int size) {
    StringBuilder sb = new StringBuilder();
    byte[] bytes = b.array();
    for (int i = 0; i < size; i++) {
      char ch = (char) bytes[i];
      if (Character.isWhitespace(ch) || Character.isLetterOrDigit(ch)) {
        sb.append(ch);
      } else {
        sb.append("\\x");
        sb.append(Integer.toHexString(bytes[i] & 0xff));
      }
    }
    return sb.toString();
  }
1322318
@Override
    public boolean readBoolean(String message, Boolean defaultValue) throws IOException {
        saveCursorPosition();
        Ansi style = ansi();
        if (getTheme().getPromptBackground() != null) {
            style.bg(getTheme().getPromptBackground());
        }
        if (getTheme().getPromptForeground() != null) {
            style.fg(getTheme().getPromptForeground());
        }
        for (int i = 1; i <= getFooterSize(); i++) {
            console.out().print(ansi().cursor(terminal.getHeight() - getFooterSize() + i, 1));
            console.out().print(style.eraseLine(Ansi.Erase.FORWARD));
        }
        console.out().print(ansi().cursor(terminal.getHeight(), 1));
        console.out().print(style.a(message).bold().eraseLine(Ansi.Erase.FORWARD));
        restoreCursorPosition();
        flush();
        try {
            EditorOperation operation;
            while (true) {
                operation = readOperation();
                switch (operation.getType()) {
                    case NEWLINE:
                        return defaultValue;
                    case TYPE:
                        if ("y".equals(operation.getInput()) || "Y".equals(operation.getInput())) {
                            return true;
                        } else if ("n".equals(operation.getInput()) || "N".equals(operation.getInput())) {
                            return false;
                        }
                }
            }
        } finally {
            redrawFooter();
        }
    }
575171
function readBlobAsDataURL(blob, path) {
                    var reader = new FileReader();
                    reader.onloadend = function(loadedEvent) {
                        var dataURL = loadedEvent.target.result;
                        var blobtype = 'Blob';
                        if (blob instanceof File) {
                            //blobtype = 'File';
                        }
                        updateEncodedBlob(dataURL, path, blobtype);
                    };
                    reader.readAsDataURL(blob);
                }
505565
function parse_PtgMemArea(blob, length, opts) {
	var type = (blob.read_shift(1) >>> 5) & 0x03;
	blob.l += (opts && opts.biff == 2 ? 3 : 4);
	var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
	return [type, cce];
}
1109273
private void processParameters() throws BadElementException, IOException {
        type = IMGTEMPLATE;
        originalType = ORIGINAL_WMF;
        InputStream is = null;
        try {
            String errorID;
            if (rawData == null){
                is = url.openStream();
                errorID = url.toString();
            }
            else{
                is = new java.io.ByteArrayInputStream(rawData);
                errorID = "Byte array";
            }
            InputMeta in = new InputMeta(is);
            if (in.readInt() != 0x9AC6CDD7)	{
                throw new BadElementException(errorID + " is not a valid placeable windows metafile.");
            }
            in.readWord();
            int left = in.readShort();
            int top = in.readShort();
            int right = in.readShort();
            int bottom = in.readShort();
            int inch = in.readWord();
            dpiX = 72;
            dpiY = 72;
            scaledHeight = (float)(bottom - top) / inch * 72f;
            setTop(scaledHeight);
            scaledWidth = (float)(right - left) / inch * 72f;
            setRight(scaledWidth);
        }
        finally {
            if (is != null) {
                is.close();
            }
            plainWidth = getWidth();
            plainHeight = getHeight();
        }
    }
1317068
function _bfs(canvas, queue, eventMap, blacklist) {
    var ctx = canvas.getContext('2d'),
        imgSize = {
            w: canvas.width,
            h: canvas.height
        },
        imgCols = ctx.getImageData(0, 0, imgSize.w, imgSize.h).data,
        visited = {},
        stopMainLoop = false,
        skipNeighbords = false;

    if (blacklist !== undefined) {
        blacklist.forEach(function(coord) {
            visited[coord.x + '-' + coord.y] = true;
        });
    }

    function visitPx(coord) {
        visited[coord.x + '-' + coord.y] = true;
        if (eventMap !== undefined && eventMap.onvisit !== undefined) {
            eventMap.onvisit({
                pixel: {
                    coord: coord,
                    color: _getColorByXY(coord, imgSize, imgCols)
                },
                stop: function() { stopMainLoop = true; },
                skip: function() { skipNeighbords = true; }
            });
        }
    }

    visitPx(queue[0]);

mainLoop:
    while (queue.length > 0) {
        if (stopMainLoop) { break mainLoop; }

        var coord = queue.shift(),
            colPos = _getColorPositionByXY(coord, imgSize),
            col = [imgCols[colPos], imgCols[colPos+1], imgCols[colPos+2], imgCols[colPos+3]],
            px = { coord: coord, color: col },
            nPxs = _getNeighborPixels(coord, imgSize, imgCols);

        for (var i = 0; i < nPxs.length; i++) {
            var nPx = nPxs[i];
            if (visited[nPx.coord.x + '-' + nPx.coord.y] !== true) {
                visitPx(nPx.coord);
                if (stopMainLoop) { break mainLoop; }
                if (!skipNeighbords) {
                    queue.push(nPx.coord);
                }
                skipNeighbords = false;
            }
        }
    }
}
266156
function parse_BrtFont(data, length, opts) {
	var out = ({});

	out.sz = data.read_shift(2) / 20;

	var grbit = parse_FontFlags(data, 2, opts);
	if(grbit.fCondense) out.condense = 1;
	if(grbit.fExtend) out.extend = 1;
	if(grbit.fShadow) out.shadow = 1;
	if(grbit.fOutline) out.outline = 1;
	if(grbit.fStrikeout) out.strike = 1;
	if(grbit.fItalic) out.italic = 1;

	var bls = data.read_shift(2);
	if(bls === 0x02BC) out.bold = 1;

	switch(data.read_shift(2)) {
		/* case 0: out.vertAlign = "baseline"; break; */
		case 1: out.vertAlign = "superscript"; break;
		case 2: out.vertAlign = "subscript"; break;
	}

	var underline = data.read_shift(1);
	if(underline != 0) out.underline = underline;

	var family = data.read_shift(1);
	if(family > 0) out.family = family;

	var bCharSet = data.read_shift(1);
	if(bCharSet > 0) out.charset = bCharSet;

	data.l++;
	out.color = parse_BrtColor(data, 8);

	switch(data.read_shift(1)) {
		/* case 0: out.scheme = "none": break; */
		case 1: out.scheme = "major"; break;
		case 2: out.scheme = "minor"; break;
	}

	out.name = parse_XLWideString(data, length - 21);

	return out;
}
869545
@Override
  public void validate(byte[] blockBuffer, int rowOffset, int rowHead, int blobTail)
  {
    int offset = rowOffset + offset();
    
    int blobLen = BitsUtil.readInt16(blockBuffer, offset + 2);
    int blobOffset = BitsUtil.readInt16(blockBuffer, offset);
    
    if (blobLen == 0) {
      return;
    }
    
    if (blobOffset < 0 || blobTail < blobOffset) {
      throw new IllegalStateException(L.l("{0}: corrupted blob offset {1} with blobTail={2}",
                                          this, blobOffset, blobTail));
    }
    
    if ((blobLen & LARGE_BLOB_MASK) != 0) {
      blobLen &= ~LARGE_BLOB_MASK;
      
      if (blobLen != 4) {
        throw new IllegalStateException(L.l("{0}: corrupted blob len {1} for large blob.",
                                            this, blobOffset));
      }
    }
    
    
    if (blobLen < 0 || blobTail < blobLen + blobOffset) {
      throw new IllegalStateException(L.l("{0}: corrupted blob len {1} with blobOffset={2} blobTail={3}",
                                          this, blobLen, blobOffset, blobTail));
    }
  }
713151
function parse_BrtWbProp(data, length) {
	var o = ({});
	var flags = data.read_shift(4);
	o.defaultThemeVersion = data.read_shift(4);
	var strName = (length > 8) ? parse_XLWideString(data) : "";
	if(strName.length > 0) o.CodeName = strName;
	o.autoCompressPictures = !!(flags & 0x10000);
	o.backupFile = !!(flags & 0x40);
	o.checkCompatibility = !!(flags & 0x1000);
	o.date1904 = !!(flags & 0x01);
	o.filterPrivacy = !!(flags & 0x08);
	o.hidePivotFieldList = !!(flags & 0x400);
	o.promptedSolutions = !!(flags & 0x10);
	o.publishItems = !!(flags & 0x800);
	o.refreshAllConnections = !!(flags & 0x40000);
	o.saveExternalLinkValues = !!(flags & 0x80);
	o.showBorderUnselectedTables = !!(flags & 0x04);
	o.showInkAnnotation = !!(flags & 0x20);
	o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
	o.showPivotChartFilter = !!(flags & 0x8000);
	o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
	return o;
}
1024295
function parse_MTRSettings(blob) {
	var fMTREnabled = blob.read_shift(4) !== 0x00;
	var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
	var cUserThreadCount = blob.read_shift(4);
	return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
}
80514
function parse_PtgAttrIfError(blob) {
	var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
	blob.l += 2;
	return [bitIf, blob.read_shift(2)];
}
541808
public int getNbRead() throws DevFailed {
		manageExceptions("getNbRead");
        int ySize = attributeValue_5.r_dim.dim_y;
		return attributeValue_5.r_dim.dim_x * DIM_MINI(ySize);
    }
681903
public void readerFromId(String bucketName, String blobName) throws IOException {
    // [START readerFromId]
    BlobId blobId = BlobId.of(bucketName, blobName);
    try (ReadChannel reader = storage.reader(blobId)) {
      ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
      while (reader.read(bytes) > 0) {
        bytes.flip();
        // do something with bytes
        bytes.clear();
      }
    }
    // [END readerFromId]
  }
240332
function (line) {
    /**
     * Background line : 0,0,"bg.jpg"
     * TODO: confirm that the second member is always zero
     *
     * Breaktimes lines : 2,1000,2000
     * second integer is start offset
     * third integer is end offset
     */
    members = line.split(',');

    if (members[0] == '0' && members[1] == '0' && members[2]) {
      var bgName = members[2].trim();

      if (bgName.charAt(0) == '"' && bgName.charAt(bgName.length - 1) == '"') {
        beatmap.bgFilename = bgName.substring(1, bgName.length - 1);
      } else {
        beatmap.bgFilename = bgName;
      }
    } else if (members[0] == '2' && /^[0-9]+$/.test(members[1]) && /^[0-9]+$/.test(members[2])) {
      beatmap.breakTimes.push({
        startTime: parseInt(members[1]),
        endTime: parseInt(members[2])
      });
    }
  }
1119369
@Override
  int insertBlob(byte[] srcBuffer, int srcRowOffset,
                 byte[] dstBuffer, int dstRowOffset, int dstBlobTail)
  {
    int srcColumnOffset = srcRowOffset + offset();
    int dstColumnOffset = dstRowOffset + offset();
    
    int blobLen = BitsUtil.readInt16(srcBuffer, srcColumnOffset + 2);

    if (blobLen == 0) {
      return dstBlobTail;
    }
    
    blobLen &= ~LARGE_BLOB_MASK;

    if (dstRowOffset < dstBlobTail + blobLen) {
      return -1;
    }

    int blobOffset = BitsUtil.readInt16(srcBuffer, srcColumnOffset);

    try {
      System.arraycopy(srcBuffer, blobOffset, dstBuffer, dstBlobTail,
                       blobLen);
    } catch (ArrayIndexOutOfBoundsException e) {
      throw new ArrayIndexOutOfBoundsException("srcOff: " + blobOffset
                                               + " dstOff: " + dstBlobTail
                                               + " len: " + blobLen
                                               + " " + this);
    }

    BitsUtil.writeInt16(dstBuffer, dstColumnOffset, dstBlobTail);
    
    /*
    System.out.println("SET: " + Hex.toHex(dstBuffer, dstRowOffset, 5) 
                       + " " + Hex.toHex(dstBuffer, dstBlobTail, 4));
                       */
    
    return dstBlobTail + blobLen;
  }
898181
function(blob, length) {
	var end = blob.l + length;
	var sVer = blob.read_shift(4);
	if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
	var flags = blob.read_shift(2);
	blob.l += 2;
	var displayName, targetFrameName, moniker, oleMoniker, location, guid, fileTime;
	if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
	if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
	if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
	if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
	if(flags & 0x0008) location = parse_HyperlinkString(blob, end - blob.l);
	if(flags & 0x0020) guid = blob.read_shift(16);
	if(flags & 0x0040) fileTime = parse_FILETIME(blob, 8);
	blob.l = end;
	var target = (targetFrameName||moniker||oleMoniker);
	if(location) target+="#"+location;
	return {Target: target};
}