text:
#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cstdio>
#include <cstring>
#include <algorithm>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax/SAXParseException.hpp>

#include <xalanc/Include/XalanVector.hpp>

#include <xalanc/XalanDOM/XalanDOMException.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/DOMStringPrintWriter.hpp>
#include <xalanc/PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <xalanc/PlatformSupport/XalanFileOutputStream.hpp>
#include <xalanc/PlatformSupport/XalanStdOutputStream.hpp>

#include <xalanc/Include/XalanAutoPtr.hpp>

#include <xalanc/DOMSupport/DOMSupportDefault.hpp>

#include <xalanc/XPath/XObjectFactoryDefault.hpp>
#include <xalanc/XPath/XPathEnvSupportDefault.hpp>
#include <xalanc/XPath/XPath.hpp>
#include <xalanc/XPath/XPathExecutionContextDefault.hpp>
#include <xalanc/XPath/XPathFactoryBlock.hpp>
#include <xalanc/XPath/XPathFactoryDefault.hpp>
#include <xalanc/XPath/XPathProcessorImpl.hpp>

#include <xalanc/XalanExtensions/XalanExtensions.hpp>

#include <xalanc/XalanEXSLT/XalanEXSLTCommon.hpp>
#include <xalanc/XalanEXSLT/XalanEXSLTMath.hpp>
#include <xalanc/XalanEXSLT/XalanEXSLTSet.hpp>
#include <xalanc/XalanEXSLT/XalanEXSLTString.hpp>

#include <xalanc/XercesParserLiaison/XercesParserLiaison.hpp>
#include <xalanc/XercesParserLiaison/XercesDOMSupport.hpp>

#include <xalanc/XMLSupport/FormatterToHTML.hpp>
#include <xalanc/XMLSupport/FormatterToNull.hpp>
#include <xalanc/XMLSupport/FormatterToText.hpp>
#include <xalanc/XMLSupport/FormatterToXML.hpp>
#include <xalanc/XMLSupport/FormatterTreeWalker.hpp>

#include <xalanc/XercesParserLiaison/FormatterToXercesDOM.hpp>

#include <xalanc/XalanSourceTree/FormatterToSourceTree.hpp>
#include <xalanc/XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <xalanc/XalanSourceTree/XalanSourceTreeDocument.hpp>
#include <xalanc/XalanSourceTree/XalanSourceTreeInit.hpp>
#include <xalanc/XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <xalanc/XSLT/XSLTEngineImpl.hpp>
#include <xalanc/XSLT/XSLTInit.hpp>
#include <xalanc/XSLT/XSLTInputSource.hpp>
#include <xalanc/XSLT/XSLTResultTarget.hpp>
#include <xalanc/XSLT/StylesheetRoot.hpp>
#include <xalanc/XSLT/StylesheetConstructionContextDefault.hpp>
#include <xalanc/XSLT/StylesheetExecutionContextDefault.hpp>
#include <xalanc/XSLT/TraceListenerDefault.hpp>
#include <xalanc/XSLT/XSLTProcessorEnvSupportDefault.hpp>

//#define XALAN_USE_ICU
#if defined(XALAN_USE_ICU)
#include <xalanc/ICUBridge/ICUBridgeCollationCompareFunctor.hpp>
#include <xalanc/ICUBridge/ICUBridgeCleanup.hpp>
#endif

//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif

XALAN_USING_STD(cerr)
XALAN_USING_STD(cin)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
XALAN_USING_STD(hex)
XALAN_USING_STD(pair)
XALAN_USING_STD(vector)

/**
 * Print argument options.
 */
void
printArgOptions()
{
	cerr << endl
		 << "TestXSLT options: "
		 << endl
		 << endl
		 << "Options are case-sensitive."
		 << endl
		 << endl
		 << " [-? Shows this message.]"
		 << endl
		 << endl
		 << " [-h Shows this message.]"
		 << endl
		 << endl
		 << " [-in <source URL> (If not specified, stdin is used.)]"
		 << endl
		 << endl
		 << " [-xsl <stylesheet URL>]"
		 << endl
		 << " [-out <output file>]"
		 << endl
		 << " [-v  Show version information only.]"
		 << endl
		 << " [-qc  Quiet pattern conflicts warnings.]"
		 << endl
		 << " [-q  Use quiet mode.]"
		 << endl
		 << " [-indent n  Controls how many spaces to indent. (default is 0)]"
		 << endl
		 << " [-validate  Controls whether validation occurs. Validation is off by default.]"
		 << endl
		 << endl
		 << " [-tt  Trace the templates as they are being called.]"
		 << endl
		 << " [-tg  Trace each generation event.]"
		 << endl
		 << " [-ts  Trace each selection event.]"
		 << endl
		 << " [-ttc  Trace the template children as they are being processed.]"
		 << endl
		 << endl
		 << " [-xml  Use XML formatter.]"
		 << endl
		 << " [-text  Use Text formatter.]"
		 << endl
		 << " [-html  Use HTML formatter.]"
		 << endl
		 << " [-dom  Use DOM formatter.  Generates a DOM instance, then formats XML for output.]"
		 << endl
		 << " [-xst  Use source tree formatter.  Generates an instance of the default source tree, then formats XML for output.]"
		 << endl
		 << endl
		 << " [-param name expression  Sets a stylesheet parameter.]"
		 << endl
		 << endl
		 << " [-xd  Use Xerces DOM instead of Xalan source tree.]"
		 << endl
		 << endl
		 << " [-de  Disable built-in extension functions.]"
		 << endl
		 << "The following option is valid only with -html."
		 << endl
		 << endl
		 << " [-noindent  Turns off HTML indenting."
		 << endl
		 << endl
		 << "The following option is valid only with -xml."
		 << endl
		 << endl
		 << " [-nh  Don't generate the XML declaration.]"
		 << endl;
}

// We only need a few things from the Xerces namespace...
XALAN_USING_XERCES(XMLPlatformUtils)
XALAN_USING_XERCES(SAXParseException)
XALAN_USING_XERCES(SAXException)
XALAN_USING_XERCES(XMLException)

// We need lots of things from the Xalan namespace, so hoist everything...
XALAN_CPP_NAMESPACE_USE

typedef vector<pair< const char*, const char*> >	StringPairVectorType;

struct CmdLineParams
{
	StringPairVectorType	params;

	bool		setQuietConflictWarnings;
	bool		setQuietMode;
	bool		versionOnly;
	bool		traceTemplates;
	bool		traceGenerationEvent;
	bool		traceSelectionEvent;
	bool		traceTemplateChildren;
	bool		shouldWriteXMLHeader;
	bool		doValidation;
	bool		noIndent;
	bool		formatToNull;
	bool		formatToSourceTree;
	bool		useDOM;
	bool		disableExtensions;

	int			indentAmount;
	int			outputType;

	const char*		outFileName;
	const char*		xslFileName;
	const char*		inFileName;

	CmdLineParams() :
		params(),
		setQuietConflictWarnings(false),
		setQuietMode(false),
		versionOnly(false),
		traceTemplates(false),
		traceGenerationEvent(false),
		traceSelectionEvent(false),
		traceTemplateChildren(false),
		shouldWriteXMLHeader(true),
		doValidation(false),
		noIndent(false),
		formatToNull(false),
		formatToSourceTree(false),
		useDOM(false),
		disableExtensions(false),
		indentAmount(-1),
		outputType(-1),
		outFileName(0),
		xslFileName(0),
		inFileName(0)
	{
	}
};

void
warnPreviousOutputMethod(int	outputMethod)
{
	cerr << endl << "Warning: Ignoring previous output method switch ";

	switch(outputMethod)
	{
	case FormatterListener::OUTPUT_METHOD_XML:
		cerr << "-XML.";
		break;

	case FormatterListener::OUTPUT_METHOD_TEXT:
		cerr << "-TEXT.";
		break;

	case FormatterListener::OUTPUT_METHOD_HTML:
		cerr << "-HTML.";
		break;

	case FormatterListener::OUTPUT_METHOD_DOM:
		cerr << "-DOM.";
		break;
	}

	cerr << endl << endl;
}

bool
getArgs(
			int				argc,
			char*			argv[],
			CmdLineParams&	p)
{
	bool fSuccess = true;

	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (!strcmp("-h", argv[i]) || !strcmp("-?", argv[i]))
		{
			fSuccess = false;
		}
		else if (!strcmp("-in", argv[i]))
		{
			++i;

			if(i < argc && argv[i][0] != '-')
			{
				p.inFileName = argv[i];
			}
			else
			{
				fSuccess = false;
			}
		}
		else if (!strcmp("-xsl", argv[i]))
		{
			++i;

			if(i < argc && argv[i][0] != '-')
			{
				p.xslFileName = argv[i];
			}
			else
			{
				fSuccess = false;
			}
		}
		else if (!strcmp("-out", argv[i]))
		{
			++i;

			if(i < argc && argv[i][0] != '-')
			{
				p.outFileName = argv[i];
			}
			else
			{
				fSuccess = false;
			}
		}
		else if (!strcmp("-noindent", argv[i]))
		{
			p.noIndent = true;
		}
		else if (!strcmp("-indent", argv[i]))
		{
			++i;

			if(i < argc && argv[i][0] != '-')
			{
#if defined(XALAN_STRICT_ANSI_HEADERS)
				p.indentAmount = std::atoi(argv[i]);
#else
				p.indentAmount = atoi(argv[i]);
#endif
			}
			else
			{
				fSuccess = false;
			}
		}
		else if(!strcmp("-validate", argv[i]))
		{
			p.doValidation = true;
		}
		else if (!strcmp("-param", argv[i]))
		{
			++i;

			if(i < argc && argv[i][0] != '-')
			{
				const char* const	name = argv[i];

				++i;

				// Don't check for '-' here, since that might
				// be a valid character in a parameter value.
				if(i < argc)
				{
					typedef StringPairVectorType::value_type	value_type;

					p.params.push_back(value_type(name, argv[i]));
				}
				else
				{
					fSuccess = false;
				}
			}
			else
			{
				fSuccess = false;
			}
		}
		else if(!strcmp("-v", argv[i]))
		{
			p.versionOnly = true;
		}
		else if(!strcmp("-qc", argv[i]))
		{
			p.setQuietConflictWarnings = true;
		}
		else if(!strcmp("-q", argv[i]))
		{
			p.setQuietMode = true;
		}
		else if(!strcmp("-xml", argv[i]))
		{
			if (p.outputType != -1)
			{
				warnPreviousOutputMethod(p.outputType);
			}

			p.outputType = FormatterListener::OUTPUT_METHOD_XML;
		}
		else if(!strcmp("-text", argv[i]))
		{
			if (p.outputType != -1)
			{
				warnPreviousOutputMethod(p.outputType);
			}

			p.outputType = FormatterListener::OUTPUT_METHOD_TEXT;
		}
		else if(!strcmp("-html", argv[i]))
		{
			if (p.outputType != -1)
			{
				warnPreviousOutputMethod(p.outputType);
			}

			p.outputType = FormatterListener::OUTPUT_METHOD_HTML;
		}
		else if(!strcmp("-dom", argv[i]))
		{
			if (p.outputType != -1)
			{
				warnPreviousOutputMethod(p.outputType);
			}

			p.outputType = FormatterListener::OUTPUT_METHOD_DOM;
		}
		else if(!strcmp("-xst", argv[i]))
		{
			if (p.outputType != -1)
			{
				warnPreviousOutputMethod(p.outputType);
			}

			p.outputType = FormatterListener::OUTPUT_METHOD_DOM;

			p.formatToSourceTree = true;
		}
		else if(!strcmp("-null", argv[i]))
		{
			p.formatToNull = true;
		}
		else if (!strcmp("-nh", argv[i]))
		{
			p.shouldWriteXMLHeader = false;
		}
		else if(!strcmp("-tt", argv[i]))
		{
			p.traceTemplates = true;
		}
		else if(!strcmp("-tg", argv[i]))
		{
			p.traceGenerationEvent = true;
		}
		else if(!strcmp("-ts", argv[i]))
		{
			p.traceSelectionEvent = true;
		}
		else if(!strcmp("-ttc", argv[i]))
		{
			p.traceTemplateChildren = true;
		}
		else if (!strcmp("-xd", argv[i]))
		{
			p.useDOM = true;
		}
		else if (!strcmp("-de", argv[i]))
		{
			p.disableExtensions = true;
		}
		else
		{
			cerr << endl << "Warning: Ignoring unknown option \"" << argv[i] << "\"." << endl << endl;
		}
	}

	return fSuccess;
}

FormatterListener*
createFormatter(
			int								outputType,
			bool							shouldWriteXMLHeader,
			bool							noIndent,
			bool							formatToNull,
			bool							formatToSourceTree,
			PrintWriter&					resultWriter,
			int								indentAmount,
			const XalanDOMString&			mimeEncoding,
			const StylesheetRoot*			stylesheet,
			XercesParserLiaison&		    parserLiaison,
			XalanSourceTreeParserLiaison&	sourceTreeParserLiaison,
			const PrefixResolver&			prefixResolver,
			const XalanDocument*&			theResultDocument)
{
    MemoryManagerType& theManager = XalanMemMgrs::getDefaultXercesMemMgr();

	FormatterListener*	formatter = 0;

	if (formatToNull == true)
	{
		formatter = new FormatterToNull;
	}
	else if(FormatterListener::OUTPUT_METHOD_XML == outputType)
	{
		XalanDOMString	version(theManager);
		bool			outputIndent = false;
		XalanDOMString	mediatype(theManager);
		XalanDOMString	doctypeSystem(theManager);
		XalanDOMString	doctypePublic(theManager);
		XalanDOMString	standalone(theManager);

		if (stylesheet != 0)
		{
			stylesheet->getOutputVersion(version);

			stylesheet->getOutputMediaType(mediatype);
			stylesheet->getOutputDoctypeSystem(doctypeSystem);
			stylesheet->getOutputDoctypePublic(doctypePublic);
			stylesheet->getOutputStandalone(standalone);
		}

		FormatterToXML* const	fToXML =
			new FormatterToXML(
					resultWriter,
					version,
					outputIndent,
					indentAmount,
					mimeEncoding,
					mediatype,
					doctypeSystem,
					doctypePublic,
					true,	// xmlDecl
					standalone,
                    FormatterToXML::OUTPUT_METHOD_XML,
                    true,
                    theManager);

		fToXML->setShouldWriteXMLHeader(shouldWriteXMLHeader);

		formatter = fToXML;
	}
	else if(FormatterListener::OUTPUT_METHOD_TEXT == outputType)
	{
		formatter = new FormatterToText(
                            resultWriter,
                            mimeEncoding,
                            true,
                            true,
                            theManager);
	}
	else if(FormatterListener::OUTPUT_METHOD_HTML == outputType)
	{
		XalanDOMString	version(theManager);
		bool			outputIndent = !noIndent;
		XalanDOMString	mediatype(theManager);
		XalanDOMString	doctypeSystem(theManager);
		XalanDOMString	doctypePublic(theManager);
		XalanDOMString	standalone(theManager);

		if (stylesheet != 0)
		{
			stylesheet->getOutputVersion(version);

			if (noIndent == false)
			{
				outputIndent = stylesheet->getOutputIndent();
			}

			 stylesheet->getOutputMediaType(mediatype);
			 stylesheet->getOutputDoctypeSystem(doctypeSystem);
			 stylesheet->getOutputDoctypePublic(doctypePublic);
			 stylesheet->getOutputStandalone(standalone);
		}

		FormatterToHTML* const	fToHTML =
				new FormatterToHTML(
						resultWriter,
						mimeEncoding,
						mediatype,
						doctypeSystem,
						doctypePublic,
						outputIndent,
						indentAmount,
                        true,
                        false,
                        theManager);

		fToHTML->setPrefixResolver(&prefixResolver);

		formatter = fToHTML;
	}
	else if(FormatterListener::OUTPUT_METHOD_DOM == outputType)
	{
		if (formatToSourceTree == true)
		{
			XalanSourceTreeDocument*	theDocument =
				sourceTreeParserLiaison.createXalanSourceTreeDocument();
			assert(theDocument != 0);

			theResultDocument = theDocument;

			FormatterToSourceTree* const	fToSourceTree =
				new FormatterToSourceTree(theManager, theDocument);

			fToSourceTree->setPrefixResolver(&prefixResolver);

			formatter = fToSourceTree;
		}
		else
		{
			DOMDocument_Type* const     theDocument =
				parserLiaison.createDOMFactory();
			assert(theDocument != 0);

			FormatterToXercesDOM* const     fToDOM =
				new FormatterToXercesDOM( theDocument, 0, theManager);

			fToDOM->setPrefixResolver(&prefixResolver);

			formatter = fToDOM;

            theResultDocument =
                parserLiaison.createDocument(
                    theDocument,
                    false,
                    false,
                    false);
		}
	}

	return formatter;
}

XalanOutputStream*
createOutputStream(MemoryManagerType& theManager , const CmdLineParams&		params)
{
	if (params.outFileName == 0)
	{
		return new XalanStdOutputStream(cout, theManager);
	}
	else
	{
        XalanDOMString buffer(theManager);

        TranscodeFromLocalCodePage(params.outFileName, buffer);

		return new XalanFileOutputStream(buffer, theManager);
	}
}

TraceListener*
createTraceListener(
            MemoryManagerType&      theManager ,
			const CmdLineParams&	params,
			PrintWriter&			diagnosticsWriter)
{
	if (params.traceTemplates == true ||
		params.traceTemplateChildren == true ||
		params.traceGenerationEvent == true ||
		params.traceSelectionEvent == true)
	{
		return new TraceListenerDefault(
				diagnosticsWriter,
				params.traceTemplates,
				params.traceTemplateChildren,
				params.traceGenerationEvent,
				params.traceSelectionEvent,
                theManager);
	}
	else
	{
		return 0;
	}

}

DOMSupport&
getDOMSupport(
		XalanSourceTreeDOMSupport&	theXalanSourceTreeDOMSupport,
		XercesDOMSupport&			theXercesDOMSupport,
		const CmdLineParams&		params)
{
	if (params.useDOM == false)
	{
		return theXalanSourceTreeDOMSupport;
	}
	else
	{
		return theXercesDOMSupport;
	}
}

XMLParserLiaison&
getParserLiaison(
		XalanSourceTreeParserLiaison&	theXalanSourceTreeParserLiaison,
		XercesParserLiaison&			theXercesParserLiaison,
		const CmdLineParams&			params)
{
	if (params.useDOM == false)
	{
		return theXalanSourceTreeParserLiaison;
	}
	else
	{
		return theXercesParserLiaison;
	}
}

int
xsltMain(const CmdLineParams&	params)
{
	// Initialize the XSLT subsystem.  This must stay in scope until
	// we're done with the subsystem, since its destructor shuts down
	// the subsystem.
    MemoryManagerType& theManager = XalanMemMgrs::getDefaultXercesMemMgr();

	XSLTInit	theInit(theManager);

	const XalanDOMString	mimeEncoding(XALAN_STATIC_UCODE_STRING("UTF-8"), theManager);
	const XalanDOMString	encoding(XALAN_STATIC_UCODE_STRING("UTF-8"), theManager);

	/**
	 * The default diagnostic writer...
	 */
	XalanStdOutputStream				theStdErr(cerr, theManager);
	XalanOutputStreamPrintWriter		diagnosticsWriter(theStdErr);

	// Make sure that error reporting, which includes any TraceListener output
	// does not throw exceptions when transcoding, since that could result in
	// an exception being thrown will another exception is active.  In particular,
	// characters that the TraceListener writes might not be representable in the
	// local code page.
	theStdErr.setThrowTranscodeException(false);

	// Initialize the XalanSourceTree subsystem.  This must stay in scope until
	// we're done with the subsystem, since its destructor shuts down the
	// subsystem.
	XalanSourceTreeInit				theXalanSourceTreeInit(theManager);

	XalanSourceTreeDOMSupport		theXalanSourceTreeDOMSupport;
	XalanSourceTreeParserLiaison	theXalanSourceTreeParserLiaison(theXalanSourceTreeDOMSupport, theManager);

	// Hookup the parser liaison instance to the support instance.
	theXalanSourceTreeDOMSupport.setParserLiaison( &theXalanSourceTreeParserLiaison);

	XercesDOMSupport		theXercesDOMSupport(theManager);
	XercesParserLiaison		theXercesParserLiaison(theManager);

	DOMSupport&				theDOMSupport = getDOMSupport(
		theXalanSourceTreeDOMSupport,
		theXercesDOMSupport,
		params);

	XMLParserLiaison&		xmlParserLiaison = getParserLiaison(
		theXalanSourceTreeParserLiaison,
		theXercesParserLiaison,
		params);

	XSLTProcessorEnvSupportDefault	theXSLProcessorSupport(theManager);

	if (params.disableExtensions == false)
	{
		XalanExtensionsInstaller::installGlobal(theManager);
		XalanEXSLTCommonFunctionsInstaller::installGlobal(theManager);
		XalanEXSLTMathFunctionsInstaller::installGlobal(theManager);
		XalanEXSLTSetFunctionsInstaller::installGlobal(theManager);
		XalanEXSLTStringFunctionsInstaller::installGlobal(theManager);
	}

	XObjectFactoryDefault	theXObjectFactory(theManager);

	XPathFactoryDefault		theXPathFactory(theManager);

	const XalanAutoPtr<TraceListener>		theTraceListener(
			createTraceListener(
                theManager,
				params,
				diagnosticsWriter));

	XSLTEngineImpl	processor(
            theManager,
			xmlParserLiaison,
			theXSLProcessorSupport,
			theDOMSupport,
			theXObjectFactory,
			theXPathFactory);

	theXSLProcessorSupport.setProcessor(&processor);

	if (theTraceListener.get() != 0)
	{
		processor.setTraceSelects(params.traceSelectionEvent);
		processor.addTraceListener(theTraceListener.get());
	}

	// Use a different factory type for the stylesheet.  This is an optimization, since
	// stylesheet XPath instances are built all at once and are deleted all at once when
	// the stylesheet is destroyed.
	XPathFactoryBlock	theStylesheetXPathFactory(theManager);

	StylesheetConstructionContextDefault	theConstructionContext(
            theManager,
			processor,
			theStylesheetXPathFactory);

	/*
	 * Set specified processor flags
	 */
	processor.setQuietConflictWarnings(params.setQuietConflictWarnings);

	if (params.params.empty() == false)
	{
		StringPairVectorType::const_iterator	it = params.params.begin();

		for ( ; it != params.params.end(); ++it)
		{
			assert((*it).first != 0 && (*it).second != 0);

			processor.setStylesheetParam(
					XalanDOMString((*it).first, theManager),
					XalanDOMString((*it).second, theManager));
		}
	}

	/*
	 * Set specified parser flags
	 */
	if (params.indentAmount != 0)
	{
		xmlParserLiaison.setIndent(params.indentAmount);
	}

	xmlParserLiaison.setUseValidation(params.doValidation);

	if (!params.setQuietMode)
	{
		processor.setDiagnosticsOutput(&diagnosticsWriter);
	}

	XalanDOMString	xslFileName(theManager);

	if(params.xslFileName != 0)
	{
		xslFileName = params.xslFileName;
	}

	const StylesheetRoot*	stylesheet = 0;

	if (!xslFileName.empty())
	{
		stylesheet = processor.processStylesheet(xslFileName, theConstructionContext);
	}

	XalanAutoPtr<XalanOutputStream>		outputFileStream(createOutputStream(theManager, params));
	assert(outputFileStream.get() != 0);

	XalanOutputStreamPrintWriter	resultWriter(*outputFileStream.get());

	const XalanDocument*	theResultDocument = 0;

	const XalanAutoPtr<FormatterListener>	formatter(
			createFormatter(
				params.outputType,
				params.shouldWriteXMLHeader,
				params.noIndent,
				params.formatToNull,
				params.formatToSourceTree,
				resultWriter,
				xmlParserLiaison.getIndent(),
				mimeEncoding,
				stylesheet,
				theXercesParserLiaison,
				theXalanSourceTreeParserLiaison,
				processor,
				theResultDocument));

	XSLTResultTarget	rTreeTarget(theManager);

	if(formatter.get() == 0)
	{
		rTreeTarget.setCharacterStream(&resultWriter);
	}
	else
	{
		rTreeTarget.setFormatterListener(formatter.get());
	}

	// Do the transformation...
	XSLTInputSource		theInputSource;

	if (params.inFileName != 0)
	{
		theInputSource.setSystemId(XalanDOMString(params.inFileName, theManager).c_str());
	}
	else
	{
		theInputSource.setStream(&cin);

		cerr << "Reading input document from stdin..." << endl;
	}

	StylesheetExecutionContextDefault	theExecutionContext(theManager, processor,
			theXSLProcessorSupport,
			theDOMSupport,
			theXObjectFactory);

#if defined(XALAN_USE_ICU)
	// Create a collation function for the ICU, and have it
	// cache collators...
	ICUBridgeCollationCompareFunctor	theICUFunctor(theManager, true);

	theExecutionContext.installCollationCompareFunctor(&theICUFunctor);
#endif

	if (params.useDOM == false)
	{
		theXalanSourceTreeParserLiaison.setExecutionContext(theExecutionContext);
	}
	else
	{
		theXercesParserLiaison.setExecutionContext(theExecutionContext);
	}

	if (stylesheet == 0)
	{
		// No stylesheet, so our only hope is that the xml file has
		// PI with the stylesheet...

		// Dummy input source...
		XSLTInputSource		theStylesheetSource;

		processor.process(
				theInputSource,
				theStylesheetSource,
				rTreeTarget,
				theConstructionContext,
				theExecutionContext);
	}
	else
	{
		theExecutionContext.setStylesheetRoot(stylesheet);

		processor.process(
				theInputSource,
				rTreeTarget,
				theExecutionContext);
	}

	if (params.outputType == FormatterListener::OUTPUT_METHOD_DOM)
	{
		// Output is to DOM, so we have to format to XML to
		// produce output...
		assert(rTreeTarget.getFormatterListener() != 0 &&
			   rTreeTarget.getFormatterListener()->getOutputFormat() ==
					FormatterListener::OUTPUT_METHOD_DOM);

		if (theResultDocument == 0)
		{
			cerr << endl << "Error: No document to format!!!" << endl;
		}
		else
		{
			// Create a FormaterToXML with the required output
			// options...
			const XalanAutoPtr<FormatterListener>	formatter(
					createFormatter(
						FormatterListener::OUTPUT_METHOD_XML,
						params.shouldWriteXMLHeader,
						params.noIndent,
						false,
						false,
						resultWriter,
						xmlParserLiaison.getIndent(),
						mimeEncoding,
						stylesheet,
						theXercesParserLiaison,
						theXalanSourceTreeParserLiaison,
						processor,
						theResultDocument));

			// Create a FormatterTreeWalker with the the
			// new formatter...
			FormatterTreeWalker theTreeWalker(*formatter.get(), theManager);

			// Walk the document and produce the XML...
			theTreeWalker.traverse(theResultDocument);
		}
	}

	theExecutionContext.reset();

	theConstructionContext.reset();
	theStylesheetXPathFactory.reset();

	processor.reset();

	theXPathFactory.reset();
	theXObjectFactory.reset();
	theXSLProcessorSupport.reset();
	theDOMSupport.reset();

	xmlParserLiaison.reset();

	if (params.disableExtensions == false)
	{
		XalanExtensionsInstaller::uninstallGlobal(theManager);
		XalanEXSLTCommonFunctionsInstaller::uninstallGlobal(theManager);
		XalanEXSLTMathFunctionsInstaller::uninstallGlobal(theManager);
		XalanEXSLTSetFunctionsInstaller::uninstallGlobal(theManager);
		XalanEXSLTStringFunctionsInstaller::uninstallGlobal(theManager);
	}

	return 0;
}

int
main(
			int		argc,
			char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

#if defined(XALAN_VQ_SPECIAL_TRACE)
	QuantifyStopRecordingData();
#endif

	int				theResult = 0;

	CmdLineParams	theParams;

	/*
	 *		Get command line arguments
	 */
	if (getArgs(argc, argv, theParams) == false)
	{
		printArgOptions();
	}
	else if (theParams.versionOnly == true)
	{
		cout << endl
			 << "Xalan version "
			 << XALAN_FULLVERSIONDOT
			 << endl
			 << "Xerces version "
			 << XERCES_FULLVERSIONDOT
			 << endl;
	}
	else
	{
		XMLPlatformUtils::Initialize();

		try
		{
			theResult = xsltMain(theParams);
		}
		catch (const XSLException&	e)
		{
			cout << "\nXSLException ";

			cout << "Type is: " << e.getType() << endl;

			cout << "Message is: " << e.getMessage() << " (";

			const XalanDOMString&	theURI = e.getURI();

			if (theURI.length() != 0)
			{
				cout << theURI;
			}
			else
			{
				cout << "Unknown URI";
			}

			cout << ", line "
				 << e.getLineNumber()
				 << ", column "
				 << e.getColumnNumber()
				 << ")"
				 << endl;

			theResult = -1;
		}
		catch (const SAXParseException&		e)
		{
			cout << "\nSAXParseException ";

			cout << "Message is: " << e.getMessage() << " (";

			const XMLCh* const	theSystemID = e.getSystemId();

			if (theSystemID != 0)
			{
				cout << theSystemID;
			}
			else
			{
				cout << "Unknown system ID";
			}

			cout << ", line "
				 << e.getLineNumber()
				 << ", column "
				 << e.getColumnNumber()
				 << ")"
				 << endl;

			theResult = -2;
		}
		catch (const SAXException&	e)
		{
			cout << "\nSAXException ";

			cout << "Message is: " << e.getMessage() << endl;

			theResult = -2;
		}
		catch (const XMLException&	e)
		{
			cout << "\nXMLException ";

			cout << "Type is: " << e.getType() << endl;

			cout << "Message is: " << e.getMessage() << endl;

			theResult = -3;
		}
		catch(const XalanDOMException&	e)
		{
			cout << endl
				 << "XalanDOMException caught.  The code is "
				 << int(e.getExceptionCode())
				 << "."
				 << endl;

			theResult = -4;
		}
		catch (...)
		{
			cout << "\nUnhandled Exception\n";

			theResult = -5;
		}

		XMLPlatformUtils::Terminate();
	}

#if defined(XALAN_USE_ICU)
    ICUBridgeCleanup::cleanup();
#endif

	return theResult;
}


text:
mkdir ~/.vim/plugged
mkdir ~/.vim/swap
git clone https://github.com/junegunn/vim-plug ~/.vim/plugged/vim-plug

redpajama_set_name: RedPajamaGithub


text:
namespace mojo {

// Issue

template <>
struct EnumTraits<media_router::mojom::Issue_ActionType,
                  media_router::IssueInfo::Action> {
  static media_router::mojom::Issue_ActionType ToMojom(
      media_router::IssueInfo::Action action) {
    switch (action) {
      case media_router::IssueInfo::Action::DISMISS:
        return media_router::mojom::Issue_ActionType::DISMISS;
      case media_router::IssueInfo::Action::LEARN_MORE:
        return media_router::mojom::Issue_ActionType::LEARN_MORE;
    }
    NOTREACHED() << "Unknown issue action type " << static_cast<int>(action);
    return media_router::mojom::Issue_ActionType::DISMISS;
  }

  static bool FromMojom(media_router::mojom::Issue_ActionType input,
                        media_router::IssueInfo::Action* output) {
    switch (input) {
      case media_router::mojom::Issue_ActionType::DISMISS:
        *output = media_router::IssueInfo::Action::DISMISS;
        return true;
      case media_router::mojom::Issue_ActionType::LEARN_MORE:
        *output = media_router::IssueInfo::Action::LEARN_MORE;
        return true;
    }
    return false;
  }
};

template <>
struct EnumTraits<media_router::mojom::Issue_Severity,
                  media_router::IssueInfo::Severity> {
  static media_router::mojom::Issue_Severity ToMojom(
      media_router::IssueInfo::Severity severity) {
    switch (severity) {
      case media_router::IssueInfo::Severity::FATAL:
        return media_router::mojom::Issue_Severity::FATAL;
      case media_router::IssueInfo::Severity::WARNING:
        return media_router::mojom::Issue_Severity::WARNING;
      case media_router::IssueInfo::Severity::NOTIFICATION:
        return media_router::mojom::Issue_Severity::NOTIFICATION;
    }
    NOTREACHED() << "Unknown issue severity " << static_cast<int>(severity);
    return media_router::mojom::Issue_Severity::WARNING;
  }

  static bool FromMojom(media_router::mojom::Issue_Severity input,
                        media_router::IssueInfo::Severity* output) {
    switch (input) {
      case media_router::mojom::Issue_Severity::FATAL:
        *output = media_router::IssueInfo::Severity::FATAL;
        return true;
      case media_router::mojom::Issue_Severity::WARNING:
        *output = media_router::IssueInfo::Severity::WARNING;
        return true;
      case media_router::mojom::Issue_Severity::NOTIFICATION:
        *output = media_router::IssueInfo::Severity::NOTIFICATION;
        return true;
    }
    return false;
  }
};

template <>
struct UnionTraits<media_router::mojom::MediaSinkExtraDataDataView,
                   media_router::MediaSinkInternal> {
  static media_router::mojom::MediaSinkExtraDataDataView::Tag GetTag(
      const media_router::MediaSinkInternal& sink);

  static bool IsNull(const media_router::MediaSinkInternal& sink) {
    return !sink.is_cast_sink() && !sink.is_dial_sink();
  }

  static void SetToNull(media_router::MediaSinkInternal* out) {}

  static const media_router::DialSinkExtraData& dial_media_sink(
      const media_router::MediaSinkInternal& sink) {
    return sink.dial_data();
  }

  static const media_router::CastSinkExtraData& cast_media_sink(
      const media_router::MediaSinkInternal& sink) {
    return sink.cast_data();
  }

  static bool Read(media_router::mojom::MediaSinkExtraDataDataView data,
                   media_router::MediaSinkInternal* out);
};

template <>
struct StructTraits<media_router::mojom::DialMediaSinkDataView,
                    media_router::DialSinkExtraData> {
  static const std::string& model_name(
      const media_router::DialSinkExtraData& extra_data) {
    return extra_data.model_name;
  }

  static const net::IPAddress& ip_address(
      const media_router::DialSinkExtraData& extra_data) {
    return extra_data.ip_address;
  }

  static const GURL& app_url(
      const media_router::DialSinkExtraData& extra_data) {
    return extra_data.app_url;
  }

  static bool Read(media_router::mojom::DialMediaSinkDataView data,
                   media_router::DialSinkExtraData* out);
};

template <>
struct StructTraits<media_router::mojom::CastMediaSinkDataView,
                    media_router::CastSinkExtraData> {
  static const std::string& model_name(
      const media_router::CastSinkExtraData& extra_data) {
    return extra_data.model_name;
  }

  static const net::IPEndPoint& ip_endpoint(
      const media_router::CastSinkExtraData& extra_data) {
    return extra_data.ip_endpoint;
  }

  static uint8_t capabilities(
      const media_router::CastSinkExtraData& extra_data) {
    return extra_data.capabilities;
  }

  static int32_t cast_channel_id(
      const media_router::CastSinkExtraData& extra_data) {
    return extra_data.cast_channel_id;
  }

  static bool Read(media_router::mojom::CastMediaSinkDataView data,
                   media_router::CastSinkExtraData* out);
};

template <>
struct StructTraits<media_router::mojom::IssueDataView,
                    media_router::IssueInfo> {
  static bool Read(media_router::mojom::IssueDataView data,
                   media_router::IssueInfo* out);

  static const std::string& route_id(const media_router::IssueInfo& issue) {
    return issue.route_id;
  }

  static const std::string& sink_id(const media_router::IssueInfo& issue) {
    return issue.sink_id;
  }

  static media_router::IssueInfo::Severity severity(
      const media_router::IssueInfo& issue) {
    return issue.severity;
  }

  static bool is_blocking(const media_router::IssueInfo& issue) {
    return issue.is_blocking;
  }

  static const std::string& title(const media_router::IssueInfo& issue) {
    return issue.title;
  }

  static const std::string& message(const media_router::IssueInfo& issue) {
    return issue.message;
  }

  static media_router::IssueInfo::Action default_action(
      const media_router::IssueInfo& issue) {
    return issue.default_action;
  }

  static const std::vector<media_router::IssueInfo::Action>& secondary_actions(
      const media_router::IssueInfo& issue) {
    return issue.secondary_actions;
  }

  static int32_t help_page_id(const media_router::IssueInfo& issue) {
    return issue.help_page_id;
  }
};

// MediaSink

template <>
struct EnumTraits<media_router::mojom::SinkIconType,
                  media_router::SinkIconType> {
  static media_router::mojom::SinkIconType ToMojom(
      media_router::SinkIconType icon_type) {
    switch (icon_type) {
      case media_router::SinkIconType::CAST:
        return media_router::mojom::SinkIconType::CAST;
      case media_router::SinkIconType::CAST_AUDIO_GROUP:
        return media_router::mojom::SinkIconType::CAST_AUDIO_GROUP;
      case media_router::SinkIconType::CAST_AUDIO:
        return media_router::mojom::SinkIconType::CAST_AUDIO;
      case media_router::SinkIconType::WIRED_DISPLAY:
        return media_router::mojom::SinkIconType::WIRED_DISPLAY;
      case media_router::SinkIconType::GENERIC:
        return media_router::mojom::SinkIconType::GENERIC;
      case media_router::SinkIconType::TOTAL_COUNT:
        break;
    }
    NOTREACHED() << "Unknown sink icon type " << static_cast<int>(icon_type);
    return media_router::mojom::SinkIconType::GENERIC;
  }

  static bool FromMojom(media_router::mojom::SinkIconType input,
                        media_router::SinkIconType* output) {
    switch (input) {
      case media_router::mojom::SinkIconType::CAST:
        *output = media_router::SinkIconType::CAST;
        return true;
      case media_router::mojom::SinkIconType::CAST_AUDIO_GROUP:
        *output = media_router::SinkIconType::CAST_AUDIO_GROUP;
        return true;
      case media_router::mojom::SinkIconType::CAST_AUDIO:
        *output = media_router::SinkIconType::CAST_AUDIO;
        return true;
      case media_router::mojom::SinkIconType::WIRED_DISPLAY:
        *output = media_router::SinkIconType::WIRED_DISPLAY;
        return true;
      case media_router::mojom::SinkIconType::GENERIC:
        *output = media_router::SinkIconType::GENERIC;
        return true;
    }
    return false;
  }
};

template <>
struct StructTraits<media_router::mojom::MediaSinkDataView,
                    media_router::MediaSinkInternal> {
  static bool Read(media_router::mojom::MediaSinkDataView data,
                   media_router::MediaSinkInternal* out);

  static const std::string& sink_id(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().id();
  }

  static const std::string& name(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().name();
  }

  static const absl::optional<std::string>& description(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().description();
  }

  static const absl::optional<std::string>& domain(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().domain();
  }

  static media_router::SinkIconType icon_type(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().icon_type();
  }

  static media_router::mojom::MediaRouteProviderId provider_id(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal.sink().provider_id();
  }

  static const media_router::MediaSinkInternal& extra_data(
      const media_router::MediaSinkInternal& sink_internal) {
    return sink_internal;
  }
};

// MediaRoute

template <>
struct EnumTraits<media_router::mojom::RouteControllerType,
                  media_router::RouteControllerType> {
  static media_router::mojom::RouteControllerType ToMojom(
      media_router::RouteControllerType controller_type) {
    switch (controller_type) {
      case media_router::RouteControllerType::kNone:
        return media_router::mojom::RouteControllerType::kNone;
      case media_router::RouteControllerType::kGeneric:
        return media_router::mojom::RouteControllerType::kGeneric;
      case media_router::RouteControllerType::kMirroring:
        return media_router::mojom::RouteControllerType::kMirroring;
    }
    NOTREACHED() << "Unknown controller type "
                 << static_cast<int>(controller_type);
    return media_router::mojom::RouteControllerType::kNone;
  }

  static bool FromMojom(media_router::mojom::RouteControllerType input,
                        media_router::RouteControllerType* output) {
    switch (input) {
      case media_router::mojom::RouteControllerType::kNone:
        *output = media_router::RouteControllerType::kNone;
        return true;
      case media_router::mojom::RouteControllerType::kGeneric:
        *output = media_router::RouteControllerType::kGeneric;
        return true;
      case media_router::mojom::RouteControllerType::kMirroring:
        *output = media_router::RouteControllerType::kMirroring;
        return true;
    }
    return false;
  }
};

template <>
struct StructTraits<media_router::mojom::MediaRouteDataView,
                    media_router::MediaRoute> {
  static bool Read(media_router::mojom::MediaRouteDataView data,
                   media_router::MediaRoute* out);

  static const std::string& media_route_id(
      const media_router::MediaRoute& route) {
    return route.media_route_id();
  }

  static const std::string& presentation_id(
      const media_router::MediaRoute& route) {
    return route.presentation_id();
  }

  static absl::optional<std::string> media_source(
      const media_router::MediaRoute& route) {
    // TODO(imcheng): If we ever convert from C++ to Mojo outside of unit tests,
    // it would be better to make the |media_source_| field on MediaRoute a
    // absl::optional<MediaSource::Id> instead so it can be returned directly
    // here.
    return route.media_source().id().empty()
               ? absl::optional<std::string>()
               : absl::make_optional(route.media_source().id());
  }

  static const std::string& media_sink_id(
      const media_router::MediaRoute& route) {
    return route.media_sink_id();
  }

  static const std::string& media_sink_name(
      const media_router::MediaRoute& route) {
    return route.media_sink_name();
  }

  static const std::string& description(const media_router::MediaRoute& route) {
    return route.description();
  }

  static bool is_local(const media_router::MediaRoute& route) {
    return route.is_local();
  }

  static media_router::RouteControllerType controller_type(
      const media_router::MediaRoute& route) {
    return route.controller_type();
  }

  static bool for_display(const media_router::MediaRoute& route) {
    return route.for_display();
  }

  static bool is_off_the_record(const media_router::MediaRoute& route) {
    return route.is_off_the_record();
  }

  static bool is_local_presentation(const media_router::MediaRoute& route) {
    return route.is_local_presentation();
  }

  static bool is_connecting(const media_router::MediaRoute& route) {
    return route.is_connecting();
  }
};

// RouteRequestResultCode

template <>
struct EnumTraits<media_router::mojom::RouteRequestResultCode,
                  media_router::RouteRequestResult::ResultCode> {
  static media_router::mojom::RouteRequestResultCode ToMojom(
      media_router::RouteRequestResult::ResultCode code) {
    switch (code) {
      case media_router::RouteRequestResult::UNKNOWN_ERROR:
        return media_router::mojom::RouteRequestResultCode::UNKNOWN_ERROR;
      case media_router::RouteRequestResult::OK:
        return media_router::mojom::RouteRequestResultCode::OK;
      case media_router::RouteRequestResult::TIMED_OUT:
        return media_router::mojom::RouteRequestResultCode::TIMED_OUT;
      case media_router::RouteRequestResult::ROUTE_NOT_FOUND:
        return media_router::mojom::RouteRequestResultCode::ROUTE_NOT_FOUND;
      case media_router::RouteRequestResult::SINK_NOT_FOUND:
        return media_router::mojom::RouteRequestResultCode::SINK_NOT_FOUND;
      case media_router::RouteRequestResult::INVALID_ORIGIN:
        return media_router::mojom::RouteRequestResultCode::INVALID_ORIGIN;
      case media_router::RouteRequestResult::OFF_THE_RECORD_MISMATCH:
        return media_router::mojom::RouteRequestResultCode::
            OFF_THE_RECORD_MISMATCH;
      case media_router::RouteRequestResult::NO_SUPPORTED_PROVIDER:
        return media_router::mojom::RouteRequestResultCode::
            NO_SUPPORTED_PROVIDER;
      case media_router::RouteRequestResult::CANCELLED:
        return media_router::mojom::RouteRequestResultCode::CANCELLED;
      case media_router::RouteRequestResult::ROUTE_ALREADY_EXISTS:
        return media_router::mojom::RouteRequestResultCode::
            ROUTE_ALREADY_EXISTS;
      case media_router::RouteRequestResult::DESKTOP_PICKER_FAILED:
        return media_router::mojom::RouteRequestResultCode::
            DESKTOP_PICKER_FAILED;
      case media_router::RouteRequestResult::ROUTE_ALREADY_TERMINATED:
        return media_router::mojom::RouteRequestResultCode::
            ROUTE_ALREADY_TERMINATED;
      default:
        NOTREACHED() << "Unknown RouteRequestResultCode "
                     << static_cast<int>(code);
        return media_router::mojom::RouteRequestResultCode::UNKNOWN_ERROR;
    }
  }

  static bool FromMojom(media_router::mojom::RouteRequestResultCode input,
                        media_router::RouteRequestResult::ResultCode* output) {
    switch (input) {
      case media_router::mojom::RouteRequestResultCode::UNKNOWN_ERROR:
        *output = media_router::RouteRequestResult::UNKNOWN_ERROR;
        return true;
      case media_router::mojom::RouteRequestResultCode::OK:
        *output = media_router::RouteRequestResult::OK;
        return true;
      case media_router::mojom::RouteRequestResultCode::TIMED_OUT:
        *output = media_router::RouteRequestResult::TIMED_OUT;
        return true;
      case media_router::mojom::RouteRequestResultCode::ROUTE_NOT_FOUND:
        *output = media_router::RouteRequestResult::ROUTE_NOT_FOUND;
        return true;
      case media_router::mojom::RouteRequestResultCode::SINK_NOT_FOUND:
        *output = media_router::RouteRequestResult::SINK_NOT_FOUND;
        return true;
      case media_router::mojom::RouteRequestResultCode::INVALID_ORIGIN:
        *output = media_router::RouteRequestResult::INVALID_ORIGIN;
        return true;
      case media_router::mojom::RouteRequestResultCode::OFF_THE_RECORD_MISMATCH:
        *output = media_router::RouteRequestResult::OFF_THE_RECORD_MISMATCH;
        return true;
      case media_router::mojom::RouteRequestResultCode::NO_SUPPORTED_PROVIDER:
        *output = media_router::RouteRequestResult::NO_SUPPORTED_PROVIDER;
        return true;
      case media_router::mojom::RouteRequestResultCode::CANCELLED:
        *output = media_router::RouteRequestResult::CANCELLED;
        return true;
      case media_router::mojom::RouteRequestResultCode::ROUTE_ALREADY_EXISTS:
        *output = media_router::RouteRequestResult::ROUTE_ALREADY_EXISTS;
        return true;
      case media_router::mojom::RouteRequestResultCode::DESKTOP_PICKER_FAILED:
        *output = media_router::RouteRequestResult::DESKTOP_PICKER_FAILED;
        return true;
      case media_router::mojom::RouteRequestResultCode::
          ROUTE_ALREADY_TERMINATED:
        *output = media_router::RouteRequestResult::ROUTE_ALREADY_TERMINATED;
        return true;
    }
    return false;
  }
};

}  // namespace mojo

#endif  // COMPONENTS_MEDIA_ROUTER_COMMON_MOJOM_MEDIA_ROUTER_MOJOM_TRAITS_H_


text:
require 'easypost'
class OrdersController < ApplicationController
  EasyPost.api_key = ENV['EASYPOST_SECRET']

  layout 'admin'
  before_action :authenticate_admin!

  def update

  end

  def destroy
    id_order = params[:id_order]
    id_product_cart = params[:id_product_cart]

    order_a = Order.find(id_order)
    if order_a
      if order_a.tag_link
        begin
          shipment = EasyPost::Shipment.retrieve(order_a.tag_link)
          shipment.refund
          order_a.shipping_tag_histories << ShippingTagHistory.create!(easy_post_id: shipment.id, order: order_a)
          order_a.tag_link = nil
          order_a.tracking_code = nil
          order_a.save!

          unless order_a.state.eql?('Shipped')
            OrdersController.refund(order_a, id_product_cart)
            if id_product_cart
              cart_a = order_a.cart
              product = cart_a.cart_products.find(id_product_cart)
              product.state = 'Cancelled'
              product.save!
            else
              order_a.state = 'Cancelled'
              order_a.save!
            end
          end
        rescue => e
          render json: {error: e}, status: :unauthorized
        end
      else
        unless order_a.state.eql?('Shipped')
          OrdersController.refund(order_a, id_product_cart)
          if id_product_cart
            cart_a = order_a.cart
            product = cart_a.cart_products.find(id_product_cart)
            product.state = 'Cancelled'
            product.save!
          else
            order_a.state = 'Cancelled'
            order_a.save!
          end
        end
      end
    end
  end

  def complete
    order = Order.find params[:id_order]
    order.confirmed = !order.confirmed
    order.save!
  end

  def cancel_shipment
    order = Order.find params[:order_id]
    shipment = EasyPost::Shipment.retrieve(order.tag_link)

    begin
      shipment.refund
      order.shipping_tag_histories << ShippingTagHistory.create!(easy_post_id: shipment.id, order: order)
      order.tag_link = nil
      order.tracking_code = nil
      order.save!
      render json: {message: 'successful'}, status: :ok
    rescue => e
      render json: {error: e}, status: :unauthorized
    end
  end

  def get_tag

    order = Order.find(params['order'])
    address = order.user_address
    user = order.overall_user

    begin
      from_address = EasyPost::Address.create(
          company: 'EasyPost',
          street1: '417 Montgomery Street',
          street2: '5th Floor',
          city: 'San Francisco',
          state: 'CA',
          zip: '94104',
          phone: '415-528-7555'
      )

      to_address = EasyPost::Address.create(
          name: "#{address.name} #{address.last_name}",
          street1: address.street_address,
          street2: '',
          city: address.city,
          state: address.state,
          zip: address.zip_code
      )

      parcel = EasyPost::Parcel.create(
          length: params['l'],
          width: params['w'],
          height: params['h'],
          weight: params['w_o']
      )

      shipment = EasyPost::Shipment.create(
          to_address: to_address,
          from_address: from_address,
          parcel: parcel
      )

      shipment.buy(
          rate: shipment.lowest_rate(carriers = ['USPS'], services = ['First'])
      )
      order.tag_link = shipment.id
      order.carrier = 'USPS'
      order.tracking_code = shipment.tracker.tracking_code
      order.save!

      TransactionalMailer.shipped_out(order).deliver_now

      render :json => {url: shipment.postage_label.label_url}.to_json
    rescue => e
        render :json => {error: e}.to_json, status: :unauthorized
    end

  end

  private

  def self.refund(order, item = nil)
    if item.nil?
      Stripe::Refund.create(:charge => order.charge_id)
    else
      amount = ApplicationHelper.product_price(item)[6]
      cart = order.cart

      promo = cart.promotion_codes.first
      gift = cart.gifts.first

      p promo, gift, cart

      if promo
        amount = amount - (amount * (promo.rate / 100))
      end

      if gift
        amount = amount - (amount * (gift.rate / 100))
      end

      p amount, '###############################', ApplicationHelper.product_price(item)

      Stripe::Refund.create(:charge => order.charge_id, :amount => HomeController.to_integer(100 * amount))
    end
  end

end


text:
/*
 * This file is generated by jOOQ.
*/
package top.zbeboy.isy.domain.tables.daos;

import java.util.List;

import javax.annotation.Generated;

import org.jooq.Configuration;
import org.jooq.impl.DAOImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import top.zbeboy.isy.domain.tables.UsersKey;
import top.zbeboy.isy.domain.tables.records.UsersKeyRecord;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.10.7"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
@Repository
public class UsersKeyDao extends DAOImpl<UsersKeyRecord, top.zbeboy.isy.domain.tables.pojos.UsersKey, String> {

    /**
     * Create a new UsersKeyDao without any configuration
     */
    public UsersKeyDao() {
        super(UsersKey.USERS_KEY, top.zbeboy.isy.domain.tables.pojos.UsersKey.class);
    }

    /**
     * Create a new UsersKeyDao with an attached configuration
     */
    @Autowired
    public UsersKeyDao(Configuration configuration) {
        super(UsersKey.USERS_KEY, top.zbeboy.isy.domain.tables.pojos.UsersKey.class, configuration);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected String getId(top.zbeboy.isy.domain.tables.pojos.UsersKey object) {
        return object.getUsername();
    }

    /**
     * Fetch records that have username IN (values)
     */
    public List<top.zbeboy.isy.domain.tables.pojos.UsersKey> fetchByUsername(String... values) {
        return fetch(UsersKey.USERS_KEY.USERNAME, values);
    }

    /**
     * Fetch a unique record that has username = value
     */
    public top.zbeboy.isy.domain.tables.pojos.UsersKey fetchOneByUsername(String value) {
        return fetchOne(UsersKey.USERS_KEY.USERNAME, value);
    }

    /**
     * Fetch records that have user_key IN (values)
     */
    public List<top.zbeboy.isy.domain.tables.pojos.UsersKey> fetchByUserKey(String... values) {
        return fetch(UsersKey.USERS_KEY.USER_KEY, values);
    }

    /**
     * Fetch a unique record that has user_key = value
     */
    public top.zbeboy.isy.domain.tables.pojos.UsersKey fetchOneByUserKey(String value) {
        return fetchOne(UsersKey.USERS_KEY.USER_KEY, value);
    }
}


text:
package ipv6addr

import (
	"context"

	"github.com/sacloud/libsacloud/v2/sacloud"
)

func (s *Service) Find(req *FindRequest) ([]*sacloud.IPv6Addr, error) {
	return s.FindWithContext(context.Background(), req)
}

func (s *Service) FindWithContext(ctx context.Context, req *FindRequest) ([]*sacloud.IPv6Addr, error) {
	if err := req.Validate(); err != nil {
		return nil, err
	}

	params, err := req.ToRequestParameter()
	if err != nil {
		return nil, err
	}

	client := sacloud.NewIPv6AddrOp(s.caller)
	found, err := client.Find(ctx, req.Zone, params)
	if err != nil {
		return nil, err
	}
	return found.IPv6Addrs, nil
}


text:
AST usage
====

I'd really prefer to build AST's for each language, then output a stringified
representation of that - rather than just build strings that happen to be valid syntax.

I don't expect the string approach to be weak or short-term (languages do not often get rewritten, with old syntax invalidated), but it feels very wrong to be writing literals with newlines, tabs, brackets and variable names baked-in.

Repetition
====

Every generator looks very similar, and all approach the same goal of writing out equivalent code in slightly different syntax. But every one is essentially copy-pasted and modified from the last (with the JS one being the common ancestor).

The only way to avoid this is abstraction - making each generator a type, then defining methods which return the appropriate string for a given type. Unfortunately that makes it _hard_ to read, because the amount of methods would be huge. Every language has _slightly_ different structure, from semicolons to tabs to names of errors to quoting strategies to string concatenation to varible naming. Everything is different, it feels like it'd be _more_ confusing to abstract rather than just copy/paste changes across generators.


text:
import { Component, OnInit, HostBinding } from '@angular/core';
import { Router } from '@angular/router';

import { AuthenticationService } from '../../_services/index';
import { User } from '../../_models/user';
import { slideInDownAnimation } from '../../animations';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  animations: [ slideInDownAnimation ]
})

/**
 * LoginComponent
 *
 * Handle login of users
 */
export class LoginComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display')   display = 'block';
  @HostBinding('style.position')  position = 'absolute';

    model: User = new User();
    loading = false;
    error = '';

    constructor(
        private router: Router,
        private authenticationService: AuthenticationService) { }

    /**
     * Reset loginstatus when the component is first created
     */
    ngOnInit() {
        // reset login status
        this.authenticationService.logout();
    }

    /**
     * Login the current user
     *
     * Requests the user to be logged in through the AuthenticationService.
     * The AuthenticationService then handles the actual logging in.
     */
    login() {
      // console.log(this.model);
        this.loading = true;
        this.authenticationService.login(this.model.email, this.model.password)
            .subscribe(result => {
              // console.log("Got response!")
                if (result === true) {
                    this.router.navigate(['/']);
                } else {
                    this.error = 'Email or password is incorrect';
                    this.loading = false;
                }
            },
            error => {
              this.model.password = "";
              this.error = 'Email or password is incorrect.';
              this.loading = false;
            }
          );
    }
}


text: <?php echo $renderer ?>


text:
function Upload-ChefPkgToAzure($publishSettingsFile, $storageAccount, $storageContainer, $extensionPackageFile) {
  trap [Exception] {echo $_.Exception.Message;exit 1}

  write-host "Upload-ChefPkgToAzure called with: $publishSettingsFile, $storageAccount, $storageContainer, $extensionPackageFile"

  # If storageAccount does not exists, create it.
  Get-AzureStorageAccount -StorageAccountName $storageAccount
  if ($? -eq $false) {
    write-host "Creating $storageAccount storage account..."
    New-AzureStorageAccount -StorageAccountName  $storageAccount -Label 'ChefExtension' -Description "Store for azure chef extension packages." -Location 'West US'
    write-host "Created storage account - $storageAccount`n`n"
  } else {
    write-host "$storageAccount storage account already exists.`n`n"
  }

  # Get the storage key that needs to be used to create context
  $storageKey = Get-AzureStorageKey -StorageAccountName $storageAccount

  $storageContext = New-AzureStorageContext  -StorageAccountName $storageAccount  -StorageAccountKey $storageKey.Primary

  # Create a storage storageContainer if not present
  # with Blob access - read access to blob data but not container
  Get-AzureStorageContainer -Name $storageContainer -Context $storageContext
  if ($? -eq $false) {
    write-host "Creating $storageContainer storage container..."
    New-AzureStorageContainer $storageContainer -Permission Blob  -Context $storageContext
    write-host "Created container - $storageContainer.`n`n"
  } else {
    write-host "$storageContainer storage container already exists.`n`n"
  }

  # Start the zip package upload to storage.
  Set-AzureStorageBlobContent -Container $storageContainer  -File $extensionPackageFile -Context $storageContext
}

Export-ModuleMember -Function Upload-ChefPkgToAzure


text:
`fixed (int* ptrInt = &_buffer[0])` and `fixed (int* ptrInt = _buffer)` have slightly different semantics.

The difference arises when `_buffer` is `null` or when it's a zero-length array.

 - When using `&_buffer[0]` you'll get an exception (either a `NullReferenceException` or an `IndexOutOfRangeException`).
 - When using `_buffer` you'll get a null pointer.

The compiler needs to emit additional checks when using `fixed (int* ptrInt = _buffer)` to handle this case, therefore the code will be slower.


text:
package org.terracotta.management.service.monitoring.registry.provider;

import com.tc.classloader.CommonComponent;
import org.terracotta.management.model.capabilities.descriptors.StatisticDescriptor;
import org.terracotta.management.model.context.Context;
import org.terracotta.management.model.stats.StatisticRegistry;
import org.terracotta.statistics.registry.Statistic;

import java.io.Closeable;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

@CommonComponent
public class AbstractExposedStatistics<T extends AliasBinding> extends AliasBindingManagementProvider.ExposedAliasBinding<T> implements Closeable {

  private final StatisticRegistry statisticRegistry;

  protected AbstractExposedStatistics(Context context, T binding, StatisticRegistry statisticRegistry) {
    super(context, binding);
    this.statisticRegistry = statisticRegistry;
  }

  @Override
  public void close() {
  }

  protected StatisticRegistry getStatisticRegistry() {
    return statisticRegistry;
  }

  @SuppressWarnings("unchecked")
  public <T extends Serializable> Optional<Statistic<T>> queryStatistic(String fullStatisticName, long since) {
    return statisticRegistry.queryStatistic(fullStatisticName, since);
  }

  public Map<String, Statistic<? extends Serializable>> queryStatistics(long since) {
    return statisticRegistry.queryStatistics(since);
  }

  @Override
  public Collection<? extends StatisticDescriptor> getDescriptors() {
    return statisticRegistry.getDescriptors();
  }

}


text:
/**
 * Get an Adapter factory object to provide an adaptor for typeCode
 * @method
 * @param {EncodingNamespace} encoding EncodingNamespace instance.
 * @return {object} Adapter factory
 */

(function() {
  module.exports = function(encoding) {
    return {
      types: require('../typecodes'),
      Undefined: require('./undefined')(encoding),
      String: require('./string')(encoding),
      Integer: require('./integer')(encoding),
      Double: require('./double')(encoding),
      Boolean: require('./boolean')(encoding),
      Null: require('./null')(encoding),
      DateTime: require('./datetime')(encoding),
      Array: require('./array')(encoding),
      Object: require('./object')(encoding),
      Function: require('./function')(encoding),

      /**
       * Get an Adapter for typeCode
       * @method
       * @param {integer} typeCode Type code.
       * @return {AbstractAdapter} AbstractAdapter extension
       */
      get: function(typeCode) {
        switch (typeCode) {
          case this.types.undefined:
            return this.Undefined;
          case this.types.string:
            return this.String;
          case this.types.integer:
            return this.Integer;
          case this.types.double:
            return this.Double;
          case this.types.boolean:
            return this.Boolean;
          case this.types["null"]:
            return this.Null;
          case this.types.datetime:
            return this.DateTime;
          case this.types.array:
            return this.Array;
          case this.types.object:
            return this.Object;
          case this.types["function"]:
            return this.Function;
          default:
            throw new Error("Unknown typeCode \"" + typeCode + "\".");
        }
      }
    };
  };

}).call(this);


text:
/// <reference path="../interfaces.ts" />

/* tslint:disable:max-line-length */
/* tslint:disable:eofline */
var resourceBase = <Resource>{
  "name": "custom_fields",
  "comment": "",
  "properties":[],
  "actions": [
  {
    "name": "createCustomField",
    "method": "POST",
    "collection": true||false,
    "path": "/custom_fields",
    "params": [
    ],
    "comment": "Create a custom field"
  },
  {
    "name": "createEnumOptionForCustomField",
    "method": "POST",
    "collection": true||false,
    "path": "/custom_fields/%s/enum_options",
    "params": [
      {
      "name": "custom_field_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the custom field.",
      "required": true
      },
    ],
    "comment": "Create an enum option"
  },
  {
    "name": "deleteCustomField",
    "method": "DELETE",
    "collection": false,
    "path": "/custom_fields/%s",
    "params": [
      {
      "name": "custom_field_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the custom field.",
      "required": true
      },
    ],
    "comment": "Delete a custom field"
  },
  {
    "name": "getCustomField",
    "method": "GET",
    "collection": false,
    "path": "/custom_fields/%s",
    "params": [
      {
      "name": "custom_field_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the custom field.",
      "required": true
      },
    ],
    "comment": "Get a custom field"
  },
  {
    "name": "getCustomFieldsForWorkspace",
    "method": "GET",
    "collection": true||false,
    "path": "/workspaces/%s/custom_fields",
    "params": [
      {
      "name": "workspace_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the workspace or organization.",
      "required": true
      },
    ],
    "comment": "Get a workspace's custom fields"
  },
  {
    "name": "insertEnumOptionForCustomField",
    "method": "POST",
    "collection": false,
    "path": "/custom_fields/%s/enum_options/insert",
    "params": [
      {
      "name": "custom_field_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the custom field.",
      "required": true
      },
    ],
    "comment": "Reorder a custom field's enum"
  },
  {
    "name": "updateCustomField",
    "method": "PUT",
    "collection": false,
    "path": "/custom_fields/%s",
    "params": [
      {
      "name": "custom_field_gid",
      "type": "string",
      "example_values": ["12345"],
      "comment": "Globally unique identifier for the custom field.",
      "required": true
      },
    ],
    "comment": "Update a custom field"
  },
  {
    "name": "updateEnumOption",
    "method": "PUT",
    "collection": false,
    "path": "/enum_options/%s",
    "params": [
      {
      "name": "enum_option_gid",
      "type": "string",
      "example_values": ["124578"],
      "comment": "Globally unique identifier for the enum option.",
      "required": true
      },
    ],
    "comment": "Update an enum option"
  },
  ]
}
export = resourceBase;


text:
In tmux, the size of window panes can be adjusted incrementally with the
`resize-pane` command. For instance, to resize a pane in any direction
(left, down, up, and right), use one of the following commands

```tmux
resize-pane -L 10
resize-pane -D 10
resize-pane -U 10
resize-pane -R 10
```

This will adjust the pane by *10* units in the corresponding direction. Of
course, other values can be used for more significant size adjustments.

Via [jbranchaud/til](https://github.com/jbranchaud/til).


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="app_bar_height">220dp</dimen>

    <dimen name="fab_margin">16dp</dimen>
    <dimen name="text_margin">16dp</dimen>

    <dimen name="main_rv_padding">4dp</dimen>

    <dimen name="details_poster_width">120dp</dimen>
    <dimen name="details_poster_height">180dp</dimen>
    <dimen name="details_title_genre_left_padding">72dp</dimen>
    <dimen name="details_title_genre_min_height">106dp</dimen>
    <!-- 106 = 180(poster)/2(anchor) + 16 (margin) -->
    <dimen name="details_title_genre_right_padding">16dp</dimen>
    <dimen name="details_space_width">80dp</dimen>
    <dimen name="details_iv_marginTop">11dp</dimen>
    <dimen name="details_tv_secondary_margin_top">8dp</dimen>
    <dimen name="movie_title_margin_top">20dp</dimen>
    <!-- 80 = 16 (margin) + 120(poster) - 72 (padding) + 16 (margin) -->

    <dimen name="hour_size">30sp</dimen>
    <dimen name="minute_size">15sp</dimen>

    <dimen name="toolbar_height2">64dp</dimen>
</resources>


text:
package com.myweather.app.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;

/**
 * ×Ô¶¨ÒåÔ²µãָʾÆ÷
 * @author winGyb
 *
 */
public class DotIndicatorView extends View{

	private int sizeR = 15;
	private int color = Color.rgb(222, 222, 222);
	private int count = 5;
	private int selColor = Color.WHITE;

	private int position = 1;
	/**
	 * ÓÃÀ´»Ô²µÄ¿ò
	 */
	private Paint paint1 =  new Paint();
	/**
	 * ÓÃÀ´Ìî³ä±»Ñ¡ÖеÄÔ²
	 */
	private Paint paint2 = new Paint();

	private int width;
	private int height;

	public DotIndicatorView(Context context, AttributeSet attrs) {
		super(context, attrs);
		WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Point point = new Point();
		window.getDefaultDisplay().getSize(point);
		width = point.x;
		height = point.y;
		System.out.println("ÆÁÄ»¿í:"+width);
		System.out.println("ÆÁÄ»¸ß:"+height);
	}
	/**
	 * ÓÉÓÚ²»ÐèÒªÔÙxmlÖÐÏÔʾ  ËùÒÔ¹¹Ôì·½·¨ÖнÓÊÕÑÕÉ«  Ô²µÄ´óС,Ô²µÄ¸öÊýµÈ²ÎÊý
	 * @param context
	 * @param sizeR   Ô²µÄ°ë¾¶
	 * @param color   »¿òµÄÑÕÉ«
	 * @param count   Ô²µÄ¸öÊý
	 * @param selColor ±»Ñ¡ÖеÄÔ²µÄÑÕÉ«
	 */
	public DotIndicatorView(Context context,int sizeR,int color,int count,int selColor){
		this(context,null);
		this.sizeR = sizeR;
		this.color = color;
		this.count = count;
		this.selColor = selColor;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		paint1.setColor(color);
		paint1.setAntiAlias(true);//¿¹¾â³Ý
		paint1.setAlpha(80);
		paint2.setColor(selColor);
		paint2.setAntiAlias(true);//¿¹¾â³Ý
		//paint1.setStyle(Style.STROKE);//»±ÊÉèÖÃΪ¿ÕÐĵÄ
		int begin = (width-(sizeR*3*count-sizeR))/2;
		for(int i=0;i<count;i++){

			if(position-1==i){
				canvas.drawCircle(begin+sizeR+(sizeR*3*i), (height+sizeR)*3/5, sizeR, paint2);
			}else{
				canvas.drawCircle(begin+sizeR+(sizeR*3*i), (height+sizeR)*3/5, sizeR, paint1);
				//System.out.println(begin+sizeR+(sizeR*3*i));
				//System.out.println((height-sizeR)/2);
			}
		}

	}
	public int getsizeR() {
		return sizeR;
	}
	public void setSizeR(int sizeR) {
		this.sizeR = sizeR;
	}
	public int getColor() {
		return color;
	}
	public void setColor(int color) {
		this.color = color;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getSelColor() {
		return selColor;
	}
	public void setSelColor(int selColor) {
		this.selColor = selColor;
	}
	public int getPosition() {
		return position;
	}
	public void setPosition(int position) {
		this.position = position;
	}

}


text:
import {exec}                       from 'child_process';
import fs                           from 'fs';
import fse                          from 'fs-extra';
import path                         from 'path';
import test                         from 'ava';
import nightmare                    from 'nightmare';

const runner = nightmare({
    show : false
});

test.serial('custom-border-radius', async t => {

    t.plan(2);

    const maxBuffer = 1024000;

    let pathProjectRoot = path.resolve(__dirname, '../../../');
    let pathTmp = path.resolve(pathProjectRoot, '.tmp');
    let pathDir = path.resolve(pathTmp, 'custom-border-radius/');
    let pathPackage = path.resolve(pathDir, 'package.json');
    let pathWebpack = path.resolve(pathDir, 'webpack.config.js');
    let pathSrc = path.resolve(pathDir, 'src/');
    let pathDist = path.resolve(pathDir, 'dist/');
    let pathHtml = path.resolve(pathDist, 'index.html');
    let pathJs = path.resolve(pathSrc, 'index.js');
    let pathTheme = path.resolve(pathSrc, 'theme.less');

    fse.emptyDirSync(pathDir);
    fse.emptyDirSync(pathSrc);
    fse.emptyDirSync(pathDist);

    fs.writeFileSync(pathPackage, `{}`);

    fs.writeFileSync(pathWebpack, `
    const path = require('path');

    module.exports = {
        entry: './src/index.js',
        output: {
            filename: 'bundle.js',
            path: '${pathDist}'
        },
        mode : 'production',
        module: {
            rules: [
                {
                    test: /\\.css$/,
                    use: [
                       'style-loader',
                       'css-loader'
                    ]
                },
                {
                    test: /\\.less$/,
                    use: [
                       'style-loader',
                       'css-loader',
                       'less-loader'
                    ]
                },
                {
                    test : /\\.woff$/,
                    use : [{
                        loader : 'url-loader'
                    }]
                }
            ]
        }
    };
    `);

    fs.writeFileSync(pathTheme, `
@import '~morning-ui/src/lib/styles/index.less';

// 自定圆角
@borderRadius : 9px;
    `);

    fs.writeFileSync(pathJs, `
    import Vue from 'vue/dist/vue.esm.js';
    import morning from 'morning-ui';
    import './theme.less';

    window.morning = morning;
    Vue.use(morning);
    new Vue({
        el : '#vue',
        template : '
<ui-textinput></ui-textinput>
'
    });
    `);

    fs.writeFileSync(pathHtml, `

            <title>e2e test : custom-theme-color</title>

    `);

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && npm install morning-ui && npm install webpack@4.29.0 style-loader css-loader less-loader url-loader vue@2.5.22`,
            {
                maxBuffer : maxBuffer
            },
            error => {

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    await new Promise((resolve, reject) => {

        exec(
            `cd ${pathDir} && node_modules/.bin/webpack --config webpack.config.js`,
            {
                maxBuffer : maxBuffer
            },
            error => {

                if (error) {

                    reject(error);

                }

                resolve();

            }
        );

    });

    const result = await runner
        .goto(`file://${pathHtml}`)
        .wait('mor-textinput')
        .evaluate(() => ({
            morning : window.morning.isMorning,
            textinput : window.getComputedStyle(document.querySelector('mor-textinput input')).borderRadius
        }));

    t.is(result.morning, true);
    t.is(result.textinput, '9px');

});


text:
package org.glowroot.common2.config;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.immutables.value.Value;

import org.glowroot.common.util.Versions;

@Value.Immutable
public abstract class HttpProxyConfig {

    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String host() {
        return "";
    }

    @JsonInclude(Include.NON_NULL)
    public abstract @Nullable Integer port();

    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String username() {
        return "";
    }

    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String encryptedPassword() {
        return "";
    }

    @Value.Derived
    @JsonIgnore
    public String version() {
        return Versions.getJsonVersion(this);
    }
}


text:
package airec

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// ExtInfo is a nested struct in airec response
type ExtInfo struct {
	ItemSeparator string `json:"itemSeparator" xml:"itemSeparator"`
	KvSeparator   string `json:"kvSeparator" xml:"kvSeparator"`
}


text:
"""
MariaDBLog - File ``/var/log/mariadb/mariadb.log``
==================================================

Module for parsing the log file for MariaDB

Typical content of ``mariadb.log`` file is::

    161109  9:25:42 [Note] WSREP: Read nil XID from storage engines, skipping position init
    161109  9:25:42 [Note] WSREP: wsrep_load(): loading provider library 'none'
    161109  9:25:42 [Warning] Failed to setup SSL
    161109  9:25:42 [Warning] SSL error: SSL_CTX_set_default_verify_paths failed
    161109  9:25:42 [Note] WSREP: Service disconnected.
    161109  9:25:43 [Note] WSREP: Some threads may fail to exit.
    161109  9:25:43 [Note] WSREP: Read nil XID from storage engines, skipping position init
    161109  9:25:43 [Note] WSREP: wsrep_load(): loading provider library 'none'
    161109  9:25:43 [Warning] Failed to setup SSL
    161109  9:25:43 [Warning] SSL error: SSL_CTX_set_default_verify_paths failed
    161109  9:25:43 [Note] WSREP: Service disconnected.
    161109  9:25:44 [Note] WSREP: Some threads may fail to exit.
    161109 14:28:22 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
    161109 14:28:22 mysqld_safe WSREP: Running position recovery with --log_error='/var/lib/mysql/wsrep_recovery.OkURTZ' --pid-file='/var/lib/mysql/overcloud-controller-0.localdomain-recover.pid'
    161109 14:28:22 [Warning] option 'open_files_limit': unsigned value 18446744073709551615 adjusted to 4294967295

Examples:

    >>> mdb = shared[MariaDBLog]
    >>> mdb.get('mysqld_safe')[0]['raw_message']
    '161109 14:28:22 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql'
    >>> 'SSL_CTX_set_default_verify_paths' in mdb
    True
"""

from .. import LogFileOutput, parser
from insights.specs import Specs

@parser(Specs.mariadb_log)
class MariaDBLog(LogFileOutput):
    """Class for parsing ``/var/log/mariadb/mariadb.log`` file.

    .. note::
        Please refer to its super-class :class:`insights.core.LogFileOutput`
    """
    time_format = {
        'pre_10.1.5': '%y%m%d %H:%M:%S',
        'post_10.1.5': '%Y-%m-%d %H:%M:%S'
    }


text:
* Fixed #328: Fixed exception when inspecting observable in `onBecomeObserved`
* Fixed #341: `array.find` now returns `undefined` instead of `null` when nothing was found, behavior now matches the docs. (By @hellectronic)

# 2.3.1

* Fixed #327: spy not working with runInAction

# 2.3.0

### Introduced `whyRun`:
Usage:
* `whyRun()`
* `whyRun(Reaction object / ComputedValue object / disposer function)`
* `whyRun(object, "computed property name")`

`whyRun` is a small utility that can be used inside computed value or reaction (`autorun`, `reaction` or the `render` method of an `observer` React component)
and prints why the derivation is currently running, and under which circumstances it will run again.
This should help to get a deeper understanding when and why MobX runs stuff, and prevent some beginner mistakes.

This feature can probably be improved based on your feedback, so feel free to file issues with suggestions!

### Semantic changes:
* `@observable` is now always defined on the class prototypes and not in the instances. This means that `@observable` properties are enumerable, but won't appear if `Object.keys` or `hasOwnProperty` is used on a class _instance_.
* Updated semantics of `reaction` as discussed in `#278`. The expression now needs to return a value and the side effect won't be triggered if the result didn't change. `asStructure` is supported in these cases. In contrast to MobX 2.2, effects will no longer be run if the output of the expression didn't change.

### Enhancements

* Introduces `isAction(fn)` #290
* If an (argumentless) action is passed to `observable` / `extendObservable`, it will not be converted into a computed property.
* Fixed #285: class instances are now also supported by `toJS`. Also members defined on prototypes which are enumerable are converted.
* Map keys are now always coerced to strings. Fixes #308
* `when`, `autorun` and `autorunAsync` now accept custom debug names (see #293, by @jamiewinder)
* Fixed #286: autorun's no longer stop working if an action throws an exception
* Implemented `runInAction`, can be used to create on the fly actions (especially useful in combination with `async/await`, see #299
* Improved performance and reduced mem usage of decorators signficantly (by defining the properties on the prototype if possible), and removed subtle differences between the implementation and behavior in babel and typescript.
* Updated logo as per #244. Tnx @osenvosem!

# 2.2.2:

* Fixed issue #267: exception when `useStrict(true)` was invoked in combination with `@observable` attributes when using Babel
* Fixed issue #269: @action in combination with typescript targeting ES6 and reflect.ts
* Improved compatibility with `JSON.stringify`, removed incorrect deprecation message
* Improved some error messages

# 2.2.1

* Fixed issue where typescript threw a compile error when using `@action` without params on a field
* Fixed issue where context was accidentally shared between class instances when using `@action` on a field

# 2.2.0

See the [release announcement](https://medium.com/@mweststrate/45cdc73c7c8d) for the full details of this release:

Introduced:
* `action` / `@action`
* `intercept`
* `spy`
* `reaction`
* `useStrict`
* improved debug names
* `toJSON` was renamed to `toJS`
* `observable(asMap())` is the new idiomatic way to create maps
* the effect of `when` is now untracked, similar to `reaction.
* `extras.trackTransations` is deprecated, use `spy` instead
* `untracked` has been undeprecated
* introduced / documented: `getAtom`, `getDebugName`, `isSpyEnabled`, `spyReport`, `spyReportStart`, `spyReportEnd`
* deprecated `extras.SimpleEventEmitter`
* array splice events now also report the `added` collection and `removedCount`

# 2.1.7

* Fixed a false negative in cycle detection, as reported in #236

# 2.1.6

* Fixed #236, #237 call stack issues when working with large arrays

# 2.1.5

* Fix #222 (by @andykog) run `observe` callback of computed properties in untracked mode.

# 2.1.4

* Fixed #201 (see also #160), another iOS enumerability issue... By @luosong

# 2.1.3

* Fixed #191, when using babel, complex field initializers where shared. By @andykog
* Added `lib/mobx.umd.min.js` for minified cdn builds, see #85

# 2.1.2

* Improved debug names of objects created using a constructor
* Fixed(?) some issues with iOS7 as reported in #60 by @bstst

# 2.1.1

* Fixed issue where `autorun`'s created inside `autorun`'s were not always kicked off. (`mobx-react`'s `observer` was not affected). Please upgrade if you often use autorun.
* Fixed typings of `mobx.map`, a list of entries is also acceptable.
* (Experimental) Improved error recovery a bit further

# 2.1.0

* MobX is now chatty again when an exception occurs inside a autorun / computed value / React.render. Previously this was considered to be the responsibility of the surrounding code. But if exceptions were eaten this would be really tricky to debug.
* (Experimental) MobX will now do a poor attempt to recover from exceptions that occured in autorun / computed value / React.render.

# 2.0.6

* `resetGlobalState` is now part of the `mobx.extras` namespace, as it is useful for test setup, to restore inconsistent state after test failures.
* `resetGlobalState` now also resets the caches of `createTransformer`, see #163.

# 2.0.5

* WIP on bower support

# 2.0.4

* `$transformId` property on transformed objects should be non-enumerable. Fixes #170.

# 2.0.3

* Always peek if inspecting a stale, computed value. Fixes #165.

# 2.0.2

* Fixed issue where changing an object property was tracked, which could lead to unending loops in `autorunAsync`.

# 2.0.1

* Undeprecated `observable(scalar)` (see 143)
* `expr` no longer prints incorrect deprecated messages (see 143)
* Requires `mobx` twice no longer fails.

# 2.0.0

## A new name...
Welcome to ~Mobservable~ MobX 2! First of all, there is the name change.
The new name is shorter and funnier and it has the right emphasis: MobX is about reactive programming.
Not about observability of data structures, which is just a technical necessity.
MobX now has its own [mobxjs](https://github.com/mobxjs) organization on GitHub. Just report an issue if you want to join.

All MobX 2.0 two compatible packages and repo's have been renamed. So `mobx-react`, `mobx-react-devtools` etc.
For the 1.0 versions, use the old `mobservable` based names.

## Migrating from Mobservable 1.x to MobX 2.0

Migrating from Mobservable should be pretty straight-forward as the public api is largely the same.
However there are some conceptual changes which justifies a Major version bump as it might alter the behavior of MobX in edge cases.
Besides that, MobX is just a large collection of minor improvements over Mobservable.
Make sure to remove your old `mobservable` dependencies when installing the new `mobx` dependencies!

## `autorun`'s are now allowed to cause cycles!
`autorun` is now allowed to have cycles. In Mobservable 1 an exception was thrown as soon as an autorun modified a variable which it was reading as well.
In MobX 2 these situations are now allowed and the autorun will trigger itself to be fired again immediately after the current execution.
This is fine as long as the autorun terminates within a reasonable amount of iterations (100).
This should avoid the need for work-arounds involving `setTimeout` etc.
Note that computed values (created using `observable(func)` are still not allowed to have cycles.

## [Breaking] `observable(scalar)` returns an object instead of a function and has been deprecated.

Creating an observable from a primitive or a reference no longer returns a getter/setter function, but a method with a `.get` and `.set` method.
This is less confusing, easier to debug and more efficient.

So to read or write from an observable scalar use:
```javascript
const temperature =  observable(27);
temperature.set(15); // previously: temperature(15)
temperature.get();   // previously: temperature()
```

`observable(scalar)` has been deprecated to make the api smaller and the syntax more uniform. In practice having observable objects, arrays and decorators seems to suffice in 99% of the cases. Deprecating this functionality means that people have simply less concepts to learn. Probably creating observable scalars will continue to work for a long time, as it is important to the internals of MobX and very convenient for testing.

## Introduced `@computed`

MobX introduced the `@computed` decorator for ES6 class properties with getter functions.
It does technically the same as `@observable` for getter properties. But having a separate decorator makes it easier to communicate about the code.
`@observable` is for mutable state properties, `@computed` is for derived values.

`@computed` can now also be parameterized. `@computed({asStructure: true})` makes sure that the result of a derivation is compared structurally instead of referentially with its preview value. This makes sure that observers of the computation don't re-evaluate if new structures are returned that are structurally equal to the original ones. This is very useful when working with point, vector or color structures for example. It behaves the same as the `asStructure` modifier for observable values.

`@computed` properties are no longer enumerable.

## MobX is now extensible!

The core algorithm of MobX has been largely rewritten to improve the clarity, extensibility, performance and stability of the source code.
It is now possible to define your own custom observable data sources by using the `Atom` class.
It is also possible to create your own reactive functions using the `Reaction` class. `autorun`, `autorunAsync` and `@observer` have now all been implemented using the concept of Reactions.
So feel free to write your own reactive [constructions](http://mobxjs.github.io/mobx/refguide/extending.html)!

## Mobservable now fails fast

In Mobservable 1 exceptions would be caught and sometimes re-thrown after logging them.
This was confusing and not all derivations were able to recover from these exceptions.
In MobX 2 it is no longer allowed for a computed function or `autorun` to throw an exception.

## Improved build

* MobX is roughly 20% faster
* MobX is smaller: 75KB -> 60KB unminified, and 54KB -> 30KB minified.
* Distributable builds are no longer available in the git repository, use npmcdn instead:
* Commonjs build: https://npmcdn.com/mobx@^2.0.0/lib/mobx.js
* Minified commonjs build: https://npmcdn.com/mobx@^2.0.0/lib/mobx.min.js
* UMD build: https://npmcdn.com/mobx@^2.0.0/lib/mobx.umd.js
* To use the minified build, require / import the lib from `"mobx/lib/mobx.min.js"` (or set up an alias in your webpack configuration if applicable)

## Other changes

* Improved debug names of all observables. This is especially visible when using `mobx-react-devtools` or `extras.trackTransitions`.
* Renamed `extras.SimpleEventEmitter` to `SimpleEventEmitter`
* Removed already deprecated methods: `isReactive`, `makeReactive`, `observeUntil`, `observeAsync`
* Removed `extras.getDNode`
* Invoking `ObservableArray.peek` is no longer registered as listener
* Deprecated `untracked`. It wasn't documented and nobody seems to miss it.

# 1.2.5

* Map no longer throws when `.has`, `.get` or `.delete` is invoked with an invalid key (#116)
* Files are now compiled without sourcemap to avoid issues when loading mobservable in a debugger when `src/` folder is not available.

# 1.2.4

* Fixed: observable arrays didn't properly apply modifiers if created using `asFlat([])` or `fastArray([])`
* Don't try to make frozen objects observable (by @andykog)
* `observableArray.reverse` no longer mutates the arry but just returns a sorted copy
* Updated tests to use babel6

# 1.2.3

* observableArray.sort no longer mutates the array being sorted but returns a sorted clone instead (#90)
* removed an incorrect internal state assumption (#97)

# 1.2.2

* Add bower support

# 1.2.1

* Computed value now yields consistent results when being inspected while in transaction

# 1.2.0

* Implemented #67: Reactive graph transformations. See: http://mobxjs.github.io/mobservable/refguide/create-transformer.html

# 1.1.8

* Implemented #59, `isObservable` and `observe` now support a property name as second param to observe individual values on maps and objects.

# 1.1.7

* Fixed #77: package consumers with --noImplicitAny should be able to build

# 1.1.6

* Introduced `mobservable.fastArray(array)`, in addition to `mobservable.observable(array)`. Which is much faster when adding items but doesn't support enumerability (`for (var idx in ar) ..` loops).
* Introduced `observableArray.peek()`, for fast access to the array values. Should be used read-only.

# 1.1.5

* Fixed 71: transactions should not influence running computations

# 1.1.4

* Fixed #65; illegal state exception when using a transaction inside a reactive function. Credits: @kmalakoff

# 1.1.3

* Fixed #61; if autorun was created during a transaction, postpone execution until the end of the transaction

# 1.1.2

* Fixed exception when autorunUntil finished immediately

# 1.1.1

* `toJSON` now serializes object trees with cycles as well. If you know the object tree is acyclic, pass in `false` as second parameter for a performance gain.

# 1.1.0

* Exposed `ObservableMap` type
* Introduced `mobservable.untracked(block)`
* Introduced `mobservable.autorunAsync(block, delay)`

# 1.0.9

Removed accidental log message

# 1.0.7 / 1.0.8

Fixed inconsistency when using `transaction` and `@observer`, which sometimes caused stale values to be displayed.

# 1.0.6

Fix incompatibility issue with systemjs bundler (see PR 52)

# 1.0.4/5

* `map.size` is now a property instead of a function
* `map()` now accepts an array as entries to construct the new map
* introduced `isObservableObject`, `isObservableArray` and `isObservableMap`
* introduced `observe`, to observe observable arrays, objects and maps, similarly to Object.observe and Array.observe

# 1.0.3

* `extendObservable` now supports passing in multiple object properties

# 1.0.2

* added `mobservable.map()`, which creates a new map similarly to ES6 maps, yet observable. Until properly documentation, see the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).

# 1.0.1

* Stricter argument checking for several api's.

# 1.0

## Renames

* `isReactive` -> `isObservable`
* `makeReactive` -> `observable`
* `extendReactive` -> `extendObservable`
* `observe` -> `autorun`
* `observeUntil` -> `autorunUntil`
* `observeAsync` -> `autorunAsync`
* `reactiveComponent` -> `observer` (in `mobservable-react` package)

## Breaking changes

* dropped the `strict` and `logLevel` settings of mobservable. View functions are by default run in `strict` mode, `autorun` (formerly: `observe`) functions in `non-strict` mode (strict indicates that it is allowed to change other observable values during the computation of a view funtion).
Use `extras.withStrict(boolean, block)` if you want to deviate from the default behavior.
* `observable` (formerly `makeReactive`) no longer accepts an options object. The modifiers `asReference`, `asStructure` and `asFlat` can be used instead.
* dropped the `default` export of observable
* Removed all earlier deprecated functions

## Bugfixes / improvements

* `mobservable` now ships with TypeScript 1.6 compliant module typings, no external typings file is required anymore.
* `mobservable-react` supports React Native as well through the import `"mobservable-react/native"`.
* Improved debugger support
* `for (var key in observablearray)` now lists the correct keys
* `@observable` now works correct on classes that are transpiled by either TypeScript or Babel (Not all constructions where supported in Babel earlier)
* Simplified error handling, mobservable will no longer catch errors in views, which makes the stack traces easier to debug.
* Removed the initial 'welcom to mobservable' logline that was printed during start-up.

# 0.7.1

* Backported Babel support for the @observable decorator from the 1.0 branch. The decorator should now behave the same when compiled with either Typescript or Babeljs.

# 0.7.0

* Introduced `strict` mode (see issues [#30](), [#31]())
* Renamed `sideEffect` to `observe`
* Renamed `when` to `observeUntil`
* Introduced `observeAsync`.
* Fixed issue where changing the `logLevel` was not picked up.
* Improved typings.
* Introduces `asStructure` (see [#8]()) and `asFlat`.
* Assigning a plain object to a reactive structure no longer clones the object, instead, the original object is decorated. (Arrays are still cloned due to Javascript limitations to extend arrays).
* Reintroduced `expr(func)` as shorthand for `makeReactive(func)()`, which is useful to create temporarily views inside views
* Deprecated the options object that could be passed to `makeReactive`.
* Deprecated the options object that could be passed to `makeReactive`:
  * A `thisArg` can be passed as second param.
  * A name (for debugging) can be passed as second or third param
  * The `as` modifier is no longer needed, use `asReference` (instead of `as:'reference'`) or `asFlat` (instead of `recurse:false`).

# 0.6.10

* Fixed issue where @observable did not properly create a stand-alone view

# 0.6.9

* Fixed bug where views where sometimes not triggered again if the dependency tree changed to much.

# 0.6.8

* Introduced `when`, which, given a reactive predicate, observes it until it returns true.
* Renamed `sideEffect -> observe`

# 0.6.7:

* Improved logging

# 0.6.6:

* Deprecated observable array `.values()` and `.clone()`
* Deprecated observeUntilInvalid; use sideEffect instead
* Renamed mobservable.toJson to mobservable.toJSON

# 0.6.5:

* It is no longer possible to create impure views; views that alter other reactive values.
* Update links to the new documentation.

# 0.6.4:

* 2nd argument of sideEffect is now the scope, instead of an options object which hadn't any useful properties

# 0.6.3

* Deprecated: reactiveComponent, reactiveComponent from the separate package mobservable-react should be used instead
* Store the trackingstack globally, so that multiple instances of mobservable can run together

# 0.6.2

* Deprecated: @observable on functions (use getter functions instead)
* Introduced: `getDependencyTree`, `getObserverTree` and `trackTransitions`
* Minor performance improvements