text:
//
// officegen: All the code to generate XLSX files.
//
// Please refer to README.md for this module's documentations.
//
// NOTE:
// - Before changing this code please refer to the hacking the code section on README.md.
//
// Copyright (c) 2013 Ziv Barber;
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

/**
 * Basicgen plugin to create xlsx files (Microsoft Excel).
 */

var baseobj = require("./basicgen.js");
var msdoc = require("./msofficegen.js");

var docplugman = require('./docplug');

// Officegen xlsx plugins:
// BMK_XLSX_PLUG:

if ( !String.prototype.encodeHTML ) {
	String.prototype.encodeHTML = function () {
		return this.replace(/&/g, '&')
			.replace(/</g, '<')
			.replace(/>/g, '>')
			.replace(/"/g, '"');
	};
}

/**
 * Extend officegen object with XLSX support.
 *
 * This method extending the given officegen object to create XLSX document.
 *
 * @param {object} genobj The object to extend.
 * @param {string} new_type The type of object to create.
 * @param {object} options The object's options.
 * @param {object} gen_private Access to the internals of this object.
 * @param {object} type_info Additional information about this type.
 * @constructor
 * @name makeXlsx
 */
function makeXlsx ( genobj, new_type, options, gen_private, type_info ) {
	/**
	 * Prepare the default data.
	 * @param {object} docpluginman Access to the document plugins manager.
	 */
	function setDefaultDocValues ( docpluginman ) {
		var pptxData = docpluginman.getDataStorage ();

		// Please put any setting that API can override here:
	}

	/**
	 * Create the shared string resource.
	 *
	 * This resource holding all the text strings of any Excel document.
	 *
	 * @param {object} data Ignored by this callback function.
	 * @return Text string.
	 */
	function cbMakeXlsSharedStrings ( data ) {
		var outString = gen_private.plugs.type.msoffice.cbMakeMsOfficeBasicXml ( data ) + '<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="' + genobj.generate_data.total_strings + '" uniqueCount="' + genobj.generate_data.shared_strings.length + '">';

		for ( var i = 0, total_size = genobj.generate_data.shared_strings.length; i < total_size; i++ ) {
			outString += '<si><t>' + genobj.generate_data.shared_strings[i].encodeHTML () + '</t></si>';
		} // Endif.

		return outString + '</sst>';
	}

	/**
	 * Prepare everything to generate XLSX files.
	 *
	 * This method working on all the Excel cells to find out information needed by the generator engine.
	 */
	function cbPrepareXlsxToGenerate () {
		genobj.generate_data = {};
		genobj.generate_data.shared_strings = [];
		genobj.lookup_strings = {};
		genobj.generate_data.total_strings = 0;
		genobj.generate_data.cell_strings = [];

		// Tell all the features (plugins) that we are about to generate a new document zip:
		gen_private.features.type.xlsx.emitEvent ( 'beforeGen', genobj );

		// Allow some plugins to do more stuff after all the plugins added their data:
		gen_private.features.type.xlsx.emitEvent ( 'beforeGenFinal', genobj );

		// Create the share strings data:
		for ( var i = 0, total_size = gen_private.pages.length; i < total_size; i++ ) {
			if ( gen_private.pages[i] ) {
				for ( var rowId = 0, total_size_y = gen_private.pages[i].sheet.data.length; rowId < total_size_y; rowId++ ) {
					if ( gen_private.pages[i].sheet.data[rowId] ) {
						for ( var columnId = 0, total_size_x = gen_private.pages[i].sheet.data[rowId].length; columnId < total_size_x; columnId++ ) {
							if ( typeof gen_private.pages[i].sheet.data[rowId][columnId] != 'undefined' ) {
								switch ( typeof gen_private.pages[i].sheet.data[rowId][columnId] ) {
									case 'string':
										genobj.generate_data.total_strings++;

										if ( !genobj.generate_data.cell_strings[i] ) {
											genobj.generate_data.cell_strings[i] = [];
										} // Endif.

										if ( !genobj.generate_data.cell_strings[i][rowId] ) {
											genobj.generate_data.cell_strings[i][rowId] = [];
										} // Endif.

										var shared_str = gen_private.pages[i].sheet.data[rowId][columnId];

										if (shared_str in genobj.lookup_strings) {
											genobj.generate_data.cell_strings[i][rowId][columnId] = genobj.lookup_strings[ shared_str ];

										} else {
											var shared_str_position = genobj.generate_data.shared_strings.length;
											genobj.generate_data.cell_strings[i][rowId][columnId] = shared_str_position;
											genobj.lookup_strings[ shared_str ] = shared_str_position;
											genobj.generate_data.shared_strings[shared_str_position] = shared_str;
										} // Endif.
										break;
								} // End of switch.
							} // Endif.
						} // End of for loop.
					} // Endif.
				} // End of for loop.
			} // Endif.
		} // End of for loop.

		if ( genobj.generate_data.total_strings ) {
			gen_private.plugs.intAddAnyResourceToParse ( 'xl\\sharedStrings.xml', 'buffer', null, cbMakeXlsSharedStrings, false );
			gen_private.type.msoffice.files_list.push (
				{
					name: '/xl/sharedStrings.xml',
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml',
					clear: 'generate'
				}
			);

			gen_private.type.msoffice.rels_app.push (
				{
					type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
					target: 'sharedStrings.xml',
					clear: 'generate'
				}
			);
		} // Endif.
	}

	/**
	 * ???.
	 *
	 * @param {object} data Ignored by this callback function.
	 * @return Text string.
	 */
	function cbMakeXlsStyles ( data ) {
		return gen_private.plugs.type.msoffice.cbMakeMsOfficeBasicXml ( data ) + '';
	}

	/**
	 * ???.
	 *
	 * @param {object} data Ignored by this callback function.
	 * @return Text string.
	 */
	function cbMakeXlsApp ( data ) {
		var pagesCount = gen_private.pages.length;
		var userName = genobj.options.author || genobj.options.creator || 'officegen';
		var outString = gen_private.plugs.type.msoffice.cbMakeMsOfficeBasicXml ( data ) + '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>' + pagesCount + '</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="' + pagesCount + '" baseType="lpstr">';

		for ( var i = 0, total_size = gen_private.pages.length; i < total_size; i++ ) {
			outString += '<vt:lpstr>Sheet' + (i + 1) + '</vt:lpstr>';
		} // End of for loop.

		outString += '</vt:vector></TitlesOfParts><Company>' + userName + '</Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>12.0000</AppVersion></Properties>';
		return outString;
	}

	/**
	 * ???.
	 *
	 * @param {object} data Ignored by this callback function.
	 * @return Text string.
	 */
	function cbMakeXlsWorkbook ( data ) {
		var outString = gen_private.plugs.type.msoffice.cbMakeMsOfficeBasicXml ( data ) + '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="xl" lastEdited="4" lowestEdited="4" rupBuild="4507"/><workbookPr defaultThemeVersion="124226"/><bookViews><workbookView xWindow="120" yWindow="75" windowWidth="19095" windowHeight="7485"/></bookViews><sheets>';

		for ( var i = 0, total_size = gen_private.pages.length; i < total_size; i++ ) {
			var sheetName = gen_private.pages[i].sheet.name || 'Sheet' + (i + 1);
                        var rId = gen_private.pages[i].relId;
			outString += '<sheet name="' + sheetName + '" sheetId="' + (i + 1) + '" r:id="rId' + rId + '"/>';
		} // End of for loop.

		outString += '</sheets><calcPr calcId="125725"/></workbook>';
		return outString;
	}

	/**
	 * Translate from the Excel displayed row name into index number.
	 *
	 * @param {string} cell_string Either the cell displayed position or the row displayed position.
	 * @param {boolean} ret_also_column ???.
	 * @return The cell's row Id.
	 */
	function cbCellToNumber ( cell_string, ret_also_column ) {
		var cellNumber = 0;
		var cellIndex = 0;
		var cellMax = cell_string.length;
		var rowId = 0;

		// Converted from C++ (from DuckWriteC++):
		while ( cellIndex < cellMax )
		{
			var curChar = cell_string.charCodeAt ( cellIndex );
			if ( (curChar >= 0x30) && (curChar <= 0x39) )
			{
				rowId = parseInt ( cell_string.slice ( cellIndex ), 10 );
				rowId = (rowId > 0) ? (rowId - 1) : 0;
				break;

			} else if ( (curChar >= 0x41) && (curChar <= 0x5A) )
			{
				if ( cellIndex > 0 )
				{
					cellNumber++;
					cellNumber *= (0x5B-0x41);
				} // Endif.

				cellNumber += (curChar - 0x41);

			} else if ( (curChar >= 0x61) && (curChar <= 0x7A) )
			{
				if ( cellIndex > 0 )
				{
					cellNumber++;
					cellNumber *= (0x5B-0x41);
				} // Endif.

				cellNumber += (curChar - 0x61);
			} // Endif.

			cellIndex++;
		} // End of while loop.

		if ( ret_also_column ) {
			return { row: rowId, column: cellNumber };
		} // Endif.

		return cellNumber;
	}

	/**
	 * ???.
	 *
	 * @param {object} cell_number ???.
	 * @return ???.
	 */
	function cbNumberToCell ( cell_number ) {
		var outCell = '';
		var curCell = cell_number;

		while ( curCell >= 0 )
		{
			outCell = String.fromCharCode ( (curCell % (0x5B-0x41)) + 0x41 ) + outCell;
			if ( curCell >= (0x5B-0x41) )
				curCell = Math.floor ( curCell / (0x5B-0x41) ) - 1;
			else
				break;
		} // End of while loop.

		return outCell;
	}

	/**
	 * ???.
	 *
	 * @param {object} data The main sheet object.
	 * @return Text string.
	 */
	function cbMakeXlsSheet ( data ) {
		var outString = gen_private.plugs.type.msoffice.cbMakeMsOfficeBasicXml ( data ) + '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">';
		var maxX = 0;
		var maxY = 0;
		var curColMax;
		var rowId;
		var columnId;
		var colsFound = 0;

		// Find the maximum cells area:
		maxY = data.sheet.data.length ? (data.sheet.data.length - 1) : 0;
		for ( rowId = 0, total_size_y = data.sheet.data.length; rowId < total_size_y; rowId++ ) {
			if ( data.sheet.data[rowId] ) {
				curColMax = data.sheet.data[rowId].length ? (data.sheet.data[rowId].length - 1) : 0;
				maxX = maxX < curColMax ? curColMax : maxX;
			} // Endif.
		} // End of for loop.

		outString += '<dimension ref="A1:' + cbNumberToCell ( maxX ) + '' + (maxY + 1) + '"/><sheetViews>';
		outString += '<sheetView tabSelected="1" workbookViewId="0"/>';
		// outString += '<selection activeCell="A1" sqref="A1"/>';
		outString += '</sheetViews><sheetFormatPr defaultRowHeight="15"/>';

		if ( data.sheet.width ) {
			data.sheet.width.forEach ( function ( value, indexId ) {
				if ( typeof value === 'object' ) {
					var outAttr = '';

					if ( typeof value.width === 'number' && value.width === value.width ) {
						outAttr = ' width="' + value.width + '" customWidth="1"';
					} // Endif.

					if ( typeof value.styleCode === 'number' && value.styleCode === value.styleCode ) {
						outAttr = ' style="' + value.styleCode + '"';
					} // Endif.

					if ( !colsFound ) {
						outString += '<cols>';
					} // Endif.

					outString += "<col min=\"" + (value.colId + 1) + "\" max=\"" + (value.colId + 1) + "\"" + outAttr + "/>";
					colsFound++;

				// Support for old code, not recommended:
				} else if ( typeof value === 'number' ) {
					if ( !colsFound ) {
						outString += '<cols>';
					} // Endif.

					outString += "<col min=\"" + (indexId + 1) + "\" max=\"" + (indexId + 1) + "\" width=\"" + value + "\" customWidth=\"1\"/>";
					colsFound++;
				} // Endif.
			});

			if ( colsFound ) {
				outString += '</cols>';
			} // Endif.
		} // Endif.

		outString += '<sheetData>';

		for ( rowId = 0, total_size_y = data.sheet.data.length; rowId < total_size_y; rowId++ ) {
			if ( data.sheet.data[rowId] ) {
				// Patch by arnesten <notifications@github.com>: Automatically support line breaks if used in cell + calculates row height:
                var rowLines = 1;
                data.sheet.data[rowId].forEach(function (cellData) {
                    if (typeof cellData === 'string') {
                        var candidate = cellData.split('\n').length;
                        rowLines = Math.max(rowLines, candidate);
                    }
                });
				outString += '<row r="' + (rowId + 1) + '" spans="1:' + (data.sheet.data[rowId].length) + '" ht="' + ( rowLines * 15 ) + '">';
				// End of patch.

				for ( columnId = 0, total_size_x = data.sheet.data[rowId].length; columnId < total_size_x; columnId++ ) {
                    var cellData = data.sheet.data[rowId][columnId];
                    if ( typeof  cellData != 'undefined' ) {
						var isString = '';
						var cellOutData = '0';

						switch ( typeof cellData ) {
							case 'number':
								cellOutData = cellData;
								break;

							case 'string':
								cellOutData = genobj.generate_data.cell_strings[data.id][rowId][columnId];
                                if (cellData.indexOf('\n') >= 0) {
                                    isString = ' s="1" t="s"';
                                }
                                else {
                                    isString = ' t="s"';
                                }
								break;
						} // End of switch.

						outString += '<c r="' + cbNumberToCell ( columnId ) + '' + (rowId + 1) + '"' + isString + '><v>' + cellOutData + '</v></c>';
					} // Endif.
				} // End of for loop.

				outString += '</row>';
			} // Endif.
		} // End of for loop.

		outString += '</sheetData><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/></worksheet>';
		return outString;
	}

	// Prepare genobj for MS-Office:
	msdoc.makemsdoc ( genobj, new_type, options, gen_private, type_info );
	gen_private.plugs.type.msoffice.makeOfficeGenerator ( 'xl', 'workbook', {} );

	gen_private.features.page_name = 'sheets'; // This document type must have pages.

	// On each generate we'll prepare the shared strings list:
	genobj.on ( 'beforeGen', cbPrepareXlsxToGenerate );

	// Create the plugins manager:
	var plugsmanObj = new docplugman ( genobj, gen_private, 'xlsx', setDefaultDocValues );

	// We'll register now any officegen internal plugin that we want to always use for Excel based documents:
	// BMK_XLSX_PLUG:

	// Dynamic loading of additional plugins requested by the user:
	if ( options.extraPlugs && typeof options.extraPlugs === 'object' && options.extraPlugs.forEach ) {
		options.extraPlugs.forEach ( function ( value ) {
			var newPlug;

			if ( value ) {
				if ( typeof value === 'function' ) {
					// You already loaded the plugin:
					newPlug = value;

				} else if ( typeof value === 'string' ) {
					// We need to load the plugin:
					newPlug = require ( './' + value );
				} // Endif.
			} // Endif.

			plugsmanObj.plugsList.push ( new newPlug ( plugsmanObj ) );
		});
	} // Endif.

	gen_private.type.msoffice.files_list.push (
		{
			name: '/xl/styles.xml',
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml',
			clear: 'type'
		},
		{
			name: '/xl/workbook.xml',
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml',
			clear: 'type'
		}
	);

	gen_private.type.msoffice.rels_app.push (
		{
			type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
			target: 'styles.xml',
			clear: 'type'
		},
		{
			type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
			target: 'theme/theme1.xml',
			clear: 'type'
		}
	);

	gen_private.plugs.intAddAnyResourceToParse ( 'docProps\\app.xml', 'buffer', null, cbMakeXlsApp, true );
	gen_private.plugs.intAddAnyResourceToParse ( 'xl\\styles.xml', 'buffer', null, cbMakeXlsStyles, true );
	gen_private.plugs.intAddAnyResourceToParse ( 'xl\\workbook.xml', 'buffer', null, cbMakeXlsWorkbook, true );

	gen_private.plugs.intAddAnyResourceToParse ( 'xl\\_rels\\workbook.xml.rels', 'buffer', gen_private.type.msoffice.rels_app, gen_private.plugs.type.msoffice.cbMakeRels, true );

	// ----- API for Excel documents: -----

	/**
	 * Create a new sheet.
	 *
	 * This method creating a new Excel sheet.
	 */
	genobj.makeNewSheet = function () {
		var pageNumber = gen_private.pages.length;

		// The sheet object that the user will use:
		var sheetObj = {
			data: [], // Place here all the data.
			width: []
		};

		gen_private.pages[pageNumber] = {};
		gen_private.pages[pageNumber].id = pageNumber;
		gen_private.pages[pageNumber].relId = gen_private.type.msoffice.rels_app.length + 1;
		gen_private.pages[pageNumber].sheet = sheetObj;

		gen_private.type.msoffice.rels_app.push (
			{
				type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
				target: 'worksheets/sheet' + (pageNumber + 1) + '.xml',
				clear: 'data'
			}
		);

		gen_private.type.msoffice.files_list.push (
			{
				name: '/xl/worksheets/sheet' + (pageNumber + 1) + '.xml',
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml',
				clear: 'data'
			}
		);

		sheetObj.setColumnWidth = function ( colId, width ) {
			var colRec = null;

			colId = cbCellToNumber ( colId + '1', false );

			sheetObj.width.every ( function ( value ) {
				if ( value.colId === colId ) {
					colRec = value;
					return false;
				} // Endif.

				return true;
			});

			if ( !colRec ) {
				sheetObj.width.push ({
					colId: colId,
					width: width
				});
				return;
			} // Endif.

			colRec.width = width;
		};

		sheetObj.setColumnCenter = function ( colId ) {
			var colRec = null;

			colId = cbCellToNumber ( colId + '1', false );

			sheetObj.width.every ( function ( value ) {
				if ( value.colId === colId ) {
					colRec = value;
					return false;
				} // Endif.

				return true;
			});

			if ( !colRec ) {
				sheetObj.width.push ({
					colId: colId,
					width: 9.140625,
					styleCode: 1
				});
				return;
			} // Endif.

			colRec.styleCode = 1;
		};

		sheetObj.setCell = function ( position, data_val ) {
			var rel_pos = cbCellToNumber ( position, true );

			if ( !sheetObj.data[rel_pos.row] ) {
				sheetObj.data[rel_pos.row] = [];
			} // Endif.

			sheetObj.data[rel_pos.row][rel_pos.column] = data_val;
		};

		gen_private.plugs.intAddAnyResourceToParse ( 'xl\\worksheets\\sheet' + (pageNumber + 1) + '.xml', 'buffer', gen_private.pages[pageNumber], cbMakeXlsSheet, false );

		// Signal to the plugins about a new sheet:
		gen_private.features.type.xlsx.emitEvent ( 'newPage', { genobj: genobj, page: sheetObj, pageData: gen_private.pages[pageNumber], pageNumber: pageNumber } );

		return sheetObj;
	};

	// Tell all the features (plugins) to add extra API:
	gen_private.features.type.xlsx.emitEvent ( 'makeDocApi', genobj );

	return this;
}

baseobj.plugins.registerDocType ( 'xlsx', makeXlsx, {}, baseobj.docType.SPREADSHEET, "Microsoft Excel Document" );


text:
import sys
from hashlib import md5
from datetime import datetime
import pyme.core, pyme.constants.sig
import yaml

def getPassphrase(hint, desc, prev_bad):
  #print "Passphrase Callback! %s %s %s" % (hint, desc, prev_bad)
  #sys.stdout.write("Enter passphrase: ")
  #return sys.stdin.readline().strip()
  return "123456"

c = pyme.core.Context()
c.set_armor(1)
c.set_passphrase_cb(getPassphrase)

topic = {}
topic['type']='topic'
topic['path']='58BD0CCEB421BFB9BE694135F66EA1A3025BA2BF/lunch/2009-07-16/place'
topic['title']='Where?'
topic['short']='Where should we go for lunch on Thursday, 2009-07-16?'
topic['text']=None
topic['expired']=str(datetime(2009,7,16,13,59))
topic['author']='futterbot'

blob = pyme.core.Data(yaml.dump(topic))

#print ("Fetching authority key")
c.op_keylist_start('Authority', 0)
r = c.op_keylist_next()
#print(r)

if not r:
  print ("No such key found.")
  sys.exit(1)

#print ("Exporting key")
key = pyme.core.Data()
c.op_export('Authority', 0, key)

#print ("Signing data with key %s." % str(r))
sig = pyme.core.Data()
c.signers_add(r)
#print ("So far, so good.")
c.op_sign(blob, sig, pyme.constants.sig.mode.CLEAR)

data = {}
sig.seek(0,0)
data['sig'] = sig.read()
#key.seek(0,0)
#data['key'] = key.read()

print(yaml.dump(data))

redpajama_set_name: RedPajamaGithub


text:
var assert = require("assert");
include('ringo/encoding');
include('binary');
include('io');

var str = "I \u2665 JS";
var bytes = new ByteString([73,32,226,153,165,32,74,83]);

exports.testEncoder = function() {
    var enc = new Encoder("utf-8");
    enc.encode(str).encode(str);
    assert.strictEqual(str + str, enc.toByteString().decodeToString("utf-8"));
    enc.encode(str);
    assert.strictEqual(str + str + str, enc.toByteString().decodeToString("utf-8"));
    enc.clear().encode(str);
    assert.strictEqual(str, enc.toByteString().decodeToString("utf-8"));
};

exports.testSmallEncoder = function() {
    var enc = new Encoder("utf-8", false, 2);
    enc.encode(str).encode(str);
    assert.strictEqual(str + str, enc.toByteString().decodeToString("utf-8"));
    enc.encode(str);
    assert.strictEqual(str + str + str, enc.toByteString().decodeToString("utf-8"));
    enc.clear().encode(str);
    assert.strictEqual(str, enc.toByteString().decodeToString("utf-8"));
};

exports.testStreamEncoder = function() {
    var enc = new Encoder("utf-8");
    var stream = new MemoryStream();
    enc.writeTo(stream);
    enc.encode(str).encode(str);
    assert.strictEqual(enc.length, 0);
    assert.strictEqual(str + str, stream.content.decodeToString("utf-8"));
    enc.encode(str);
    assert.strictEqual(enc.length, 0);
    assert.strictEqual(str + str + str, stream.content.decodeToString("utf-8"));
    enc.clear().encode(str);
    assert.strictEqual(enc.length, 0);
    assert.strictEqual(str + str + str + str, stream.content.decodeToString("utf-8"));
};

exports.testDecoder = function() {
    var dec = new Decoder("utf-8");
    dec.decode(bytes).decode(bytes);
    assert.strictEqual(str + str, dec.toString());
    dec.decode(bytes);
    assert.strictEqual(str + str + str, dec.toString());
    dec.clear().decode(bytes);
    assert.strictEqual(str, dec.toString());
};

exports.testDecoderSmall = function() {
    var dec = new Decoder("utf-8", false, 2);
    dec.decode(bytes).decode(bytes);
    assert.strictEqual(str + str, dec.toString());
    dec.decode(bytes);
    assert.strictEqual(str + str + str, dec.toString());
    dec.clear().decode(bytes);
    assert.strictEqual(str, dec.toString());
};

exports.testStreamDecoder = function() {
    var dec = new Decoder("utf-8");
    var stream = new MemoryStream();
    stream.write(bytes.concat(bytes).concat(bytes));
    stream.position = 0;
    dec.readFrom(stream);
    assert.strictEqual(str + str + str, dec.read());
    assert.strictEqual(null, dec.read());
    assert.strictEqual(0, dec.length);
};

exports.testStreamDecoderReadLine = function() {
    var dec = new Decoder("utf-8");
    var stream = new MemoryStream();
    new TextStream(stream, {charset: "utf-8"}).writeLine(str).writeLine(str).writeLine(str);
    stream.position = 0;
    dec.readFrom(stream);
    assert.strictEqual(str, dec.readLine());
    assert.strictEqual(str, dec.readLine());
    assert.strictEqual(str, dec.readLine());
    assert.strictEqual(null, dec.readLine());
    assert.strictEqual(0, dec.length);
};

exports.testStreamDecoderReadLineShort = function() {
    var line = "The quick brown fox jumps over the lazy dog";
    var dec = new Decoder("utf-8", false, 2);
    var stream = new MemoryStream();
    new TextStream(stream, {charset: "utf-8"}).writeLine(line).writeLine(line).writeLine(line);
    stream.position = 0;
    dec.readFrom(stream);
    assert.strictEqual(line, dec.readLine());
    assert.strictEqual(line, dec.readLine());
    assert.strictEqual(line, dec.readLine());
    assert.strictEqual(null, dec.readLine());
    assert.strictEqual(0, dec.length);
};


text:
package re.jcg.playmusicexporter.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import re.jcg.playmusicexporter.R;
import re.jcg.playmusicexporter.activities.SettingsActivity;
import re.jcg.playmusicexporter.settings.PlayMusicExporterPreferences;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the
 * design guidelines for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment {
    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private View mFragmentContainerView;

    private boolean mUserLearnedDrawer;

    private Button mButtonTypeAlbum;
    private Button mButtonTypeArtist;
    private Button mButtonTypePlaylist;
    private Button mButtonTypeRated;
    private Button mButtonSettings;

    public enum ViewType {
        Album, Artist, Playlist, Rated;

        public static ViewType fromName(String name) {
            for (ViewType type : values()) {
                if (type.name().equals(name)) return type;
            }
            return Album;
        }

    }

    private ViewType mViewType;

    /**
     * @return Gets the current view type
     */
    public ViewType getViewType() {
        return mViewType;
    }

    /**
     * @param viewType Sets the current view type
     */
    private void setViewType(ViewType viewType) {
        // Change the ui
        setButtonActive(mButtonTypeAlbum, viewType == ViewType.Album);
        setButtonActive(mButtonTypeArtist, viewType == ViewType.Artist);
        setButtonActive(mButtonTypePlaylist, viewType == ViewType.Playlist);
        setButtonActive(mButtonTypeRated, viewType == ViewType.Rated);

        // Callback the parent activity
        if (viewType != mViewType)
            if (mCallbacks != null) mCallbacks.onViewTypeChanged(viewType);

        mViewType = viewType;

        // Save the selection
        PlayMusicExporterPreferences.init(getContext());
        PlayMusicExporterPreferences.setDrawerViewType(viewType);

        // Close the drawer
        if (mDrawerLayout != null)
            mDrawerLayout.closeDrawers();
    }

    public NavigationDrawerFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the settings
        PlayMusicExporterPreferences.init(getContext());
        mUserLearnedDrawer = PlayMusicExporterPreferences.getDrawerLearned();
        mViewType = PlayMusicExporterPreferences.getDrawerViewType();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);

        // Gets all buttons
        mButtonTypeAlbum = (Button) view.findViewById(R.id.button_type_album);
        mButtonTypeArtist = (Button) view.findViewById(R.id.button_type_artist);
        mButtonTypePlaylist = (Button) view.findViewById(R.id.button_type_playlist);
        mButtonTypeRated = (Button) view.findViewById(R.id.button_type_rated);

        mButtonSettings = (Button) view.findViewById(R.id.button_setting);

        // Set the default
        setViewType(mViewType);

        // Click on album
        mButtonTypeAlbum.setOnClickListener(v -> setViewType(ViewType.Album));

        // Click on artist
        mButtonTypeArtist.setOnClickListener(v -> setViewType(ViewType.Artist));

        // Click on playlist
        mButtonTypePlaylist.setOnClickListener(v -> setViewType(ViewType.Playlist));

        // Click on rated
        mButtonTypeRated.setOnClickListener(v -> setViewType(ViewType.Rated));

        // Click on settings
        mButtonSettings.setOnClickListener(v -> {
            Intent intentSettings = new Intent(getActivity(), SettingsActivity.class);
            startActivity(intentSettings);

            // Close the drawer
            mDrawerLayout.closeDrawers();
        });

        // Color the settings button
        setButtonActive(mButtonSettings, false);

        return view;
    }

    /**
     * Format the button
     *
     * @param button The button
     * @param active Active
     */
    public void setButtonActive(Button button, boolean active) {
        int colorText;
        int colorBackground;

        // Button is active
        if (active) {
            // Gets the active color

            colorText = ContextCompat.getColor(getContext(), R.color.button_navigation_drawer_text_active);
            colorBackground = ContextCompat.getColor(getContext(), R.color.button_navigation_drawer_active);
        } else {
            // Gets the normal color
            colorText = ContextCompat.getColor(getContext(), R.color.button_navigation_drawer_text);
            colorBackground = ContextCompat.getColor(getContext(), R.color.button_navigation_drawer_normal);
        }

        // Sets the color
        button.setBackgroundColor(colorBackground);
        button.setTextColor(colorText);
        button.getCompoundDrawables()[0].setColorFilter(colorText, PorterDuff.Mode.MULTIPLY);
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    public void setOnListViewChanged(NavigationDrawerCallbacks callback) {
        mCallbacks = callback;
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    PlayMusicExporterPreferences.init(getContext());
                    PlayMusicExporterPreferences.setDrawerLearned(mUserLearnedDrawer);
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
        // per the navigation drawer design guidelines.
        if (!mUserLearnedDrawer) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(mDrawerToggle::syncState);

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallbacks = (NavigationDrawerCallbacks) context;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            //inflater.inflate(R.menu.global, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        /*if (item.getItemId() == R.id.action_example) {
            Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.
     */
    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

    private ActionBar getActionBar() {
        return ((AppCompatActivity) getActivity()).getSupportActionBar();
    }

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onViewTypeChanged(ViewType viewType);
    }
}


text:
**The pydarkstar package will not work unless you tell python where pydarkstar is located**.

We accomplish this by writing shell scripts that set an environment variable called PYTHONPATH to the absolute path of the pydarkstar root directory.

The process of setting the PYTHONPATH is not needed in the case that pydarkstar is in the current directory of an executing python interpreter.

#### Shell Scripts : Anaconda Environment

It is very important that the correct Python interpreter is used.  If you use Anaconda, you must activate the environment you want to use.  This can be done with the `conda activate command`.

To check what Python interpreter is being used, you can run `python --version`.

##### Linux

* Create the following text file.

```bash
#!/bin/bash
export PYTHONPATH=$PYTHONPATH:/path/to/pydarkstar
conda activate pydarkstar
python -m pydarkstar.apps.scrub.run $*
```

* Make the file executable.

```bash
bash:~$ chmod +x scrub.sh
```

* Run the app.

```bash
bash:~$ ./scrub.sh --help
```

##### Windows

* Create the following text file.
* Please note that spaces in directory names can cause issues to arise when quotes are not used.

```bat
@ECHO OFF
set PYTHONPATH="%PYTHONPATH%;C:\Path\To\pydarkstar"
conda activate pydarkstar
python3 -m pydarkstar.apps.scrub.run %*
```

#### Shell Scripts : Running Apps

**Please note that pydarkstar takes advantage of python's -m flag to run library modules as scripts**.  Python modules are just python files beneath the pydarkstar top level directory.  There is no other way to run the apps.

* This will work

```bash
bash:~$ cd /path/to/pydarkstar
bash:~$ conda activate pydarkstar
bash:~$ python3 -m pydarkstar.apps.scrub.run --help
```

* This will not work

```bash
bash:~$ cd /path/to/pydarkstar
bash:~$ conda activate pydarkstar
bash:~$ python3 ./pydarkstar/apps/scrub/run.py --help
```


text:
create table role (
    id int primary key auto_increment,
    name varchar(255) not null
);
create table role_permission (
    id int primary key auto_increment,
    role_id int not null,
    permission_id int not null
);
create table permission (
    id int primary key auto_increment,
    name varchar(255) not null
);


text:
package org.kuali.coeus.propdev.impl.s2s;

import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.coeus.propdev.api.s2s.S2sApplicationContract;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "S2S_APPLICATION")
public class S2sApplication extends KcPersistableBusinessObjectBase implements S2sApplicationContract {

    @Id
    @Column(name = "PROPOSAL_NUMBER")
    private String proposalNumber;

    @Column(name = "APPLICATION")
    @Lob
    private String application;

    @OneToMany(orphanRemoval = true, cascade = { CascadeType.ALL })
    @JoinColumn(name = "PROPOSAL_NUMBER", referencedColumnName = "PROPOSAL_NUMBER")
    private List<S2sAppAttachments> s2sAppAttachmentList;

    @Override
    public String getProposalNumber() {
        return proposalNumber;
    }

    public void setProposalNumber(String proposalNumber) {
        this.proposalNumber = proposalNumber;
    }

    @Override
    public String getApplication() {
        return application;
    }

    public void setApplication(String application) {
        this.application = application;
    }

    @Override
    public List<S2sAppAttachments> getS2sAppAttachmentList() {
        return s2sAppAttachmentList;
    }

    public void setS2sAppAttachmentList(List<S2sAppAttachments> s2sAppAttachmentList) {
        this.s2sAppAttachmentList = s2sAppAttachmentList;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <TITLE>
        LoopIterationEvent (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.engine.event.LoopIterationEvent class">

    <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

        org.apache.jmeter.engine.event

    Class LoopIterationEvent

java.lang.Object
  org.apache.jmeter.engine.event.LoopIterationEvent

public class LoopIterationEvent

extends Object

    An iteration event provides information about the iteration number and the
    source of the event.

            Constructor Summary

        LoopIterationEvent(TestElement source,
            int iter)

            Method Summary

             int
        getIteration()

                      Returns the iteration.

             TestElement
        getSource()

                      Returns the source.

        Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

            Constructor Detail

    LoopIterationEvent

public LoopIterationEvent(TestElement source,
                          int iter)

            Method Detail

    getIteration

public int getIteration()

Returns the iteration.

Returns:

int

    getSource

public TestElement getSource()

Returns the source.

Returns:

TestElement

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

Copyright © 1998-2009 Apache Software Foundation. All Rights Reserved.


text:
require "cases/helper"
require "active_model/type"

module ActiveModel
  module Type
    class DateTimeTest < ActiveModel::TestCase
      def test_type_cast_datetime_and_timestamp
        type = Type::DateTime.new
        assert_nil type.cast(nil)
        assert_nil type.cast("")
        assert_nil type.cast("  ")
        assert_nil type.cast("ABC")

        datetime_string = ::Time.now.utc.strftime("%FT%T")
        assert_equal datetime_string, type.cast(datetime_string).strftime("%FT%T")
      end

      def test_string_to_time_with_timezone
        ["UTC", "US/Eastern"].each do |zone|
          with_timezone_config default: zone do
            type = Type::DateTime.new
            assert_equal ::Time.utc(2013, 9, 4, 0, 0, 0), type.cast("Wed, 04 Sep 2013 03:00:00 EAT")
          end
        end
      end

      private

        def with_timezone_config(default:)
          old_zone_default = ::Time.zone_default
          ::Time.zone_default = ::Time.find_zone(default)
          yield
        ensure
          ::Time.zone_default = old_zone_default
        end
    end
  end
end


text:
module Uur
  module TablePrinting
    class TablesPrinter

      def initialize(tables, alignments, out=$stdout)
        @tables     = tables
        @alignments = alignments
        @out        = out
      end

      def print
        tables.each do |table|
          TablePrinter.new(table, widths, alignments, @out).print
          @out.puts
        end
      end

      private

      attr_reader :tables, :alignments

      def widths
        @widths ||= tables.flatten(1).transpose.map { |rows_in_column| rows_in_column.map(&:length).max }
      end
    end
  end
end


text:
#include <aws/mediaconvert/model/Timing.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MediaConvert
{
namespace Model
{

Timing::Timing() :
    m_finishTimeHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_submitTimeHasBeenSet(false)
{
}

Timing::Timing(JsonView jsonValue) :
    m_finishTimeHasBeenSet(false),
    m_startTimeHasBeenSet(false),
    m_submitTimeHasBeenSet(false)
{
  *this = jsonValue;
}

Timing& Timing::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("finishTime"))
  {
    m_finishTime = jsonValue.GetDouble("finishTime");

    m_finishTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("startTime"))
  {
    m_startTime = jsonValue.GetDouble("startTime");

    m_startTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("submitTime"))
  {
    m_submitTime = jsonValue.GetDouble("submitTime");

    m_submitTimeHasBeenSet = true;
  }

  return *this;
}

JsonValue Timing::Jsonize() const
{
  JsonValue payload;

  if(m_finishTimeHasBeenSet)
  {
   payload.WithDouble("finishTime", m_finishTime.SecondsWithMSPrecision());
  }

  if(m_startTimeHasBeenSet)
  {
   payload.WithDouble("startTime", m_startTime.SecondsWithMSPrecision());
  }

  if(m_submitTimeHasBeenSet)
  {
   payload.WithDouble("submitTime", m_submitTime.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace MediaConvert
} // namespace Aws


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.moonillusions.utils</groupId>
  <artifactId>PropertyNavigation</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>PropertyNavigation</name>
  <url>http://maven.apache.org</url>
  <build>
  <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
    </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
	<groupId>org.hamcrest</groupId>
	<artifactId>hamcrest-all</artifactId>
	<version>1.3</version>
	</dependency>
	<dependency>
	<groupId>cglib</groupId>
	<artifactId>cglib</artifactId>
	<version>3.1</version>
</dependency>
  </dependencies>
</project>


text:
package org.apache.camel.processor;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.saga.InMemorySagaService;

public class SagaFailuresTest extends ContextTestSupport {

    private AtomicInteger maxFailures;

    public void testCompensationAfterFailures() throws Exception {
        maxFailures = new AtomicInteger(2);

        MockEndpoint compensate = getMockEndpoint("mock:compensate");
        compensate.expectedMessageCount(1);

        sendBody("direct:saga-compensate", "hello");

        compensate.assertIsSatisfied();
    }

    public void testNoCompensationAfterMaxFailures() throws Exception {
        maxFailures = new AtomicInteger(3);

        MockEndpoint compensate = getMockEndpoint("mock:compensate");
        compensate.expectedMessageCount(1);
        compensate.setResultWaitTime(200);

        sendBody("direct:saga-compensate", "hello");

        compensate.assertIsNotSatisfied();
    }

    public void testCompletionAfterFailures() throws Exception {
        maxFailures = new AtomicInteger(2);

        MockEndpoint complete = getMockEndpoint("mock:complete");
        complete.expectedMessageCount(1);

        MockEndpoint end = getMockEndpoint("mock:end");
        end.expectedBodiesReceived("hello");

        sendBody("direct:saga-complete", "hello");

        complete.assertIsSatisfied();
        end.assertIsSatisfied();
    }

    public void testNoCompletionAfterMaxFailures() throws Exception {
        maxFailures = new AtomicInteger(3);

        MockEndpoint complete = getMockEndpoint("mock:complete");
        complete.expectedMessageCount(1);
        complete.setResultWaitTime(200);

        MockEndpoint end = getMockEndpoint("mock:end");
        end.expectedBodiesReceived("hello");

        sendBody("direct:saga-complete", "hello");

        complete.assertIsNotSatisfied();
        end.assertIsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                InMemorySagaService sagaService = new InMemorySagaService();
                sagaService.setMaxRetryAttempts(3);
                sagaService.setRetryDelayInMilliseconds(20);
                context.addService(sagaService);

                from("direct:saga-compensate")
                        .saga()
                        .compensation("direct:compensate")
                        .process(x -> {
                            throw new RuntimeException("fail");
                        });

                from("direct:saga-complete")
                        .saga()
                        .completion("direct:complete")
                        .to("mock:end");

                from("direct:compensate")
                        .process(x -> {
                            int current = maxFailures.decrementAndGet();
                            if (current >= 0) {
                                throw new RuntimeException("compensation failure");
                            }
                        })
                        .to("mock:compensate");

                from("direct:complete")
                        .process(x -> {
                            int current = maxFailures.decrementAndGet();
                            if (current >= 0) {
                                throw new RuntimeException("completion failure");
                            }
                        })
                        .to("mock:complete");

            }
        };
    }

}


text:
class CalibrationLaser : public CModule
{
public:
    void Initialize();
    void Update( CCommand& commandIn );
};


text:
package io.redlink.smarti.repositories;

import io.redlink.smarti.model.SmartiUser;
import org.bson.types.ObjectId;

import java.util.List;
import java.util.Map;

public interface UserRepositoryCustom {
    SmartiUser create(SmartiUser user);

    SmartiUser removeClient(String login, ObjectId id);

    SmartiUser addClient(String login, ObjectId id);

    List<SmartiUser> findAllWithFilter(String filter);

    SmartiUser updateProfile(String login, Map<String, String> profile);
}


text:
#ifndef _HOSTTABLE_H_
#define _HOSTTABLE_H_

#include "rpc_tcstp.h"
#include "threads.h"

#define CONNECTION_TYPE_TCP_PERSISTANT	1

struct host_table_entry {
	struct host_table_entry *next;
	TSS_HCONTEXT tspContext;
	TCS_CONTEXT_HANDLE tcsContext;
	BYTE *hostname;
	int type;
	int socket;
	struct tcsd_comm_data comm;
	MUTEX_DECLARE(lock);
};

struct host_table {
	struct host_table_entry *entries;
	MUTEX_DECLARE(lock);
};

struct host_table_entry *get_table_entry(TCS_CONTEXT_HANDLE);
void put_table_entry(struct host_table_entry *);
TSS_RESULT __tspi_add_table_entry(TSS_HCONTEXT, BYTE *, int, struct host_table_entry **);
void remove_table_entry(TCS_CONTEXT_HANDLE);

#endif


text:
package net.dv8tion.jda.api.entities;

import net.dv8tion.jda.internal.utils.EntityString;

import javax.annotation.Nonnull;
import java.util.Objects;

/**
 * Meta data for the vanity invite of a guild
 *
 * @since  4.2.1
 */
public class VanityInvite
{
    private final String code;
    private final int uses;

    public VanityInvite(@Nonnull String code, int uses)
    {
        this.code = code;
        this.uses = uses;
    }

    /**
     * The invite code used for the invite url.
     *
     * @return The code
     */
    @Nonnull
    public String getCode()
    {
        return code;
    }

    /**
     * How many times this invite has been used.
     * <br>This is reset after the invite is changed or removed.
     *
     * @return The invite uses
     */
    public int getUses()
    {
        return uses;
    }

    /**
     * The invite url.
     *
     * @return The invite url
     */
    @Nonnull
    public String getUrl()
    {
        return "https://discord.gg/" + getCode();
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (!(obj instanceof VanityInvite))
            return false;
        VanityInvite other = (VanityInvite) obj;
        return uses == other.uses && code.equals(other.code);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(code, uses);
    }

    @Override
    public String toString()
    {
        return new EntityString(this)
                .addMetadata("code", code)
                .toString();
    }
}


text:
self.addEventListener('connect', function(e) {
  var port = e.ports[0];
  port.start();
  port.postMessage('hullo there!');
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Documentation for the R package pwrcalc — pwrcalc 0.0.0.9000 documentation</title>

    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Introduction" href="intro.html" />

Navigation

          index

          next |

pwrcalc 0.0.0.9000 documentation »

Documentation for the R package pwrcalc¶

Contents:

Introduction

Why Power Analysis?

Why Another Power Analysis Package for R?

Installation

ghit

devtools

Manual installation

Reference

twomeans

clustered

Practical Examples

Two sample t-test

Two sample t-test with group clusters

Indices and tables¶

Index

Module Index

Search Page

Table Of Contents

Documentation for the R package pwrcalc

Indices and tables

Next topic

Introduction

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

pwrcalc 0.0.0.9000 documentation »

        © Copyright 2017.
      Created using Sphinx 1.5.6.


text:
(function () {
  'use strict';
  angular.module('yapp').factory('dataService', dataService);
  function dataService($http) {
    return {

      getdata: function () {
        console.log("in get service");
        return $http.get("https://reqres.in/api/users?page=1");
      },

      postdata: function () {
        console.log("in post service");
        var dataObj = {
          "email": "sydney@fife",
          "password": "pistol"
        };
        return $http.post("https://reqres.in/api/register", dataObj);
      },

      formPostData: function (dataObj) {
        console.log("in post service");
        console.log(dataObj);

        return $http.post("https://reqres.in/api/users", dataObj);
      }

    }
  }
}());


text:
<Group>
  <Identifier>hkk_127</Identifier>
  <Name>Stiching Cultuurgeschiedenis Boxtel-Meierij H. Verhees</Name>
  <Address>
    <Street>Händelstraat 27</Street>
    <Postcode>5283 KM</Postcode>
    <Place>Boxtel</Place>
    <Thumbnail>http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Flag_of_Boxtel.gif/200px-Flag_of_Boxtel.gif</Thumbnail>
  </Address>
  <Website/>
</Group>


text:
<?php

/**
 * Will clean various things
 *
 * @package Cleaner
 * @copyright (c) Cotonti Team
 * @license https://github.com/Cotonti/Cotonti/blob/master/License.txt
 */

defined('COT_CODE') or die('Wrong URL');


text:
require 'roar/representer'
require 'roar/json'
require 'roar/json/hal'

require 'slack-amber-alert/api/presenters/paginated_presenter'
require 'slack-amber-alert/api/presenters/status_presenter'
require 'slack-amber-alert/api/presenters/team_presenter'
require 'slack-amber-alert/api/presenters/teams_presenter'
require 'slack-amber-alert/api/presenters/missing_kid_presenter'
require 'slack-amber-alert/api/presenters/missing_kids_presenter'
require 'slack-amber-alert/api/presenters/root_presenter'


text:
<?xml version="1.0" encoding="UTF-8"?>
<shortcut>
	<attribute name="title" value="Reset password"/>
	<attribute name="title" lang="fr_FR" value="Réinitialisation du mot de passe"/>
	<attribute name="description" value="Reset my password"/>
	<attribute name="description" lang="fr_FR" value="Réinitialiser mon mot de passe"/>
	<attribute name="command" value="gnome-reset-password"/>
	<attribute name="icon" value="actions/keys"/>
	<attribute name="menu" value="system"/>
	<attribute name="category" value="administration"/>
	<attribute name="hidden" value="1"/>
</shortcut>


text:
class Browser;
namespace views {
class ImageView;
class MenuButton;
}

class ExtensionInfoBar : public InfoBarView,
                         public ExtensionInfoBarDelegate::DelegateObserver,
                         public views::MenuButtonListener {
 public:
  ExtensionInfoBar(Browser* browser,
                   InfoBarService* owner,
                   ExtensionInfoBarDelegate* delegate);

 private:
  virtual ~ExtensionInfoBar();

  // InfoBarView:
  virtual void Layout() OVERRIDE;
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child) OVERRIDE;
  virtual int ContentMinimumWidth() const OVERRIDE;

  // ExtensionInfoBarDelegate::DelegateObserver:
  virtual void OnDelegateDeleted() OVERRIDE;

  // views::MenuButtonListener:
  virtual void OnMenuButtonClicked(views::View* source,
                                   const gfx::Point& point) OVERRIDE;

  void OnImageLoaded(const gfx::Image& image);

  ExtensionInfoBarDelegate* GetDelegate();

  // TODO(pkasting): This shadows InfoBarView::delegate_.  Get rid of this once
  // InfoBars own their delegates (and thus we don't need the DelegateObserver
  // functionality).  For now, almost everyone should use GetDelegate() instead.
  InfoBarDelegate* delegate_;

  Browser* browser_;

  // The infobar icon used for the extension infobar. The icon can be either a
  // plain image (in which case |icon_as_image_| is set) or a dropdown menu (in
  // which case |icon_as_menu_| is set).
  // The icon is a dropdown menu if the extension showing the infobar shows
  // configure context menus.
  views::View* infobar_icon_;

  // The dropdown menu for accessing the contextual extension actions.
  // It is non-NULL if the |infobar_icon_| is a menu button and in that case
  // |icon_as_menu_ == infobar_icon_|.
  views::MenuButton* icon_as_menu_;

  // The image view for the icon.
  // It is non-NULL if |infobar_icon_| is an image and in that case
  // |icon_as_image_ == infobar_icon_|.
  views::ImageView* icon_as_image_;

  base::WeakPtrFactory<ExtensionInfoBar> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionInfoBar);
};

#endif  // CHROME_BROWSER_UI_VIEWS_INFOBARS_EXTENSION_INFOBAR_H_


text:
<!DOCTYPE html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="baidu-site-verification" content="wKG531ni5l" />
<meta name="google-site-verification" content="9KXTTa8tuuse9iILjkzFWzLNiBo3w3GtZtjUHQTf6C8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">

  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">

  <meta name="keywords" content="Hexo, NexT" />

<meta name="description" content="Keep hungry keep foolish!">
<meta property="og:type" content="website">
<meta property="og:title" content="liangtong">
<meta property="og:url" content="https://l900416.github.io/page/6/index.html">
<meta property="og:site_name" content="liangtong">
<meta property="og:description" content="Keep hungry keep foolish!">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="liangtong">
<meta name="twitter:description" content="Keep hungry keep foolish!">

  <link rel="canonical" href="https://l900416.github.io/page/6/"/>

  <title>liangtong</title>

        liangtong

    <button>

    </button>

            首页

            标签

            分类

            归档

            关于

            搜索

      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">

    <link itemprop="mainEntityOfPage" href="https://l900416.github.io/2017/08/07/share_github_blog_jekyll/">

      <meta itemprop="name" content="liangtong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">

      <meta itemprop="name" content="liangtong">

                Mac下使用Jekyll搭建GitHub博客

                发表于

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-07T16:25:19+08:00">
                2017-08-07
              </time>

              |

                分类于

                    技术分享

               |

                 阅读次数:

Jekyll是一个静态网站和博客模版,本文介绍如何使用Jekyll进行个人GitHub博客的搭建。搭建前提是拥有个人Github账号,且Mac上有安装 git 工具。

安装Jekyll

  参照Jekyll官方介绍,打开终端,通过以下命令安装:

1

$ gem install jekyll bundler

注:gem的安装/更新可以自己去查,此处不再进行说明。Jekyll安装成功后,便可以进行个人博客/静态网站的创建了。

快速使用博客

通过在终端输入以下命令执行初始化

1

2

3

$ jekyll new my_blog

$ cd my_blog

$ bundle exec jekyll serve

参照官方模版配置介绍,修改Jekyll配置文件_config.yml,如果没有特殊要求,建议直接GitHub找现成的博客模板即可。

              阅读全文 »

    <link itemprop="mainEntityOfPage" href="https://l900416.github.io/2017/08/04/share_github_blog_hexo/">

      <meta itemprop="name" content="liangtong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">

      <meta itemprop="name" content="liangtong">

                Mac下使用Hexo搭建GitHub博客

                发表于

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-04T14:25:19+08:00">
                2017-08-04
              </time>

              |

                分类于

                    技术分享

               |

                 阅读次数:

创建GitHub账号

  注册Github账号,建立个人博客仓库(Repository),不在赘述。

安装Git工具

  终端直接执行 git 命令,或者通过安装GitHub客户端。

安装Node和NPM

  打开终端,通过以下命令安装:

1

$ brew install node

安装Hexo

  可以参照Hexo在Github上的官方介绍,在终端依次执行以下命令进行:

$ npm install hexo-cli -g

  安装成功后,可以通过以下命令进行查看

$ hexo

              阅读全文 »

    <link itemprop="mainEntityOfPage" href="https://l900416.github.io/2017/07/27/bluetooth_central/">

      <meta itemprop="name" content="liangtong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">

      <meta itemprop="name" content="liangtong">

                iOS蓝牙开发 - Central模式

                发表于

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-27T19:50:12+08:00">
                2017-07-27
              </time>

              |

                分类于

                    蓝牙

               |

                 阅读次数:

Central模式

中心模式(Central Model),可以简单理解为设备App作为中心,连接其他蓝牙外设设备。区别于外设模式,官方介绍可自行Google。这里主要介绍iOS上蓝牙设备作为中心模式的集成。

功能集成

  作为蓝牙使用者,程序需要请求蓝牙设备授权,在info.plist配置文件中,添加代码:

1

2

3

</array>

<key>NSBluetoothPeripheralUsageDescription</key>

<string>蓝牙设备请求描述,比如:程序需要使用蓝牙进行设备发现</string>

  项目Targets对应的 BuildPhases 中,引入 CoreBluetooth.framework ,使用的代码中引入头文件

1

#import <CoreBluetooth/CoreBluetooth.h>

              阅读全文 »

    1…567…20

liangtong

Keep hungry keep foolish!

                  59
                  日志

                  7
                  分类

                  17
                  标签

                        GitHub

                        E-Mail

                        微博

                        知乎

                友情链接

                    lidm1989

© 2016 — 2018

  liangtong

由 Hexo 强力驱动

  |

主题 — NexT.Pisces v5.1.4

        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package Xref::Schema::Result::GeneTranscriptTranslation;

=head1 NAME

Xref::Schema::Result::GeneTranscriptTranslation

=cut

use strict;
use warnings;
use utf8;

use base 'DBIx::Class::Core';

=head1 TABLE: C<gene_transcript_translation>

=cut

__PACKAGE__->table("gene_transcript_translation");

=head1 ACCESSORS

=head2 gene_id

  data_type: 'integer'
  extra: {unsigned => 1}
  is_nullable: 0

=head2 transcript_id

  data_type: 'integer'
  extra: {unsigned => 1}
  is_nullable: 0

=head2 translation_id

  data_type: 'integer'
  extra: {unsigned => 1}
  is_nullable: 1

=cut

__PACKAGE__->add_columns(
  "gene_id",
  { data_type => "integer", extra => { unsigned => 1 }, is_nullable => 0 },
  "transcript_id",
  { data_type => "integer", extra => { unsigned => 1 }, is_nullable => 0 },
  "translation_id",
  { data_type => "integer", extra => { unsigned => 1 }, is_nullable => 1 },
);

=head1 PRIMARY KEY

=over 4

=item * L</transcript_id>

=back

=cut

__PACKAGE__->set_primary_key("transcript_id");

1;


text:
<?php
    require_once get_template_directory() . '/admin/install/index.php';
    require_once get_template_directory() . '/admin/templates/theme_settings.php';

?>


text:
import freetype as ft
import numpy as np

from ..gl_importer import gl as gl
from ..shader_program import Attribute, BufferDescription

__all__ = ['DisplayList']

class DisplayList:
    RECORD_TYPE = np.dtype([('vertex', '<f4', 2),
                            ('code', '<i4')])

    def __init__(self, font):
        self.font = font
        self.buffer, = gl.glGenBuffers(1)
        self.vertex_array, = font.shader_program.create_vertex_arrays(
            [BufferDescription(
                self.buffer,
                self.RECORD_TYPE,
                [Attribute('vertex', ['vertex'], is_vector=True),
                 Attribute('code', ['code'])])])
        self.array = None
        self.text = None
        self.characters = {}

    def delete(self):
        # Work around the fact that glGenBuffers returns a result that
        # glDeleteBuffers can't handle.
        gl.glDeleteBuffers(1, int(self.buffer))
        self.vertex_array.delete()

    def set_text(self, text):
        """
        Fill the buffer and vertex array.
        Possibly render additional glyphs into the texture.
        """
        if not isinstance(text, str):
            raise TypeError("text argument must be a string — not {}".format(
                type(text)))
        if (text == self.text
                and self.atlas_creation_id == self.font.atlas.creation_id):
            return
        self.text = text
        self.regenerate()

    def regenerate(self):
        face = self.font.face
        options = self.font.FT_OPTIONS

        self.atlas_creation_id = self.font.atlas.creation_id
        self.array = np.empty(len(self.text), self.RECORD_TYPE)
        vertex = np.zeros(2, dtype='f')
        last_char_index = 0

        for i, c in enumerate(self.text):
            this_vertex = self.array[i: i + 1]

            # Set code.
            this_vertex['code'] = self.font.get_char(c)

            # get_char might have caused creation_id to change.
            if self.atlas_creation_id != self.font.atlas.creation_id:
                self.regenerate()
                return

            # Set vertex.
            face.load_char(c, options)
            glyph = face.glyph

            this_char_index = face.get_char_index(c)
            assert this_char_index > 0

            kerning = face.get_kerning(last_char_index, this_char_index,
                                       ft.FT_KERNING_DEFAULT)

            advance = glyph.linearHoriAdvance / 65536
#           print("==========")
#           print(glyph.format)
#           print(c)
#           print("glyph", glyph.bitmap.rows)
#           for x in ['linearHoriAdvance', 'linearVertAdvance',
#                     'bitmap_left', 'bitmap_top']:
#               print(x, getattr(glyph, x))
#           print("glyph metrics")
#           for x in ['horiAdvance', 'horiBearingX', 'horiBearingY',
#                     'vertAdvance', 'vertBearingX', 'vertBearingY', 'width']:
#               print(x, getattr(glyph.metrics, x))
            bottom_left = np.array(
                (glyph.bitmap_left + kerning.x / 64,
                 -glyph.bitmap_top + glyph.bitmap.rows + kerning.y / 64),
                dtype='f')

            this_vertex['vertex'] = vertex + bottom_left
            vertex[0] += advance

            last_char_index = this_char_index

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER,
                        self.array.nbytes,
                        self.array,
                        gl.GL_STATIC_DRAW)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)

    def draw(self, widget_point):
        """
        Before drawing, be sure to set the uniforms:
        * projection
        * color
        * gamma
        * scale
        """
        if self.atlas_creation_id != self.font.atlas.creation_id:
            self.regenerate()
        with self.vertex_array.bind_context():
            self.font.shader_program.vertex_offset(widget_point)
            gl.glDrawArrays(gl.GL_POINTS, 0, len(self.text))


text:
extern "C"
{
#endif

#include "MriImageWriterPlugin.h"
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
    // Windows DLL export definition for the getPlugins() function
    #define DLLEXPORT __declspec(dllexport)
#else
    //A Linux placeholder library export definition to match Windows
    #define DLLEXPORT
#endif

//------------------------------------------------------------------------------
// Function prototypes and data
//------------------------------------------------------------------------------

// Saves an image file
MriImagePluginResult save(MriImageHandle ImageHandle, const char *pFileName, const char **ppMessageStringOut,
                          MriImageDataFormat Format, int NumMipMapLevels, int TileWidth, int TileHeight);
// Returns the image data formats supported by the plug-in
MriImageDataFormat *supportedImageFormats(const char *pExtension, int *pNumFormatsOut);
// Returns the file formats supported by the plug-in
MriFileFormatDesc *supportedFormats(int *pNumFormatsOut);

// Returns the list of plug-ins in this library
DLLEXPORT FnPlugin *getPlugins(unsigned int *pNumPlugins);
// Sets the host information for a plug-in
FnPluginStatus setImageWriterHost(const FnPluginHost *pHost);
// Returns the suite of functions provided by a plug-in
const void *getImageWriterSuite();
// Cleans up the plug-in
void flushImageWriterSuite();

//The host structure, which contains functions that the plug-in can call
MriImageWriterHostV1 s_Host;

// The plug-in structure, to provide to the host so it can call functions when needed
MriImageWriterPluginV1 s_PluginSuite =
{
    &save,
    &supportedImageFormats,
    &supportedFormats
};

#ifdef __cplusplus
}
#endif

#include <fstream>
using namespace std;

//OpenExr include
#include <half.h>

//OpenImageIO include
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/typedesc.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
OIIO_NAMESPACE_USING

//------------------------------------------------------------------------------
// Plug-in suite function definitions
//------------------------------------------------------------------------------

MriImagePluginResult save(MriImageHandle ImageHandle, const char *pFileName, const char **ppMessageStringOut,
                          MriImageDataFormat Format, int NumMipMapLevels, int TileWidth, int TileHeight)
{
    MriImagePluginResult Result;
    MriImageMipMapInfo MipMapInfo;
    int NumChannels, ChannelSize;
    int BufferSize, MipMapLevel, PixcelSize;
    int TileSizeX, TileSizeY, TileSize, TileX, TileY;
    int HashSize, Scanline, buf_y, buf_x;
    int Width, Height;
    unsigned char *pBuffer = NULL;
    unsigned char *pPtr = NULL;
    char *pHash = NULL;
    float pixel[4];
    half *pHalf;
    void *pVoid;
    MipMapLevel = 0;

    //todo:check if the channel is supported.
    //channel format.
    switch (Format)
    {
    case MRI_IDF_BYTE_RGB:
        NumChannels = 3;
        ChannelSize = 1;
        s_Host.trace("Channel format not supported: %d", Format);
        return MRI_IPR_FAILED;
        //break;

    case MRI_IDF_BYTE_RGBA:
        NumChannels = 4;
        ChannelSize = 1;
        s_Host.trace("Channel format not supported: %d", Format);
        return MRI_IPR_FAILED;
        //break;

    case MRI_IDF_HALF_RGB:
        NumChannels = 3;
        ChannelSize = 2;
        break;
        s_Host.trace("Channel format not supported: %d", Format);
        return MRI_IPR_FAILED;
        //break;

    //MRI_IDF_HALF_RGBA. this is the only channel type thats supported at the moment.
    case MRI_IDF_HALF_RGBA:
        NumChannels = 4;
        ChannelSize = 2;
        break;

    case MRI_IDF_FLOAT_RGB:
        NumChannels = 3;
        ChannelSize = 4;
        s_Host.trace("Channel format not supported: %d", Format);
        return MRI_IPR_FAILED;
        //break;

    case MRI_IDF_FLOAT_RGBA:
        NumChannels = 4;
        ChannelSize = 4;
        s_Host.trace("Channel format not supported: %d", Format);
        return MRI_IPR_FAILED;
        //break;

    default:
        s_Host.trace("Invalid format: %d", Format);
        return MRI_IPR_FAILED;
    }

    //bytes of one pixcel.
    PixcelSize = NumChannels * ChannelSize;
    //bytes of y row
    TileSizeY = TileHeight * PixcelSize;
    TileSizeX = TileWidth * PixcelSize;
    TileSize = TileWidth * TileSizeY;

    //for this we only care about level 0 since OpenImageIO takes care of the mipmap.
    for (; MipMapLevel  <= 0 ; ++MipMapLevel)
    {
        //getting info of current mipmap level.
        Result = s_Host.getMipMapInfo(ImageHandle, MipMapLevel, &MipMapInfo);
        if (MRI_IPR_SUCCEEDED != Result)
        {
            s_Host.trace("Failed: %d", Result);
            return Result;
        }

        //current level res
        Width = MipMapInfo.m_Width;
        Height = MipMapInfo.m_Height;

        //create oiio objects
        ImageSpec spec (Width, Height, NumChannels, TypeDesc::FLOAT);
        ImageBuf Input("mriExrWriterBuf", spec);

        // Allocate a buffer big enough to hold a complete set of tiles in the x axis.
        BufferSize = MipMapInfo.m_Width * TileSizeY;
        pBuffer = (unsigned char*)malloc(BufferSize);

        //s_Host.trace("Mip-map %d tile count: %dx%d", MipMapLevel, MipMapInfo.m_NumTilesX, MipMapInfo.m_NumTilesY);
        for (TileY = 0; TileY < MipMapInfo.m_NumTilesY; ++TileY)
        {
            //reset every new Y tile.
            pPtr = pBuffer;

            //for each Y row. loop through all x tiles.
            for (TileX = 0; TileX < MipMapInfo.m_NumTilesX; ++TileX)
            {
                Result = s_Host.getTileHashSize(ImageHandle, TileX, TileY, MipMapLevel, &HashSize);
                if (MRI_IPR_SUCCEEDED != Result)
                {
                    s_Host.trace("Failed: %d", Result);
                    free(pBuffer);
                    return Result;
                }

                pHash = (char*)malloc(HashSize);

                Result = s_Host.getTileHash(ImageHandle, TileX, TileY, MipMapLevel, pHash, HashSize);
                if (MRI_IPR_SUCCEEDED != Result)
                {
                    s_Host.trace("Failed: %d", Result);
                    free(pHash);
                    free(pBuffer);
                    return Result;
                }
                //looping through each x tile...
                //s_Host.trace("Filling in tile (%d, %d) - {%s}\n", TileX, TileY, pHash);
                free(pHash);

                //load the tile bites into the buffer.
                Result = s_Host.loadTile(ImageHandle, TileX, TileY, MipMapLevel, pPtr, TileSize);

                //pData   The address of a buffer that is at least DataSizeBytes long that will receive the image data from the tile
                if (MRI_IPR_SUCCEEDED != Result)
                {
                    s_Host.trace("Failed: %d", Result);
                    free(pBuffer);
                    return Result;
                }
                //move the pointer begining of the next tile.
                pPtr += TileSize;
            }
            // The whole row of X tiles loaded into buffer.

            // not for the example can just keeps writing. for our frame buffer we need to shift the base
            // for each y row.
            // write each scanline of the Y row into the file
            for (Scanline = 0; Scanline < TileHeight; ++Scanline)
            {
                //set cordinate for image buffer y scanline off set
                buf_y = (TileY*TileHeight)+Scanline;
                buf_x = 0;

                //set the pointer to the begining of each scanline and start writing.
                //push the pointer to the start of next scanline.
                pPtr = pBuffer + (Scanline * TileSizeX);

                //loop through the scanline of each X tiles
                for (TileX = 0; TileX < MipMapInfo.m_NumTilesX; ++TileX)
                {
                    //cast pointer to a half pointer
                    pVoid = pPtr;
                    pHalf = static_cast<half*>(pVoid);

                    //figureout how many bytes are in the tile scanline
                    //loop through the current scanline and grab the value as half
                    //TileSizeX( int bytes)/(sizeof(half)*numChannels)
                    for (int i=0; i < TileSizeX/(2*4); ++ i)
                    {
                        //todo: add in other channal type support.(for now only 16bit RGBA)
                        //for p<NumChannels. set valu for each channel on the pixcel.
                        for (int p=0; p<4; ++p)
                        {
                            pixel[p]=(float)*pHalf;
                            pHalf += 1;
                        }
                        //set pixcel on image buffer.
                        //todo: use image buffer iterator to get better performance.
                        Input.setpixel(buf_x,buf_y,pixel);
                        buf_x += 1;

                    }
                    //move pPtr to next tile
                    pPtr += TileSize;
                }
            }
        }
        free(pBuffer);

        //config for maketx
        ImageSpec config;
        config.attribute ("maketx:highlightcomp", 1);
        config.attribute ("maketx:filtername", "lanczos3");
        config.attribute ("maketx:opaquedetect", 1);

        //metadata
        config.attribute("show", getenv("SHOW"));
        config.attribute("shot", getenv("SHOT"));
        config.attribute("artist", getenv("USER"));

        //write image
        stringstream s; //s.str()
        bool success = ImageBufAlgo::make_texture (ImageBufAlgo::MakeTxTexture,Input, pFileName, config, &s);
        if (! success)
        {
            s_Host.trace("Fail to write image.");
            return MRI_IPR_FAILED;
        }

    }
    return MRI_IPR_SUCCEEDED;
}

//------------------------------------------------------------------------------
MriImageDataFormat *supportedImageFormats(const char *pExtension, int *pNumFormatsOut)
{
    return NULL;
}

//------------------------------------------------------------------------------
MriFileFormatDesc *supportedFormats(int *pNumFormatsOut)
{
    static MriFileFormatDesc s_Format = { "exr", "mipmap exr writer plug-in by chi-chang chu" };
    *pNumFormatsOut = 1;
    return &s_Format;
}

//------------------------------------------------------------------------------
// Plug-in interface functions
//------------------------------------------------------------------------------

const void *getImageWriterSuite()
{
    return &s_PluginSuite;
}

//------------------------------------------------------------------------------
void flushImageWriterSuite()
{
}

//------------------------------------------------------------------------------
FnPluginStatus setImageWriterHost(const FnPluginHost *pHost)
{
    const void *pHostSuite = NULL;

    if (NULL == pHost)
        return FnPluginStatusError;

    pHostSuite = pHost->getSuite(MRI_IMAGE_WRITER_API_NAME, MRI_IMAGE_WRITER_API_VERSION);
    if (NULL == pHostSuite)
        return FnPluginStatusError;

    s_Host = *(const MriImageWriterHostV1 *)pHostSuite;
    s_Host.trace("Connected to host '%s' version '%s' (%u)", pHost->name, pHost->versionStr, pHost->versionInt);
    return FnPluginStatusOK;
}

//------------------------------------------------------------------------------
DLLEXPORT FnPlugin *getPlugins(unsigned int *pNumPlugins)
{
    static FnPlugin s_Plugin;
    s_Plugin.name               = "ccMriMipMapExrWriter";
    s_Plugin.pluginVersionMajor = 1;
    s_Plugin.pluginVersionMinor = 0;
    s_Plugin.apiName            = MRI_IMAGE_WRITER_API_NAME;
    s_Plugin.apiVersion         = MRI_IMAGE_WRITER_API_VERSION;
    s_Plugin.setHost            = &setImageWriterHost;
    s_Plugin.getSuite           = &getImageWriterSuite;
    s_Plugin.flush              = &flushImageWriterSuite;

    *pNumPlugins = 1;
    return &s_Plugin;
}


text:
using System.Diagnostics.Contracts;
using System.IO;

namespace Code2Xml.Core.Serialization {
    public class TextSerializer : Serializer {
        private readonly TextWriter _writer;

        public TextSerializer(TextWriter writer) {
            Contract.Requires(writer != null);
            _writer = writer;
        }

        public override void Serialize(bool value) {
            _writer.Write(value ? '1' : '0');
        }

        public override void Serialize(int value) {
            _writer.Write(value);
            _writer.Write(',');
        }

        public override void Serialize(string text) {
            Serialize(text.Length);
            _writer.Write(text);
        }
    }
}


text:
namespace paddle {
namespace framework {
namespace details {

class ExceptionHolder {
 public:
  void Catch(std::exception_ptr eptr) {
    try {
      std::rethrow_exception(eptr);
    } catch (platform::EOFException exp) {
      Catch(exp);
    } catch (platform::EnforceNotMet exp) {
      Catch(exp);
    } catch (std::exception& ex) {
      LOG(FATAL) << "std::exception caught, " << ex.what();
    } catch (...) {
      LOG(FATAL) << "Unknown exception caught";
    }
  }

  bool IsCaught() const {
    std::lock_guard<std::mutex> lock(mu_);
    return exception_.get() != nullptr;
  }

  void ReThrow() {
    std::lock_guard<std::mutex> lock(mu_);
    switch (type_) {
      case kNone:
        break;
      case kEnforceNotMet: {
        auto e = *static_cast<platform::EnforceNotMet*>(exception_.get());
        throw e;
      }
      case kEOF: {
        auto e = *static_cast<platform::EOFException*>(exception_.get());
        throw e;
      }
    }
    ClearImpl();
  }

  void Clear() {
    std::lock_guard<std::mutex> lock(mu_);
    ClearImpl();
  }

  std::string Type() {
    std::lock_guard<std::mutex> lock(mu_);
    switch (type_) {
      case kNone:
        return "None";
      case kEnforceNotMet: {
        return "EnforceNotMet";
      }
      case kEOF: {
        return "EOF";
      }
    }
    return "unknown";
  }

 private:
  void ClearImpl() {
    exception_.reset();
    type_ = kNone;
  }

  void Catch(const platform::EnforceNotMet& exp) {
    std::lock_guard<std::mutex> lock(mu_);
    exception_.reset(new platform::EnforceNotMet(exp));
    type_ = kEnforceNotMet;
  }

  void Catch(const platform::EOFException& exp) {
    std::lock_guard<std::mutex> lock(mu_);
    // EOFException will not cover up existing EnforceNotMet.
    if (exception_.get() == nullptr) {
      exception_.reset(new platform::EOFException(exp));
      type_ = kEOF;
    }
  }

  enum ExceptionType { kNone, kEnforceNotMet, kEOF };
  ExceptionType type_{kNone};

  std::unique_ptr<std::exception> exception_;
  mutable std::mutex mu_;
};

}  // namespace details
}  // namespace framework
}  // namespace paddle


text:
package com.kpi.ip41m.pceshop.order;

import com.github.springtestdbunit.annotation.DatabaseOperation;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.kpi.ip41m.pceshop.PcEshopApplicationTests;
import com.kpi.ip41m.pceshop.dto.OrderDto;
import com.kpi.ip41m.pceshop.dto.OrderRowDto;
import com.kpi.ip41m.pceshop.dto.ShippingDto;
import com.kpi.ip41m.pceshop.entity.order.Payment;
import com.kpi.ip41m.pceshop.entity.product.Product;
import org.junit.Test;

import java.util.Arrays;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import static org.hamcrest.Matchers.*;

/**
 * Created by Dmytro on 23.12.2015.
 */
@DatabaseSetup(value = {"/data/customers.xml", "/data/products.xml", "/data/orders.xml"}, type = DatabaseOperation.CLEAN_INSERT)
@DatabaseTearDown(value = {"/data/customers.xml", "/data/products.xml", "/data/orders.xml"}, type = DatabaseOperation.DELETE_ALL)
public class OrderEndpointIT extends PcEshopApplicationTests{

    private final String ordersEndpointURL = "/orders/";

    private final String username = "test";

    @Test
    public void shouldReturnAllOrdersForUser() throws Exception {
        get(ordersEndpointURL + username)
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)));
    }

    @Test
    public void shouldSaveNewOrder() throws Exception {
        post(ordersEndpointURL, newOrder())
                .andExpect(status().isOk());

    }

    @Test
     public void shouldSaveProduct() throws Exception {
        get(ordersEndpointURL + "/1/remove").andExpect(status().isOk());
    }

    private OrderDto newOrder(){
        ShippingDto shippingDto = new ShippingDto();
        shippingDto.setCountry("USA");

        Payment payment = new Payment();
        payment.setDetails("Free for bosses");

        OrderRowDto orderRowDto = new OrderRowDto();
        orderRowDto.setProductId(2l);
        orderRowDto.setQuantity(3);

        OrderDto orderDto = new OrderDto();
        orderDto.setCustomerId("8");
        orderDto.setPayment(payment);
        orderDto.setShipping(shippingDto);
//        orderDto.setRows(Arrays.asList(orderRowDto));

        return orderDto;
    }
}


text:
package javaschool.app;

import asg.cliche.Command;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public abstract class Record {
    private static Integer count = 0;

    private final Integer id;
    private String name = null;
    //    private final Instant created = Instant.now();
//    private final LocalDateTime createdDateTime = LocalDateTime.ofInstant(this.created, ZoneId.systemDefault());

    private final ZonedDateTime created = ZonedDateTime.now();
//    private final DateTimeFormatter format = DateTimeFormatter.ofPattern("y.MM.dd HH:mm:ss");

    Record(String name) {
        this.id = ++Record.count;
        this.name = name;
    }

    Integer getId() {
        return id;
    }

    String getName() {
        return name;
    }

    @Command
    void setName(String name) {
        this.name = name;
    }

    public boolean contains(String criteria) {
        return this.getName().toLowerCase().contains(criteria);
    }

    @Override
    @Command(abbrev = "i", name = "info", description = "Print record\'s information")
    public String toString() {
        String result = String.format("Record #%d (%s) — '%s'", getId(), getType(), getName());
        result += String.format("\n     created: %s", created.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)));
        return result;
    }

    protected String getType() {
        return "record";
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  Class: NomadClient::Api::Evaluation

    — Documentation by YARD 0.9.5

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

    Index (E) »
    NomadClient » Api
     »
    Evaluation

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

Class: NomadClient::Api::Evaluation

Inherits:

      Path

Object

Path

NomadClient::Api::Evaluation

        show all

Defined in:

lib/nomad_client/api/evaluation.rb

Instance Attribute Summary

Attributes inherited from Path

#nomad_connection

      Instance Method Summary
      collapse

      #allocations(id)  ⇒ Faraday::Response

Query the allocations created or modified by an evaluation www.nomadproject.io/docs/http/eval.html.

      #get(id)  ⇒ Faraday::Response

Query a specific evaluation www.nomadproject.io/docs/http/eval.html.

Methods inherited from Path

#connection, #initialize

Constructor Details

This class inherits a constructor from NomadClient::Api::Path

Instance Method Details

    #allocations(id)  ⇒ <tt>Faraday::Response</tt>

Query the allocations created or modified by an evaluation www.nomadproject.io/docs/http/eval.html

Parameters:

        id

        (<tt>String</tt>)

        —

The ID of the evaluation according to Nomad

Returns:

        (<tt>Faraday::Response</tt>)

        —

A faraday response from Nomad

28
29
30
31
32

# File 'lib/nomad_client/api/evaluation.rb', line 28

def allocations(id)
  connection.get do |req|
    req.url "evaluation/#{id}/allocations"
  end
end

    #get(id)  ⇒ <tt>Faraday::Response</tt>

Query a specific evaluation www.nomadproject.io/docs/http/eval.html

Parameters:

        id

        (<tt>String</tt>)

        —

The ID of the evaluation according to Nomad

Returns:

        (<tt>Faraday::Response</tt>)

        —

A faraday response from Nomad

16
17
18
19
20

# File 'lib/nomad_client/api/evaluation.rb', line 16

def get(id)
  connection.get do |req|
    req.url "evaluation/#{id}"
  end
end

  Generated on Wed Dec 21 11:57:42 2016 by
  yard
  0.9.5 (ruby-2.2.3).


text:
package alien4cloud.topology.validation;

import alien4cloud.component.CSARRepositorySearchService;
import alien4cloud.exception.NotFoundException;
import alien4cloud.model.components.IndexedInheritableToscaElement;
import alien4cloud.model.components.IndexedRelationshipType;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.RelationshipTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.topology.task.TaskCode;
import alien4cloud.topology.task.TopologyTask;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.elasticsearch.common.collect.Lists;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Performs validation by checking that no relationships in a topology are abstract (and cannot be instanciated).
 */
@Component
public class TopologyAbstractRelationshipValidationService {
    @Resource
    private CSARRepositorySearchService csarRepoSearchService;

    /**
     * Checks that no relationships in a topology are abstract (and cannot be instanciated).
     *
     * @param topology The topology to validate.
     * @return A list tasks to be done to make this topology valid.
     */
    public List<TopologyTask> validateAbstractRelationships(Topology topology) {
        Map<String, IndexedRelationshipType[]> abstractIndexedRelationshipTypes = getIndexedRelationshipTypesFromTopology(topology, true);
        return getTaskListFromMapArray(abstractIndexedRelationshipTypes, TaskCode.IMPLEMENT);
    }

    /**
     * Get the relationships from a topology
     *
     * @param topology topology to be validated
     * @param abstractOnes if only abstract ones should be retrieved
     * @return a map containing node template id --> list of relationship type that this node references
     */
    private Map<String, IndexedRelationshipType[]> getIndexedRelationshipTypesFromTopology(Topology topology, Boolean abstractOnes) {
        Map<String, IndexedRelationshipType[]> indexedRelationshipTypesMap = Maps.newHashMap();
        if (topology.getNodeTemplates() == null) {
            return indexedRelationshipTypesMap;
        }
        for (Map.Entry<String, NodeTemplate> template : topology.getNodeTemplates().entrySet()) {
            if (template.getValue().getRelationships() == null) {
                continue;
            }

            Set<IndexedRelationshipType> indexedRelationshipTypes = Sets.newHashSet();
            for (RelationshipTemplate relTemplate : template.getValue().getRelationships().values()) {
                IndexedRelationshipType indexedRelationshipType = csarRepoSearchService.getElementInDependencies(IndexedRelationshipType.class,
                        relTemplate.getType(), topology.getDependencies());
                if (indexedRelationshipType != null) {
                    if (abstractOnes == null || abstractOnes.equals(indexedRelationshipType.isAbstract())) {
                        indexedRelationshipTypes.add(indexedRelationshipType);
                    }
                } else {
                    throw new NotFoundException("Relationship Type [" + relTemplate.getType() + "] cannot be found");
                }
            }
            if (indexedRelationshipTypes.size() > 0) {
                indexedRelationshipTypesMap.put(template.getKey(),
                        indexedRelationshipTypes.toArray(new IndexedRelationshipType[indexedRelationshipTypes.size()]));
            }

        }
        return indexedRelationshipTypesMap;
    }

    /**
     * Constructs a TopologyTask list given a Map (node template name => component) and the code
     */
    private <T extends IndexedInheritableToscaElement> List<TopologyTask> getTaskListFromMapArray(Map<String, T[]> components, TaskCode taskCode) {
        List<TopologyTask> taskList = Lists.newArrayList();
        for (Map.Entry<String, T[]> entry : components.entrySet()) {
            for (IndexedInheritableToscaElement compo : entry.getValue()) {
                TopologyTask task = new TopologyTask();
                task.setNodeTemplateName(entry.getKey());
                task.setComponent(compo);
                task.setCode(taskCode);
                taskList.add(task);
            }
        }
        if (taskList.isEmpty()) {
            return null;
        } else {
            return taskList;
        }
    }
}