text:
define(['jscc', 'constants', 'configurationManager', 'grammarConverter', 'jquery', 'logger', 'module'],
/**
 * Generator for executable language-grammars (i.e. converted JSON grammars).
 *
 *

 * This generator uses JS/CC for compiling the JSON grammar.
 *
 *

 * The generator for compiling the JSON grammar definitions in www/config/languages/<language code>/grammar.json
 * can be configured in www/config/configuration.json:

 *

 * {
 *   ...
 *   "grammarCompiler": "jscc",
 *   ...
 * }

 *
 * NOTE: this is the default grammar engine (if there is no setting in
 * 			 configuration.json, then this engine will be used)
 *
 *
 *

 * JS/CC supports grammar generation for:
 * LALR(1)
 *
 * (in difference to jison, JS/CC supports backtracking to certain extend)
 *
 * @see http://jscc.phorward-software.com/
 *
 * @class
 * @constant
 * @public
 * @name JsccGenerator
 * @memberOf mmir.env.grammar
 *
 * @requires JS/CC
 * @requires jQuery.Deferred
 * @requires jQuery.extend
 * @requires jQuery.ajax
 * @requires jQuery.makeArray
 */
function(jscc, constants, configManager, GrammarConverter, $, Logger, module){

//////////////////////////////////////  template loading / setup for JS/CC generator ////////////////////////////////

/**
 * Deferred object that will be returned - for async-initialization:
 * the deferred object will be resolved, when this module has been initialized.
 *
 * @private
 * @type Deferred
 * @memberOf JsccGenerator#
 *
 * @see #_loadTemplate
 */
var deferred = $.Deferred();

/**
 * The Logger for the JS/CC generator.
 *
 * @private
 * @type Logger
 * @memberOf JsccGenerator#
 *
 * @see mmir.Logging
 */
var logger = Logger.create(module);

//setup logger for compile-messages
/**
 * HELPER for creating default logging / error-print functions
 *
 * @function
 * @private
 * @memberOf JsccGenerator#
 *
 * @see mmir.Logging
 */
function _createCompileLogFunc(log /*Logger*/, level /*String: log-function-name*/, libMakeArray/*helper-lib: provides function makeArray(obj); e.g. jquery*/){
	return function(){
		var args = libMakeArray.makeArray(arguments);
		//prepend "location-information" to logger-call:
		args.unshift('JS/CC', 'compile');
		//output log-message:
		log[level].apply(log, args);
	};
}

/**
 * The URL to the JS/CC template file (generated code-text will be "embedded" in this template)
 *
 * @private
 * @type String
 * @memberOf JsccGenerator#
 */
var templatePath = constants.getGrammarPluginPath() + 'grammarTemplate_reduced.tpl';

/**
 * The argument name when generating the grammar function:
 * the argument holds the raw text that will be parsed by the generated grammar.
 *
 * NOTE: this argument/variable name must not collide with any code that is generated for the grammar.
 *
 * @constant
 * @private
 * @memberOf JsccGenerator#
 */
var INPUT_FIELD_NAME = 'asr_recognized_text';

/**
 * The default options for the JS/CC compiler.
 *
 * To overwrite the default options, configure the following property in www/config/configuration.json:

 *

 * {
 *   ...
 *   "grammar": {
 *   	...
 *   	"jscc": {
 *   		"execMode": "your configuration setting!"
 *   	}
 *   	...
 *   },
 *   ...
 * }

 *
 * Valid settings are:
 * execMode = 'sync' | 'async'
 * genSourceUrl = true | STRING | FALSY'
 *
 *
 * genSourceUrl: if TRUTHY, the sourceUrl for eval'ed parser-module is set
 *               (i.e. eval'ed code will appear at the URL in debugger, if browser supports sourceURL setting)
 *               if true: the sourceUrl will be generated using the grammar's ID
 *               if STRING: the string will be used as sourceUrl; if "<id>" is contained, it will be replaced by the grammar's ID
 *
 * @constant
 * @private
 * @default targetType := jscc.MODE_GEN_JS, execMode := sync, genSourceUrl := FALSY
 * @memberOf JsccGenerator#
 */
var DEFAULT_OPTIONS = {
		targetType: jscc.MODE_GEN_JS,
		execMode: 'sync',//'sync' | 'async' | default: sync
		genSourceUrl: '',// true | STRING: the sourceURL for eval'ed parser-module | default: FALSY
};

/**
 * Name for this plugin/grammar-generator (e.g. used for looking up configuration values in configuration.json).
 * @constant
 * @private
 * @memberOf JsccGenerator#
 */
var pluginName = 'grammar.jison';

/**
 * Exported (public) functions for the JS/CC grammar-engine.
 * @public
 * @type GrammarGenerator
 * @memberOf JsccGenerator#
 */
var jsccGen = {
	/** @scope JsccGenerator.prototype */

	/**
	 * The name/ID for the compile engine for the JS/CC compiler
	 *
	 * @memberOf mmir.env.grammar.JsccGenerator.prototype
	 */
	engineId: 'jscc',
	/**
	 * @param {Function} [callback] OPTIONAL
	 * 			the callback that is triggered, when the engine is initialized
	 * @returns {Deferred}
	 * 			a promise that is resolved, when the engine is initialized
	 * 			(NOTE: if you use the same function for the callback AND the promise,
	 * 			       then the function will be invoked twice!)
	 *
	 * @memberOf mmir.env.grammar.JsccGenerator.prototype
	 */
	init: function(callback){
		if(callback){
			deferred.always(callback);
		}
		return deferred;
	},
	/** @returns {Boolean} if this engine compilation works asynchronously. The current implementation works synchronously (returns FALSE) */
	isAsyncCompilation: function(){ return false; },
	/**
	 * The function for compiling a JSON grammar:
	 *
	 *
	 * @param {GrammarConverter} theConverterInstance
	 * @param {String} instanceId
	 * 				the ID for the compiled grammar (usually this is a language code)
	 * @param {Number} fileFormatVersion
	 * 				the version of the file format (this is a constant within {@link mmir.SemanticInterpreter}
	 * @param callback
	 * @returns {GrammarConverter}
	 * 			the grammar instance with attached with the compiled function for executing the
	 * 			grammar to the instance's {@link GrammarConvert#executeGrammar} property/function.
	 */
	compileGrammar: function(theConverterInstance, instanceId, fileFormatVersion, callback){

		//attach functions for JS/CC conversion/generation to the converter-instance:
		$.extend(theConverterInstance, JsccGrammarConverterExt);
		//attach the JS/CC template to the converter instance
		theConverterInstance.TEMPLATE = this.template;

		//start conversion: create grammar in JS/CC syntax (from the JSON definition):
		theConverterInstance.init();
		this._preparePrintError();
        theConverterInstance.convertJSONGrammar();
        var grammarDefinition = theConverterInstance.getGrammarDef();

        //load options from configuration:
        var config = configManager.get(pluginName, true, {});
        //combine with default default options:
        var options = $.extend({id: instanceId}, DEFAULT_OPTIONS, config);

        var compileParserModule = function(grammarParserStr, hasError){

	        var addGrammarParserExec =
	    	  '(function(){\n  var semanticInterpreter = require("semanticInterpreter");\n'//FIXME
	        	+ 'var options = {fileFormat:'+fileFormatVersion+',execMode:'+JSON.stringify(options.execMode)+'};\n'
	        	+ 'var grammarFunc = function('+INPUT_FIELD_NAME+'){'
	    			//TODO active/use safe_acc (instead of try-catch construct in semantic-result extraction
	//        			+ "var safe_acc = function(obj){\n  \tvar len = arguments.length;\n  \tif(len === 1){\n  \t    return null;\n  \t}\n  \tvar curr = obj, prop = arguments[1], i = 2;\n  \tfor(; i < len; ++i){\n  \tif(obj[prop] != null){\n  \t    obj = obj[prop];\n  \t}\n  \tprop = arguments[i];\n  \t}\n  \tvar res = obj[prop];\n  \treturn typeof res !== 'undefined'? res : null;\n  \t};"
	    			+ grammarParserStr
	        	+ '\n};\n'

	        	//add "self registering" for the grammar-function
	        	//  i.e. register the grammar-function for the ID with the SemanticInterpreter
	        	+ 'semanticInterpreter.addGrammar("'
	        		+instanceId
	        		+'", grammarFunc, options);\n\n'
	        	+ 'semanticInterpreter.setStopwords("'
	        		+instanceId+'",'
	        		//store stopwords with their Unicode representation (only for non-ASCII chars)
	        		+JSON.stringify(
	        				theConverterInstance.getEncodedStopwords()
	        		).replace(/\\\\u/gm,'\\u')//<- revert JSON.stringify encoding for the Unicodes
	        	+ ');\n'
	        	+ 'return grammarFunc;\n'
	        	+ '})();'
	        ;

	        if(options.genSourceUrl){

            	var sourceUrlStr;
            	if(options.genSourceUrl === true){
            		sourceUrlStr = 'gen/grammar/_compiled_grammar_'+instanceId;
            	} else {
            		sourceUrlStr = options.genSourceUrl.toString().replace(/<id>/g,instanceId);
            	}

            	//for Chrome / FireFox debugging: provide an URL for eval'ed code
            	addGrammarParserExec += '//@ sourceURL='+sourceUrlStr+'\n'
            							+'//# sourceURL='+sourceUrlStr+'\n';

            }

	        theConverterInstance.setGrammarSource(addGrammarParserExec);

	        try{

	        	eval(addGrammarParserExec);

	        } catch (err) {

	        	//TODO russa: generate meaningful error message with details about error location
	        	//			  eg. use esprima (http://esprima.org) ...?
	        	//			... as optional dependency (see deferred initialization above?)

	        	var evalMsg = 'Error during eval() for "'+ instanceId +'": ' + err;

	        	if(jscc.get_printError()){
	        		jscc.get_printError()(evalMsg);
	        	}
	        	else {
	        		logger.error('JS/CC', 'evalCompiled', evalMsg, err);
	        	}

	        	if(! hasError){
	            	evalMsg = '[INVALID GRAMMAR JavaScript CODE] ' + evalMsg;
	            	var parseDummyFunc = (function(msg, error){
	            		return function(){ console.error(msg); console.error(error); throw msg;};
	            	})(evalMsg, err);

	            	parseDummyFunc.hasErrors = true;

	            	theConverterInstance.setGrammarFunction(parseDummyFunc);
	        	}

	        }

	        //invoke callback if present:
	        if(callback){
	        	callback(theConverterInstance);
	        }
		};

		var isPreventDefault = this._afterCompileParser(compileParserModule, callback);
        var result = this._compileParser(grammarDefinition, options, isPreventDefault);

        if(!isPreventDefault){
        	var hasError = result.hasError;
        	compileParserModule(result.def, hasError);
        }

        return theConverterInstance;
	},
	/**
	 * @protected
	 */
	_compileParser: function(grammarDefinition, options, afterCompileParserResult){

		//set up the JS/CC compiler:
        var dfa_table = '';
        jscc.reset_all( jscc.EXEC_WEB );

        var isParsingFailed = false;
        var grammarParserStr;
        try {
        	jscc.parse_grammar(grammarDefinition);
        } catch (err){
        	var msg = 'Error while compiling grammar: ' + (err.stack?err.stack:err);
        	isParsingFailed = msg;

        	msg = '[INVALID GRAMMAR] ' + msg;
        	grammarParserStr = 'var msg = '+JSON.stringify(msg)+'; console.error(msg); throw msg;';//FIXME
        }

        if (jscc.getErrors() == 0) {
        	jscc.undef();
        	jscc.unreachable();

            if (jscc.getErrors() == 0) {
            	jscc.first();
            	jscc.print_symbols();
            	dfa_table = jscc.create_subset(jscc.get_nfa_states());
            	dfa_table = jscc.minimize_dfa(dfa_table);

            	jscc.set_dfa_table(dfa_table);//FIXME: check, if this is really necessary

            	jscc.lalr1_parse_table(false);
            	jscc.resetErrors();
            }
        }

        if (jscc.getErrors() > 0 || jscc.getWarnings() > 0){
            logger.error(
            		'JSCC', 'compile', 'there occured'
            		+ (jscc.getWarnings() > 0? jscc.getWarnings() + ' warning(s)' : '')
            		+ (jscc.getErrors() > 0? jscc.getErrors() + ' error(s)' : '')
            		+ ' during compilation.'
            );
        }
        jscc.resetErrors();
        jscc.resetWarnings();

//      console.debug("before replace " + theConverterInstance.PARSER_TEMPLATE);//debug

        if( ! isParsingFailed){

        	var genData = this._getGenerated(options.targetType, dfa_table);
        	grammarParserStr = this._applyGenerated(genData, this.template);
        }

		return {def: grammarParserStr, hasError: isParsingFailed};
	},
	/**
	 * @protected
	 */
	_preparePrintError: function(){

		//only set print-message function, if it is not already set
		//  (i.e. if JS/CC still has its default print function set)
		if(jscc.is_printError_default()){
			/**
			 * The default logging function for printing compilation errors.
			 * @private
			 * @name set_printError
			 * @function
			 * @memberOf JsccGenerator.jscc#
			 */
			jscc.set_printError(	_createCompileLogFunc(logger, 'error', $));
		}
		if(jscc.is_printWarning_default()){
			/**
			 * The default logging function for printing compilation warnings.
			 * @private
			 * @name set_printWarning
			 * @function
			 * @memberOf JsccGenerator.jscc#
			 */
			jscc.set_printWarning(	_createCompileLogFunc(logger, 'warn', $));
		}
		if(jscc.is_printInfo_default()){
			/**
			 * The default logging function for printing compilation information.
			 * @private
			 * @name set_printInfo
			 * @function
			 * @memberOf JsccGenerator.jscc#
			 */
			jscc.set_printInfo(		_createCompileLogFunc(logger, 'info', $));
		}
	},
	/**
	 * The default logging / error-print function for JS/CC.
	 *
	 * @protected
	 *
	 * @see mmir.Logging
	 */
	printError: function(){
		var errorFunc = jscc.get_printError();
		if(errorFunc){
			errorFunc.apply(jscc, arguments);
		} else {
			var args = $.makeArray(arguments);
			//prepend "location-information" to logger-call:
			args.unshift('JS/CC', 'compile');
			//output log-message:
			logger.error.apply(logger, args);
		}
	},
	/**
	 * Optional hook for pre-processing the generated parser, after the parser is generated.
	 *
	 * By default, this function returns VOID, in which case the parser-module is created by default.
	 *
	 * If a function is returned instead, then it must invoke compileParserModuleFunc:
	 * compileParserModuleFunc(compiledParser : STRING, hasErrors : BOOLEAN)
	 *
	 *
	 * @param {Function} compileParserModuleFunc
	 * 				the function that generates the parser-module:
	 * 				compileParserModuleFunc(compiledParser : STRING, hasErrors : BOOLEAN)
	 *
	 * @param {Function} compileCallbackFunc
	 * 				the callback function which will be invoked by compileParserModuleFunc, after it has finished.
	 * 				If compileParserModuleFunc() is prevented from exectution then the callback MUST be invoked manually
	 * 				compileCallbackFunc(theConverterInstance: GrammarConverter)
	 *
	 * @returns {TRUTHY|VOID}
	 * 				FALSY for the default behavior.
	 * 				IF a TRUTHY value is returned, then the default action after compiling the parser
	 * 				is not executed:
	 * 					i.e. compileParserModuleFunc is not automatically called and in consequence the callback is not invoked
	 *
	 *
	 * 				NOTE: if not FALSY, then either compileParserModuleFunc() must be invoked, or the callback() must be invoked!
	 *
	 * @protected
	 */
	_afterCompileParser: function(compileParserModuleFunc, compileCallbackFunc){
		//default: return VOID
		return;
	},
	/**
	 * @protected
	 */
	_getGenerated: function(genMode, dfaTable){
		return {
			head: jscc.get_code_head(),
			tables: jscc.print_parse_tables(genMode),//jscc.MODE_GEN_JS
			dfa: jscc.print_dfa_table(dfaTable),//dfa_table
			terminals: jscc.print_term_actions(),
			labels: jscc.print_symbol_labels(),
			actions: jscc.print_actions(),
			error: jscc.get_error_symbol_id(),
			eof: jscc.get_eof_symbol_id(),
			whitespace: jscc.get_whitespace_symbol_id()
		};
	},
	/**
	 * @protected
	 */
	_applyGenerated: function(genData, template){

        var grammarParserStr = template;
        grammarParserStr = grammarParserStr.replace(/##PREFIX##/g, "");
        grammarParserStr = grammarParserStr.replace(/##HEADER##/g, genData.head);
        grammarParserStr = grammarParserStr.replace(/##TABLES##/g, genData.tables);
        grammarParserStr = grammarParserStr.replace(/##DFA##/g, genData.dfa);
        grammarParserStr = grammarParserStr.replace(/##TERMINAL_ACTIONS##/g, genData.terminals);
        grammarParserStr = grammarParserStr.replace(/##LABELS##/g, genData.labels);
        grammarParserStr = grammarParserStr.replace(/##ACTIONS##/g, genData.actions);
        grammarParserStr = grammarParserStr.replace(/##FOOTER##/g, "\nvar _semanticAnnotationResult = { result: {}};\n__parse( "+INPUT_FIELD_NAME+", new Array(), new Array(), _semanticAnnotationResult);\nreturn _semanticAnnotationResult.result;");
        grammarParserStr = grammarParserStr.replace(/##ERROR##/g, genData.error);
        grammarParserStr = grammarParserStr.replace(/##EOF##/g, genData.eof);
        grammarParserStr = grammarParserStr.replace(/##WHITESPACE##/g, genData.whitespace);

        return grammarParserStr;
	}
};

/**
 * Initializes the grammar-engine:
 *
 * loads the template and resolves the engine as initialzed.
 *
 * @param {String} url
 * 			URL to the template file
 * @param {GrammarGenerator} jsccGenerator
 * 			the JS/CC grammar generator instance
 * @param {Deferred} promise
 * 			the {@link #deferred} for resolving the generator
 * 			as initialized.
 *
 *
 * @private
 * @function
 * @memberOf JsccGenerator#
 */
function _loadTemplate(url, jsccGenerator, promise){
	$.ajax({
		url: url,
		dataType: 'text',
		async: true,
		success: function(data){

			jsccGenerator.template = data;

			promise.resolve();

		},
		error: function(xhr, status, err){
			var msg = 'Failed to load grammar template file from "'+templatePath+'": '+status+', ERROR '+err;
			console.error(msg);
			promise.reject(msg);
		}
	});
}

//load the JS/CC template and resolve this module as "initialzed":
_loadTemplate(templatePath, jsccGen, deferred);

////////////////////////////////////// JS/CC specific extensions to GrammarConverter ////////////////////////////////

/**
 * JS/CC specific extension / implementation for {@link GrammarConverter} instances
 *
 * @type GrammarConverter
 * @memberOf JsccGenerator#
 */
var JsccGrammarConverterExt = {
	/** @memberOf JsccGrammarConverterExt */
	init: function(){

		this.THE_INTERNAL_GRAMMAR_CONVERTER_INSTANCE_NAME = "theGrammarConverterInstance";
		this.grammar_tokens = "/~ --- Token definitions --- ~/\n\n/~ Characters to be ignored ~/\n!   ' |\\t' ;\n\n/~ Non-associative tokens ~/\n";
		this.grammar_utterances = "";
		this.grammar_phrases = "phrases:";
		this.token_variables = "[*\n  var " + this.variable_prefix
				+ "result = '';\n";
		this.tokens_array = [];
	},
	convertJSONGrammar: function(){

		this.json_grammar_definition = this.maskJSON(this.json_grammar_definition);

		this.parseTokens();
		this.parseUtterances();
		this.parseStopWords();

		this.jscc_grammar_definition = this.token_variables
				+ "*]\n\n"
				+ this.grammar_tokens
				+ "\n\n ##\n\n/~ --- Grammar specification --- ~/\n\nutterance:      phrases    [*  "

				//TODO use LOG LEVEL for activating / deactivating this:
				+ "console.log("
				+ this.variable_prefix + "result); "

				+ "semanticAnnotationResult.result = "
				+ this.variable_prefix + "result; *] ;\n\n" + this.grammar_utterances
				+ "\n" + this.grammar_phrases + ";";

		this.json_grammar_definition = this.unmaskJSON(this.json_grammar_definition);
	},
	parseTokens: function(){
		var self = this;
		var json_tokens =  this.json_grammar_definition.tokens;
		var pref = self.variable_prefix;

		for(token_name in json_tokens){

			var words = json_tokens[token_name];

			self.token_variables += "  var " + pref
					+ token_name.toLowerCase() + " = {};\n";

			var grammar_token ="    '";

			for(var i=0, size = words.length; i < size ; ++i){
				if(i > 0){
					grammar_token += "|";
				}
				grammar_token += words[i];
			}

			grammar_token += "'    " + token_name + " [* " + pref
					+ token_name.toLowerCase() + "[%match] = %match; *];\n";

			self.grammar_tokens += grammar_token;
		}
	},
	parseUtterances: function(){
		var self = this;
		var utt_index = 0;
		var json_utterances =  this.json_grammar_definition.utterances;

		for(var utterance_name in json_utterances){
			var utterance_def = json_utterances[utterance_name];
			if(utt_index > 0){
				self.grammar_phrases += "\n\t|";
			}
			utt_index++;
			self.doParseUtterance(utterance_name, utterance_def);
		}
	},
	doParseUtterance: function(utterance_name, utterance_def){
		var grammar_utterance = utterance_name + ":";
		var self = this;
		self.token_variables += "  var " + self.variable_prefix
				+ utterance_name.toLowerCase() + " = {};\n";
		//self.grammar_phrases += utterance_name + "  " +  self.doCreateSemanticInterpretationForUtterance(utterance_name, utterance_def);
		self.grammar_phrases += utterance_name + "  " ;
		var phrases = utterance_def.phrases;
		var semantic  = self.doCreateSemanticInterpretationForUtterance(utterance_name, utterance_def);

		for(var index=0,size=phrases.length; index < size; ++index){
			if(index > 0){
				grammar_utterance += "\n|";
			}
			var phrase = phrases[index];
			var semantic_interpretation = self.doCreateSemanticInterpretationForPhrase(
					utterance_name.toLowerCase(), utterance_def, phrase, semantic
			);
			grammar_utterance += phrase + semantic_interpretation;
		}
		self.grammar_utterances += grammar_utterance + ";\n\n";
	},
	doCreateSemanticInterpretationForUtterance: function(utterance_name, utterance_def){
		var semantic = utterance_def.semantic,
		variable_index, variable_name;

		if(logger.isDebug()) logger.debug('doCreateSemanticInterpretationForUtterance: '+semantic);//debug

		var semantic_as_string = JSON.stringify(semantic);
		if( semantic_as_string != null){
		this.variable_regexp.lastIndex = 0;
		var variables = this.variable_regexp.exec(semantic_as_string);
		while (variables != null) {
			var variable = variables[1],
			remapped_variable_name = "";

			if(logger.isDebug()) logger.debug("variables " + variable, semantic_as_string);//debug

			variable_index = /\[(\d+)\]/.exec(variable);
			variable_name = new RegExp('_\\$([a-zA-Z_][a-zA-Z0-9_\\-]*)').exec(variable)[1];
//			variableObj = /_\$([a-zA-Z_][a-zA-Z0-9_\-]*)(\[(\d+)\])?(\["semantic"\]|\['semantic'\]|\.semantic)?/.exec(variable);
//			variableObj = /_\$([a-zA-Z_][a-zA-Z0-9_\-]*)(\[(\d+)\])?((\[(("(.*?[^\\])")|('(.*?[^\\])'))\])|(\.(\w+)))?/.exec(variable);
	//"_$NAME[INDEX]['FIELD']":  _$NAME                  [ INDEX ]        [" FIELD "]  | [' FIELD ']      |   .FIELD
			if (variable_index == null) {
				remapped_variable_name = variable;
			} else {
					remapped_variable_name = variable.replace(
							  '[' + variable_index[1] + ']'
							, "["
								+ utterance_name.toLowerCase() + "_temp['phrases']['"
								+ variable_name.toLowerCase() + "']["
								+ variable_index[1]
							+ "]."+this.entry_token_field+"]");
					//TODO replace try/catch with safe_acc function
					//     PROBLEM: currently, the format for variable-access is not well defined
					//              -> in case of accessing the "semantic" field for a variable reference of another Utterance
					//                 we would need another safe_acc call
					//				   ... i.e. need to parse expression for this, but since the format is not well defined
					//				   we cannot say, for what exactly we should parse...
					//                 NORMAL VAR EXPR: 		_$a_normal_token[0]
					//                 ACCESS TO SEMANTICS: 	_$other_utterance[0]['semantic']
					//                                      but this could also be expressed e.g. as _$other_utterance[0].semantic
					//                                      ...
//					remapped_variable_name = variable.replace(
//							  '[' + variable_index[1] + ']'
//							, "[safe_acc("
//								+ utterance_name.toLowerCase() + "_temp, 'phrases', '"
//								+ variable_name.toLowerCase() + "', "
//								+ variable_index[1]
//								+ ")]"
//							);
			}
			semantic_as_string = semantic_as_string.replace(
					variables[0],
					" function(){try{return " + remapped_variable_name
						+ ";} catch(e){return void(0);}}() "
//					"' + " + remapped_variable_name + " + '"//TODO replace try/catch with safe_acc function
			);
			variables =  this.variable_regexp.exec(semantic_as_string);
		}
		}
		return semantic_as_string;
	},
	doCreateSemanticInterpretationForPhrase: function(utterance_name, utterance_def, phrase, semantic_as_string){
		var phraseList = phrase.split(/\s+/),
		length = phraseList.length,
		duplicate_helper = {};

		var result = " [* %% = ";
		var i = 0;
		while (i < length){
			i++;
			result += "%"+i;
			if(i < length){
				result += " + ' ' + ";
			}
		}
		result += "; var "+utterance_name+"_temp = {}; "+utterance_name+"_temp['phrases'] = {};";
		for (i = 0; i < length; i += 1) {
			if (typeof(duplicate_helper[phraseList[i]]) == "undefined") {
				duplicate_helper[phraseList[i]] = 0;
				result += utterance_name+"_temp['phrases']['"+phraseList[i].toLowerCase()+"'] = [];";
			} else {
				duplicate_helper[phraseList[i]] += 1;
			}
			result += utterance_name + "_temp['phrases']['"
						+ phraseList[i].toLowerCase() + "']["
						+ duplicate_helper[phraseList[i]] + "] = {"
							+ this.entry_token_field + ": %" + (i + 1) + ","
							+ this.entry_index_field + ": " + i
						+"};\n\t\t";
		}
		result += "var " + this.variable_prefix + "phrase = %%; "
				+ utterance_name + "_temp['phrase']=" + this.variable_prefix + "phrase; "
				+ utterance_name + "_temp['utterance']='" + utterance_name + "'; "
				+ utterance_name + "_temp['engine']='jscc'; "//FIXME debug
				+ utterance_name + "_temp['semantic'] = " + semantic_as_string
				+ "; " + this.variable_prefix + utterance_name + "["
				+ this.variable_prefix + "phrase] = " + utterance_name + "_temp; "
				+ this.variable_prefix + "result = " + utterance_name + "_temp; *]";
		return result;
	}
};

return jsccGen;

});


text:
const childProcess = require('child_process');
const treeKill = require('tree-kill');
const chalk = require('chalk');

const killHelp = () => {
  process.stdout.write(chalk.magenta('kill+[enter] to properly end the process', '\n'));
};

const bye = (error, stdout, stderr) => {
  process.stdout.write(chalk.yellow('---goodbye---', '\n'));
  process.exit();
};

const kill = (pid) => {
  const isWin = /^win/.test(process.platform);
  process.stdout.write(chalk.yellow('---killing dev env---', '\n'));
  process.stdout.write(chalk.blue('pid:', pid, '\n'));
  process.stdout.write(chalk.blue('platform:', process.platform, '\n'));
  if (isWin) {
    childProcess.exec('taskkill /PID ' + pid + ' /T /F', bye);
  } else {
    treeKill(pid, 'SIGTERM', (err) => {
      if (err) process.stdout.write(chalk.red(err, '\n'));
      bye();
    });
  }
};

module.exports = {
  killHelp: killHelp,
  bye: bye,
  kill: kill,
};

redpajama_set_name: RedPajamaGithub


text:
package validators

import (
	"reflect"
	"testing"
)

var testValidators = []*Validator{
	{
		Name:     "test-v1",
		Validate: func(input *Input) (bool, error) { return true, nil },
	},
	{
		Name:     "test-v2",
		Validate: func(input *Input) (bool, error) { return false, nil },
	},
}

func TestRunValidators(t *testing.T) {
	vfMap := ValidationFailureMap(testValidators)
	failures := RunValidators(testValidators, &Input{}, vfMap, nil)

	if vfMap.GetKey("test-v1").Int64() != 0 {
		t.Error("Got unexpected test-v1 validation failure.")
	}

	if vfMap.GetKey("test-v2").Int64() != 1 {
		t.Errorf("Didn't get expected test-v2 validation failure.")
	}

	if !reflect.DeepEqual(failures, []string{"test-v2"}) {
		t.Errorf("Didn't get expected validation failures. Expected: {\"test-v2\"}, Got: %v", failures)
	}
}

func TestValidatorFailureMap(t *testing.T) {
	vfMap := ValidationFailureMap(testValidators)

	expectedKeys := []string{"test-v1", "test-v3"}
	if reflect.DeepEqual(vfMap.Keys(), expectedKeys) {
		t.Errorf("Didn't get expected keys in the mao. Got: %s, Expected: %v", vfMap.Keys(), expectedKeys)
	}
}


text:
from bs4 import BeautifulSoup as BS
import urllib
import re
import json
membersUrl = 'http://senate.ca.gov/senators'
districtClass = 'views-field-field-member-district-value'
partyClass = 'views-field-field-member-party-value'
imageDir = 'static/images/'
jsonDir = 'static/'

class Member(object):
    def __init__(self, soup):
        self.name = soup.a.string.strip()
        nameParts = self.name.split(',')
        #Note a member might have no comma (Vacant) or two commas (Jr.)
        self.lastName = nameParts[0]
        self.firstName = nameParts[-1]
        self.district = int(soup.find(class_=districtClass).string.strip())
        self.party = soup.find(class_=partyClass).string.strip()[0]
        self.imageUrl = soup.img['src']
        self.dictionaryFields = ['district', 'lastName', 'firstName', 'name', 'party']
        self.dictionary = {attr: getattr(self, attr) for attr in self.dictionaryFields}

    def saveImage(self):
        filename = str(self.district) + ".jpg"
        urllib.urlretrieve(self.imageUrl, imageDir + filename)

class Members(object):
    def __init__(self, url):
        members = urllib.urlopen(url)
        html = members.read()
        self.soup = BS(html)
        self.cells = self.soup.find_all(class_=re.compile('odd|even'))
        self.elements = []
        for m in self.cells:
            try:
                self.elements.append(Member(m))
            except Exception as e:
                print 'a member could not be added because: ' + repr(e)

    def downloadImages(self):
        for m in self.elements:
            m.saveImage()

    def saveJSON(self):
        self.dictionary = [m.dictionary for m in self.elements]
        jsonDictionary = json.dumps(self.dictionary)
        jsonFile = open(jsonDir+'members.json', 'w')
        jsonFile.write(jsonDictionary)
        jsonFile.close()

if __name__ == '__main__':
    m = Members(membersUrl)
    m.saveJSON()


text:
package com.zhigu.task;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zhigu.common.constant.enumconst.OrderStatus;
import com.zhigu.common.utils.DateUtil;
import com.zhigu.mapper.OrderMapper;
import com.zhigu.mapper.RechargeRecordMapper;
import com.zhigu.mapper.SystemTaskRecordMapper;
import com.zhigu.model.Order;
import com.zhigu.model.OrderCondition;
import com.zhigu.model.PageBean;
import com.zhigu.model.SystemTaskRecord;
import com.zhigu.model.dto.MsgBean;
import com.zhigu.service.user.ICartService;
import com.zhigu.service.user.IOrderService;

/**
 * 系统自动执行处理
 *
 * @ClassName: Task
 * @Description: 现在部分直接update,在大数据情况下需要修改为分页操作
 * @author hesimin
 * @date 2015年5月12日 下午5:38:41
 *
 */
@Component
public class Task {
	@Autowired
	private ICartService cartService;
	@Autowired
	private SystemTaskRecordMapper systemTaskRecordMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private RechargeRecordMapper rechargeRecordMapper;

	/** 自动删除购物车中多少天以前 */
	private static final int SHOPPING_CART_CLEAR_DAY = 30;
	/** 订单有效时间(小时) */
	private static final int ORDER_WAIT_PAY_HOURS = 24;
	/** 订单待收货自动确认时间(天) */
	private static final int ORDER_WAIT_CONFIRM_RECEIVE_GOODS_DAY = 30;
	/** 充值失效(小时) */
	private static final int RECHARGE_RECORD_EFFECTIVE_HOURS = 24 * 2;

	/**
	 * 购物车清除,每天2点
	 */
	@Scheduled(cron = "0 0 2 * * ?")
	public void shopingCartClear() {
		Date now = new Date();
		SystemTaskRecord record = new SystemTaskRecord();
		record.setType("购物车清除");
		record.setStartTime(now);
		systemTaskRecordMapper.insert(record);
		Date effectiveDate = DateUtils.addDays(now, -SHOPPING_CART_CLEAR_DAY);
		int row = cartService.systemDeleteBeforeByDate(DateUtil.format(effectiveDate, DateUtil.yyyy_MM_dd));
		record.setEndTime(new Date());
		record.setContent("清除行数:" + row);
		systemTaskRecordMapper.updateByPrimaryKey(record);
	}

	/**
	 * 充值失效,每天2点
	 */
	@Scheduled(cron = "0 30 4 * * ?")
	public void rechargeRecordCancel() {
		Date now = new Date();
		SystemTaskRecord record = new SystemTaskRecord();
		record.setType("充值失效");
		record.setStartTime(now);
		systemTaskRecordMapper.insert(record);
		Date effectiveDate = DateUtils.addHours(now, -RECHARGE_RECORD_EFFECTIVE_HOURS);
		int row = rechargeRecordMapper.systemCancel(DateUtil.format(effectiveDate, DateUtil.yyyy_MM_dd));
		record.setEndTime(new Date());
		record.setContent("充值失效处理行数:" + row);
		systemTaskRecordMapper.updateByPrimaryKey(record);
	}

	/**
	 * 订单自动取消
	 */
	@Scheduled(cron = "0 0 0,4,16,23 * * ?")
	public void orderCancel() {
		Date now = new Date();
		SystemTaskRecord record = new SystemTaskRecord();
		record.setType("订单取消");
		record.setStartTime(now);
		systemTaskRecordMapper.insert(record);

		PageBean page = new PageBean();
		OrderCondition oc = new OrderCondition();
		oc.setStatus(OrderStatus.ORDER_WAIT_PAY.getValue());
		oc.setEndDate(DateUtils.addHours(new Date(), -ORDER_WAIT_PAY_HOURS));
		page.addParas("oc", oc);

		orderMapper.queryOrdersByPage(page);
		while (page.getPageNo() <= page.getTotalPage()) {
			List<Order> orderList = orderMapper.queryOrdersByPage(page);
			for (Order o : orderList) {
				MsgBean msg = orderService.handlerCancelOrder(o.getOrderNO(), o.getUserID());

				SystemTaskRecord r = new SystemTaskRecord();
				r.setType("订单取消明细");
				Date n = new Date();
				r.setStartTime(n);
				r.setEndTime(n);
				r.setContent("订单号【" + o.getOrderNO() + "】" + msg.getMsg());
				systemTaskRecordMapper.insert(r);
			}
			page.setPageNo(page.getPageNo() + 1);
		}

		record.setEndTime(new Date());
		record.setContent("取消订单");
		systemTaskRecordMapper.updateByPrimaryKey(record);
	}

	/**
	 * 订单自动取消
	 */
	@Scheduled(cron = "0 0 1,5,19,23 * * ?")
	public void orderConfirmReceipt() {
		Date now = new Date();
		SystemTaskRecord record = new SystemTaskRecord();
		record.setType("订单确认收货");
		record.setStartTime(now);
		systemTaskRecordMapper.insert(record);

		PageBean page = new PageBean();
		OrderCondition oc = new OrderCondition();
		oc.setStatus(OrderStatus.ORDER_WAIT_CONFIRM_RECEIVE_GOODS.getValue());
		oc.setEndDate(DateUtils.addDays(new Date(), -ORDER_WAIT_CONFIRM_RECEIVE_GOODS_DAY));
		page.addParas("oc", oc);

		orderMapper.queryOrdersByPage(page);
		while (page.getPageNo() <= page.getTotalPage()) {
			List<Order> orderList = orderMapper.queryOrdersByPage(page);
			for (Order o : orderList) {
				MsgBean msg = orderService.handlerConfirmReceipt(o.getUserID(), o.getID());

				SystemTaskRecord r = new SystemTaskRecord();
				r.setType("订单确认收货明细");
				Date n = new Date();
				r.setStartTime(n);
				r.setEndTime(n);
				r.setContent("订单号【" + o.getOrderNO() + "】" + msg.getMsg());
				systemTaskRecordMapper.insert(r);
			}
			page.setPageNo(page.getPageNo() + 1);
		}

		record.setEndTime(new Date());
		record.setContent("订单收货");
		systemTaskRecordMapper.updateByPrimaryKey(record);
	}

	// @Scheduled(cron = "0/5 * *  * * ? ")
	// 每5秒执行一次
	public void test() {
		Date now = new Date();
		SystemTaskRecord record = new SystemTaskRecord();
		record.setType("test");
		record.setStartTime(now);
		systemTaskRecordMapper.insert(record);
		System.out.println(this.hashCode() + "task test : " + DateUtil.format(DateUtil.yyyy_MM_dd_HH_mm_ss));
		record.setEndTime(new Date());
		record.setContent("test");
		systemTaskRecordMapper.updateByPrimaryKey(record);
	}

}


text: Helping code for database CRUD (CREATE, READ, UPDATE, DELETE ) operations for android


text:
<?php

namespace Nanbando\Core\Server;

/**
 * Indicates missing command.
 */
class MissingCommandException extends \Exception
{
    /**
     * @var string
     */
    private $serverName;

    /**
     * @var string
     */
    private $commandName;

    /**
     * @param string $serverName
     * @param string $commandName
     */
    public function __construct($serverName, $commandName)
    {
        parent::__construct(sprintf('Command "%s" for server "%s" not supported.', $commandName, $serverName));

        $this->serverName = $serverName;
        $this->commandName = $commandName;
    }

    /**
     * Returns serverName.
     *
     * @return string
     */
    public function getServerName()
    {
        return $this->serverName;
    }

    /**
     * Returns commandName.
     *
     * @return string
     */
    public function getCommandName()
    {
        return $this->commandName;
    }
}


text:
.class Lcom/android/internal/telephony/uicc/UiccCard$2;
.super Landroid/os/Handler;
.source "UiccCard.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/uicc/UiccCard;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/telephony/uicc/UiccCard;

# direct methods
.method constructor <init>(Lcom/android/internal/telephony/uicc/UiccCard;)V
    .locals 0

    .prologue
    .line 481
    iput-object p1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 10
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    const/4 v6, 0x0

    const/4 v2, 0x0

    const/4 v3, 0x1

    .line 484
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mDestroyed:Z
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$300(Lcom/android/internal/telephony/uicc/UiccCard;)Z

    move-result v0

    if-eqz v0, :cond_1

    .line 485
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "Received message "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, "["

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget v2, p1, Landroid/os/Message;->what:I

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, "] while being destroyed. Ignoring."

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->loge(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$400(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 566
    :cond_0
    :goto_0
    :sswitch_0
    return-void

    .line 491
    :cond_1
    iget v0, p1, Landroid/os/Message;->what:I

    sparse-switch v0, :sswitch_data_0

    .line 564
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "Unknown Event "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget v2, p1, Landroid/os/Message;->what:I

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->loge(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$400(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    goto :goto_0

    .line 497
    :sswitch_1
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mContext:Landroid/content/Context;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$200(Lcom/android/internal/telephony/uicc/UiccCard;)Landroid/content/Context;

    move-result-object v0

    iget-object v1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mPhone:Lcom/android/internal/telephony/Phone;
    invoke-static {v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$500(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/Phone;

    move-result-object v1

    move-object v3, v2

    move-object v4, v2

    move-object v5, v2

    invoke-static/range {v0 .. v6}, Lcom/android/internal/telephony/DefaultSIMSettings;->onAllIccidQueryComplete(Landroid/content/Context;Lcom/android/internal/telephony/Phone;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V

    goto :goto_0

    .line 511
    :sswitch_2
    iget-object v7, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v7, Landroid/os/AsyncResult;

    .line 512
    .local v7, "ar":Landroid/os/AsyncResult;
    iget-object v0, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-eqz v0, :cond_2

    .line 513
    const-string v0, "UiccCard"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "Error in SIM access with exception"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/telephony/Rlog;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 516
    :cond_2
    iget-object v0, v7, Landroid/os/AsyncResult;->userObj:Ljava/lang/Object;

    check-cast v0, Landroid/os/Message;

    iget-object v1, v7, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    iget-object v2, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-static {v0, v1, v2}, Landroid/os/AsyncResult;->forMessage(Landroid/os/Message;Ljava/lang/Object;Ljava/lang/Throwable;)Landroid/os/AsyncResult;

    .line 518
    iget-object v0, v7, Landroid/os/AsyncResult;->userObj:Ljava/lang/Object;

    check-cast v0, Landroid/os/Message;

    invoke-virtual {v0}, Landroid/os/Message;->sendToTarget()V

    goto :goto_0

    .line 522
    .end local v7    # "ar":Landroid/os/AsyncResult;
    :sswitch_3
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccRecords:Lcom/android/internal/telephony/uicc/IccRecords;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$600(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccRecords;

    move-result-object v0

    instance-of v0, v0, Lcom/android/internal/telephony/uicc/SIMRecords;

    if-eqz v0, :cond_3

    .line 523
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    iget-object v1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccRecords:Lcom/android/internal/telephony/uicc/IccRecords;
    invoke-static {v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$600(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccRecords;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/internal/telephony/uicc/IccRecords;->getIMSI()Ljava/lang/String;

    move-result-object v1

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$702(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)Ljava/lang/String;

    .line 524
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "mGsmImsi = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/telephony/uicc/UiccCard;->access$700(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 525
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccFileHandler:Lcom/android/internal/telephony/uicc/IccFileHandler;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$800(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccFileHandler;

    move-result-object v0

    const/16 v1, 0x6f22

    const-string v2, "3F007F25"

    const/16 v3, 0x11

    invoke-virtual {p0, v3}, Lcom/android/internal/telephony/uicc/UiccCard$2;->obtainMessage(I)Landroid/os/Message;

    move-result-object v3

    invoke-virtual {v0, v1, v2, v3}, Lcom/android/internal/telephony/uicc/IccFileHandler;->loadEFTransparent(ILjava/lang/String;Landroid/os/Message;)V

    goto/16 :goto_0

    .line 527
    :cond_3
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccRecords:Lcom/android/internal/telephony/uicc/IccRecords;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$600(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccRecords;

    move-result-object v0

    instance-of v0, v0, Lcom/android/internal/telephony/uicc/RuimRecords;

    if-eqz v0, :cond_0

    .line 528
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    iget-object v1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccRecords:Lcom/android/internal/telephony/uicc/IccRecords;
    invoke-static {v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$600(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccRecords;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/internal/telephony/uicc/IccRecords;->getIMSI()Ljava/lang/String;

    move-result-object v1

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mCdmaImsi:Ljava/lang/String;
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$902(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)Ljava/lang/String;

    .line 529
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "mCdmaImsi = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mCdmaImsi:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/telephony/uicc/UiccCard;->access$900(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 530
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mIccFileHandler:Lcom/android/internal/telephony/uicc/IccFileHandler;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$800(Lcom/android/internal/telephony/uicc/UiccCard;)Lcom/android/internal/telephony/uicc/IccFileHandler;

    move-result-object v0

    const/16 v1, 0x6f07

    const-string v2, "3F007F20"

    const/16 v3, 0x10

    invoke-virtual {p0, v3}, Lcom/android/internal/telephony/uicc/UiccCard$2;->obtainMessage(I)Landroid/os/Message;

    move-result-object v3

    invoke-virtual {v0, v1, v2, v3}, Lcom/android/internal/telephony/uicc/IccFileHandler;->loadEFTransparent(ILjava/lang/String;Landroid/os/Message;)V

    goto/16 :goto_0

    .line 535
    :sswitch_4
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    const-string v1, "handleMessage (EVENT_GET_CDMA_IMSI_DONE)"

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 536
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGetImsiDoneFlag:Z
    invoke-static {v0, v3}, Lcom/android/internal/telephony/uicc/UiccCard;->access$1002(Lcom/android/internal/telephony/uicc/UiccCard;Z)Z

    .line 537
    iget-object v7, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v7, Landroid/os/AsyncResult;

    .line 538
    .restart local v7    # "ar":Landroid/os/AsyncResult;
    iget-object v0, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-nez v0, :cond_4

    .line 539
    iget-object v0, v7, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v0, [B

    move-object v8, v0

    check-cast v8, [B

    .line 540
    .local v8, "mCdmaRawData":[B
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    iget-object v1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->parseCdmaImsi([B)Ljava/lang/String;
    invoke-static {v1, v8}, Lcom/android/internal/telephony/uicc/UiccCard;->access$1100(Lcom/android/internal/telephony/uicc/UiccCard;[B)Ljava/lang/String;

    move-result-object v1

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mCdmaImsi:Ljava/lang/String;
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$902(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)Ljava/lang/String;

    .line 541
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "mCdmaImsi = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mCdmaImsi:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/telephony/uicc/UiccCard;->access$900(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 545
    .end local v8    # "mCdmaRawData":[B
    :goto_1
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    const-string v1, "notify GET_CDMA_IMSI_DONE"

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 546
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mDualImsiReadyRegistrants:Landroid/os/RegistrantList;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$1200(Lcom/android/internal/telephony/uicc/UiccCard;)Landroid/os/RegistrantList;

    move-result-object v0

    invoke-virtual {v0}, Landroid/os/RegistrantList;->notifyRegistrants()V

    goto/16 :goto_0

    .line 543
    :cond_4
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "exception"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    goto :goto_1

    .line 549
    .end local v7    # "ar":Landroid/os/AsyncResult;
    :sswitch_5
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGetImsiDoneFlag:Z
    invoke-static {v0, v3}, Lcom/android/internal/telephony/uicc/UiccCard;->access$1002(Lcom/android/internal/telephony/uicc/UiccCard;Z)Z

    .line 550
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    const-string v1, "handleMessage (EVENT_GET_GSM_IMSI_DONE)"

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 551
    iget-object v7, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v7, Landroid/os/AsyncResult;

    .line 552
    .restart local v7    # "ar":Landroid/os/AsyncResult;
    iget-object v0, v7, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v0, [B

    move-object v9, v0

    check-cast v9, [B

    .line 553
    .local v9, "mGsmRawData":[B
    iget-object v0, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-nez v0, :cond_5

    .line 554
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    aget-byte v1, v9, v6

    invoke-static {v9, v3, v1}, Lcom/android/internal/telephony/uicc/IccUtils;->bcdToString([BII)Ljava/lang/String;

    move-result-object v1

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$702(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)Ljava/lang/String;

    .line 555
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    iget-object v1, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$700(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/telephony/uicc/UiccCard;->access$700(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/String;->length()I

    move-result v2

    invoke-virtual {v1, v3, v2}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v1

    # setter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$702(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)Ljava/lang/String;

    .line 556
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "mGsmImsi = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mGsmImsi:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/telephony/uicc/UiccCard;->access$700(Lcom/android/internal/telephony/uicc/UiccCard;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 560
    :goto_2
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    const-string v1, "notify GET_GSM_IMSI_DONE"

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    .line 561
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    # getter for: Lcom/android/internal/telephony/uicc/UiccCard;->mDualImsiReadyRegistrants:Landroid/os/RegistrantList;
    invoke-static {v0}, Lcom/android/internal/telephony/uicc/UiccCard;->access$1200(Lcom/android/internal/telephony/uicc/UiccCard;)Landroid/os/RegistrantList;

    move-result-object v0

    invoke-virtual {v0}, Landroid/os/RegistrantList;->notifyRegistrants()V

    goto/16 :goto_0

    .line 558
    :cond_5
    iget-object v0, p0, Lcom/android/internal/telephony/uicc/UiccCard$2;->this$0:Lcom/android/internal/telephony/uicc/UiccCard;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "exception"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, v7, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    # invokes: Lcom/android/internal/telephony/uicc/UiccCard;->log(Ljava/lang/String;)V
    invoke-static {v0, v1}, Lcom/android/internal/telephony/uicc/UiccCard;->access$100(Lcom/android/internal/telephony/uicc/UiccCard;Ljava/lang/String;)V

    goto :goto_2

    .line 491
    nop

    :sswitch_data_0
    .sparse-switch
        0xd -> :sswitch_1
        0xe -> :sswitch_0
        0xf -> :sswitch_3
        0x10 -> :sswitch_5
        0x11 -> :sswitch_4
        0x64 -> :sswitch_2
        0x65 -> :sswitch_2
        0x66 -> :sswitch_2
        0x67 -> :sswitch_2
        0x68 -> :sswitch_2
        0x69 -> :sswitch_2
    .end sparse-switch
.end method


text:
package org.apache.flink.streaming.runtime.operators.windowing.functions;

import org.apache.flink.api.common.functions.IterationRuntimeContext;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.java.operators.translation.WrappingFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.util.Collections;

/**
 * Internal window function for wrapping a {@link WindowFunction} that takes an {@code Iterable}
 * when the window state is a single value.
 */
public final class InternalSingleValueWindowFunction<IN, OUT, KEY, W extends Window>
        extends WrappingFunction<WindowFunction<IN, OUT, KEY, W>>
        implements InternalWindowFunction<IN, OUT, KEY, W> {

    private static final long serialVersionUID = 1L;

    public InternalSingleValueWindowFunction(WindowFunction<IN, OUT, KEY, W> wrappedFunction) {
        super(wrappedFunction);
    }

    @Override
    public void process(
            KEY key, W window, InternalWindowContext context, IN input, Collector<OUT> out)
            throws Exception {
        wrappedFunction.apply(key, window, Collections.singletonList(input), out);
    }

    @Override
    public void clear(W window, InternalWindowContext context) throws Exception {}

    @Override
    public RuntimeContext getRuntimeContext() {
        throw new RuntimeException("This should never be called.");
    }

    @Override
    public IterationRuntimeContext getIterationRuntimeContext() {
        throw new RuntimeException("This should never be called.");
    }
}


text:
import {Runtime} from '../../../../build/runtime/runtime.js';
import {logsFactory} from '../../../../build/platform/logs-factory.js';

const {log} = logsFactory('pipe::parse');

// can provide either a path or literal content for a manifest
export const parse = async (runtime, {id, path, content}, bus) => {
  // TODO(sjmiles): catch exceptions and relay over bus?
  let manifest;
  if (path) {
    log(`loading [${path}]`);
    manifest = await runtime.parseFile(path);
  } else if (content) {
    log(`parsing [${content.length}] bytes`);
    manifest = await runtime.parse(content);
  }
  let recipes = [];
  if (manifest) {
    recipes = manifest.allRecipes.map(r => ({name: r.name}));
  }
  log(`sending [${JSON.stringify(recipes)}]`);
  bus.send({messageType: 'manifest', id, recipes});
};


text:
package com.codepath.apps.restclienttemplate.models;

import com.codepath.apps.restclienttemplate.MyDatabase;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;

import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcel;

/**
 * Created by tanvigupta on 6/26/17.
 */

@Table(database = MyDatabase.class)
@Parcel(analyze={User.class})
public class User extends BaseModel {

    // attributes of this class
    @Column
    public String name;

    @Column
    @PrimaryKey
    public long uid;

    @Column
    public String screenName;

    @Column
    public String profileImageUrl;

    @Column
    public String tagline;

    @Column
    public int followingCount;

    @Column
    public int followersCount;

    public User() {
    }

    // deserialize the JSON
    public static User fromJSON(JSONObject json) throws JSONException {
        User user = new User();

        // extract values
        user.name = json.getString("name");
        user.uid = json.getLong("id");
        user.screenName = json.getString("screen_name");
        user.profileImageUrl = json.getString("profile_image_url");
        user.tagline = json.getString("description");
        user.followersCount = json.getInt("followers_count");
        user.followingCount = json.getInt("friends_count");

        String s = user.profileImageUrl;
        s = s.replace("normal", "bigger");
        user.profileImageUrl = s;

        // enter user into database
        user.save();

        return user;
    }
}


text:
package Service::Web::UrlData;

use strict;
use warnings;

use Moose;
use namespace::autoclean;

with( ServiceClient => { server_address => join( ":" , $ENV{ SERVICES_BASE } , $ENV{ SERVICE_PORT_URLDATA } ) } );

sub get_field {
    my $this = shift;
    return $this->_url_data_service_request( 'url-data' , @_ );
}

sub global_count {
    my $this = shift;
    return $this->_url_data_service_request( 'global-count' , @_ );
}

sub _url_data_service_request {

    my $this = shift;
    my $method = shift;

    # forward request to service
    my $service_response = $this->request( $method , @_ );

    return $service_response;

}

1;


text:
using System;
using System.Collections.Generic;
using System.Text;
using JetBrains.Annotations;
using Newtonsoft.Json;

namespace VimeoDotNet.Models
{
    public class Folder
    {
        /// <summary>
        /// User
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "user")]
        public User User { get; set; }

        /// <summary>
        /// Created time
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "created_time")]
        public DateTime CreatedTime { get; set; }

        /// <summary>
        /// Modified time
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "modified_time")]
        public DateTime ModifiedTime { get; set; }

        /// <summary>
        /// Name
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Privacy
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "privacy")]
        public Privacy Privacy { get; set; }

        /// <summary>
        /// Status
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "resource_key")]
        public string ResourceKey { get; set; }

        /// <summary>
        /// URI
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "uri")]
        public string Uri { get; set; }

        /// <summary>
        /// URI
        /// </summary>
        [PublicAPI]
        [JsonProperty(PropertyName = "link")]
        public string Link { get; set; }
    }
}


text:
package io.opensec.six.oval.core.repository.morphia.definitions;

import io.opensec.six.oval.model.common.GeneratorType;
import io.opensec.six.oval.model.definitions.DefinitionType;
import io.opensec.six.oval.model.definitions.DefinitionsType;
import io.opensec.six.oval.model.definitions.OvalDefinitions;
import io.opensec.six.oval.model.definitions.StateType;
import io.opensec.six.oval.model.definitions.StatesType;
import io.opensec.six.oval.model.definitions.SystemObjectType;
import io.opensec.six.oval.model.definitions.SystemObjectsType;
import io.opensec.six.oval.model.definitions.TestType;
import io.opensec.six.oval.model.definitions.TestsType;
import io.opensec.six.oval.model.definitions.VariableType;
import io.opensec.six.oval.model.definitions.VariablesType;
import io.opensec.util.core.repository.morphia.BaseDAO;
import java.util.UUID;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.dao.DAO;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author  Akihito Nakamura, AIST
 */
public class OvalDefinitionsDAO
    extends BaseDAO<OvalDefinitions, String>
{

    /**
     * Logger.
     */
    private static final Logger  _LOG_ = LoggerFactory.getLogger( OvalDefinitionsDAO.class );

    /**
     */
    public OvalDefinitionsDAO(
                    final Datastore ds
                    )
    {
        super( OvalDefinitions.class, ds );
    }

    protected Key<OvalDefinitions> _findUniqueKey(
                    final OvalDefinitions oval_definitions
                    )
    {
        Query<OvalDefinitions>  q = createQuery();

        GeneratorType  generator = oval_definitions.getGenerator();
        q.filter( "generator.timestamp",      generator.getTimestamp() );
        q.filter( "generator.schema_version", generator.getSchemaVersion() );

        String  digest = oval_definitions.getDefinitionsDigest();
        q.filter( "definitions_digest", digest );

        _LOG_.debug( "find unique: query=" + q );
        Key<OvalDefinitions>  id = find( q ).getKey();
        _LOG_.debug( "find unique: id=" + id );

        return id;
    }

    protected Key<OvalDefinitions> _findExistingKey(
                    final OvalDefinitions oval_definitions
                    )
    {
        Query<OvalDefinitions>  q = createQuery();

        String  pid = oval_definitions.getPersistentID();
        if (pid == null) {
            GeneratorType  generator = oval_definitions.getGenerator();
            q.filter( "generator.timestamp",      generator.getTimestamp() );
            q.filter( "generator.schema_version", generator.getSchemaVersion() );

            String  digest = oval_definitions.getDefinitionsDigest();
            q.filter( "definitions_digest", digest );

        } else {
            q.filter( "_id", oval_definitions.getPersistentID() );
        }

        _LOG_.debug( "find existing key: query=" + q );
        Key<OvalDefinitions>  key = find( q ).getKey();
        _LOG_.debug( "find existing key: found key=" + key );

        return key;
    }

    //*********************************************************************
    //  DAO
    //*********************************************************************

    @Override
    public Key<OvalDefinitions> save(
                    final OvalDefinitions oval_definitions
                    )
    {
        Key<OvalDefinitions>  key = _findExistingKey( oval_definitions );
        if (key != null) {
            oval_definitions.setPersistentID( String.valueOf( key.getId() ) );
            _LOG_.debug( "equivalent OvalDefinitions already exists: ID=" + oval_definitions.getPersistentID() );
            return key;
        }

        String  pid = oval_definitions.getPersistentID();
        if (pid == null) {
            pid = UUID.randomUUID().toString();
            oval_definitions.setPersistentID( pid );
        }

        VariablesType  variables = oval_definitions.getVariables();
        if (variables != null) {
            DAO<VariableType, String>  dao = _getForwardingDAO( VariableType.class );
            for (VariableType  variable : variables.getVariable()) {
                _LOG_.debug( "saving Variable: OVAL ID=" + variable.getOvalId() );
                variable.ovalSetGenerator( oval_definitions.getGenerator() );
                dao.save( variable );
            }
        }

        StatesType  states = oval_definitions.getStates();
        if (states != null) {
            DAO<StateType, String>  dao = _getForwardingDAO( StateType.class );
            for (StateType  state : states.getState()) {
                _LOG_.debug( "saving State: OVAL ID=" + state.getOvalId() );
                state.ovalSetGenerator( oval_definitions.getGenerator() );
                dao.save( state );
            }
        }

        SystemObjectsType  objects = oval_definitions.getObjects();
        if (objects != null) {
            DAO<SystemObjectType, String>  dao = _getForwardingDAO( SystemObjectType.class );
            for (SystemObjectType  object : objects.getObject()) {
                _LOG_.debug( "saving Object: OVAL ID=" + object.getOvalId() );
                object.ovalSetGenerator( oval_definitions.getGenerator() );
                dao.save( object );
            }
        }

        TestsType  tests = oval_definitions.getTests();
        if (tests != null) {
            DAO<TestType, String>  dao = _getForwardingDAO( TestType.class );
            for (TestType  test : tests.getTest()) {
                _LOG_.debug( "saving Test: OVAL ID=" + test.getOvalId() );
                test.ovalSetGenerator( oval_definitions.getGenerator() );
                dao.save( test );
            }
        }

        DefinitionsType  definitions = oval_definitions.getDefinitions();
        if (definitions != null) {
            DAO<DefinitionType, String>  dao = _getForwardingDAO( DefinitionType.class );
            for (DefinitionType  definition : definitions.getDefinition()) {
                _LOG_.debug( "saving Definition: OVAL ID=" + definition.getOvalId() );

                //TODO: for NETSAP2013, deprecated Definitions are ignored.
                // If deprecated definitions are NOT saved, they must be removed
                // from the Definitions list.
                // Otherwise, saving oval_definitions cause ERROR because
                // some Definitions have NULL @Id _id values.
                // For example, the Mitre's Solaris vuln XML contains
                // deprecated Definitions, e.g. oval:org.mitre.oval:def:1163.
//                if (definition.getDeprecated() == Boolean.TRUE) {
//                    continue;
//                }

                definition.ovalSetGenerator( oval_definitions.getGenerator() );
                dao.save( definition );
            }
        }

        //compute the digest!!!
        oval_definitions.getDefinitionsDigest();

        _LOG_.debug( "saving OvalDefinitions: ID=" + oval_definitions.getPersistentID() );
        return super.save( oval_definitions );
    }

//    @Override
//    public Key<OvalDefinitions> save(
//                    final OvalDefinitions oval_definitions
//                    )
//    {
//        Key<OvalDefinitions>  key = _findUniqueKey( oval_definitions );
//        if (key != null) {
//            oval_definitions.setPersistentID( String.valueOf( key.getId() ) );
//            return key;
//        }
//
//
//        VariablesType  variables = oval_definitions.getVariables();
//        if (variables != null) {
//            DAO<VariableType, String>  dao = _getForwardingDAO( VariableType.class );
//            for (VariableType  variable : variables.getVariable()) {
//                variable.generator( oval_definitions.getGenerator() );
//                dao.save( variable );
//            }
//        }
//
//        StatesType  states = oval_definitions.getStates();
//        if (states != null) {
//            DAO<StateType, String>  dao = _getForwardingDAO( StateType.class );
//            for (StateType  state : states.getState()) {
//                state.generator( oval_definitions.getGenerator() );
//                dao.save( state );
//            }
//        }
//
//        SystemObjectsType  objects = oval_definitions.getObjects();
//        if (objects != null) {
//            DAO<SystemObjectType, String>  dao = _getForwardingDAO( SystemObjectType.class );
//            for (SystemObjectType  object : objects.getObject()) {
//                object.generator( oval_definitions.getGenerator() );
//                dao.save( object );
//            }
//        }
//
//        TestsType  tests = oval_definitions.getTests();
//        if (tests != null) {
//            DAO<TestType, String>  dao = _getForwardingDAO( TestType.class );
//            for (TestType  test : tests.getTest()) {
//                test.generator( oval_definitions.getGenerator() );
//                dao.save( test );
//            }
//        }
//
//        DefinitionsType  definitions = oval_definitions.getDefinitions();
//        if (definitions != null) {
//            DAO<DefinitionType, String>  dao = _getForwardingDAO( DefinitionType.class );
//            for (DefinitionType  definition : definitions.getDefinition()) {
//                definition.generator( oval_definitions.getGenerator() );
//                dao.save( definition );
//            }
//        }
//
//        //compute the digest!!!
//        oval_definitions.getDefinitionsDigest();
//
//        return super.save( oval_definitions );
//    }
}
// OvalDefinitionsDAO


text:
var resizeSensorFactory = (function (global) {
    'use strict';

    /** @var {Function} */
    var getStyle = require('./getStyle');
    /** @var {Object} */
    var css = require('./css');

    /**
     * @param {HTMLElement} targetElement
     * @param {Function} callback
     * @constructor
     */
    var resizeSensor = function (targetElement, callback) {
        /** @var {HTMLElement} */
        this.targetElement = targetElement;
        /** @var {Function} */
        this.callback = callback;
        /** @var {{width: int, height: int}} */
        this.dimensions = {
            width: 0,
            height: 0
        };

        if ('attachEvent' in global.document) {
            this.boundOnResizeHandler = this.onElementResize.bind(this);
            this.targetElement.attachEvent('onresize', this.boundOnResizeHandler);
            return;
        }

        /** @var {{container: HTMLElement, expand: HTMLElement, expandChild: HTMLElement, contract: HTMLElement}} */
        this.triggerElements = {};
        /** @var {int} */
        this.resizeRAF = 0;

        this.setup();
    };

    resizeSensor.prototype.setup = function () {
        // Make sure the target element is "positioned"
        if (getStyle(this.targetElement, 'position') === 'static') {
            this.targetElement.style.position = 'relative';
        }

        // Create and append resize trigger elements
        this.insertResizeTriggerElements();

        // Start listening to events
        this.boundScrollListener = this.handleElementScroll.bind(this);
        this.targetElement.addEventListener('scroll', this.boundScrollListener, true);

        if (css.isAnimationSupported()) {
            this.boundAnimationStartListener = this.resetTriggersOnAnimationStart.bind(this);
            this.triggerElements.container.addEventListener(
                css.getAnimationPropertiesForBrowser().animationStartEvent,
                this.boundAnimationStartListener
            );
        }

        // Initial value reset of all triggers
        this.resetTriggers();
    };

    resizeSensor.prototype.insertResizeTriggerElements = function () {
        var resizeTrigger = global.document.createElement('div');
        var expandTrigger = global.document.createElement('div');
        var expandTriggerChild = global.document.createElement('div');
        var contractTrigger = global.document.createElement('div');

        resizeTrigger.className = 'ResizeSensor ResizeSensor__resizeTriggers';
        expandTrigger.className = 'ResizeSensor__expandTrigger';
        contractTrigger.className = 'ResizeSensor__contractTrigger';

        expandTrigger.appendChild(expandTriggerChild);
        resizeTrigger.appendChild(expandTrigger);
        resizeTrigger.appendChild(contractTrigger);

        this.triggerElements.container = resizeTrigger;
        this.triggerElements.expand = expandTrigger;
        this.triggerElements.expandChild = expandTriggerChild;
        this.triggerElements.contract = contractTrigger;

        this.targetElement.appendChild(resizeTrigger);
    };

    resizeSensor.prototype.onElementResize = function () {
        var currentDimensions = this.getDimensions();

        if (this.isResized(currentDimensions)) {
            this.dimensions.width = currentDimensions.width;
            this.dimensions.height = currentDimensions.height;
            this.elementResized();
        }
    };

    resizeSensor.prototype.handleElementScroll = function () {
        var _this = this;

        this.resetTriggers();

        if (this.resizeRAF) {
            global.cancelAnimationFrame(this.resizeRAF);
        }

        this.resizeRAF = global.requestAnimationFrame(function () {
            var currentDimensions = _this.getDimensions();
            if (_this.isResized(currentDimensions)) {
                _this.dimensions.width = currentDimensions.width;
                _this.dimensions.height = currentDimensions.height;
                _this.elementResized();
            }
        });
    };

    /**
     * @param {{width: number, height: number}} currentDimensions
     * @returns {boolean}
     */
    resizeSensor.prototype.isResized = function (currentDimensions) {
        return (currentDimensions.width !== this.dimensions.width || currentDimensions.height !== this.dimensions.height);
    };

    /**
     * @returns {{width: number, height: number}}
     */
    resizeSensor.prototype.getDimensions = function () {
        return {
            width: this.targetElement.offsetWidth,
            height: this.targetElement.offsetHeight
        };
    };

    /**
     * @param {Event} event
     */
    resizeSensor.prototype.resetTriggersOnAnimationStart = function (event) {
        if (event.animationName === css.getAnimationPropertiesForBrowser().animationName) {
            this.resetTriggers();
        }
    };

    resizeSensor.prototype.resetTriggers = function () {
        this.triggerElements.contract.scrollLeft = this.triggerElements.contract.scrollWidth;
        this.triggerElements.contract.scrollTop = this.triggerElements.contract.scrollHeight;
        this.triggerElements.expandChild.style.width = this.triggerElements.expand.offsetWidth + 1 + 'px';
        this.triggerElements.expandChild.style.height = this.triggerElements.expand.offsetHeight + 1 + 'px';
        this.triggerElements.expand.scrollLeft = this.triggerElements.expand.scrollWidth;
        this.triggerElements.expand.scrollTop = this.triggerElements.expand.scrollHeight;
    };

    resizeSensor.prototype.elementResized = function () {
        this.callback(this.dimensions);
    };

    resizeSensor.prototype.destroy = function () {
        this.removeEventListeners();
        this.targetElement.removeChild(this.triggerElements.container);
        delete this.boundAnimationStartListener;
        delete this.boundScrollListener;
        delete this.callback;
        delete this.targetElement;
    };

    resizeSensor.prototype.removeEventListeners = function () {
        if ('attachEvent' in global.document) {
            this.targetElement.detachEvent('onresize', this.boundOnResizeHandler);
            return;
        }

        this.triggerElements.container.removeEventListener(
            css.getAnimationPropertiesForBrowser().animationStartEvent,
            this.boundAnimationStartListener
        );
        this.targetElement.removeEventListener('scroll', this.boundScrollListener, true);
    };

    return {
        /**
         * @param {Element} targetElement
         * @param {Function} callback
         * @returns {resizeSensor}
         */
        create: function (targetElement, callback) {
            return new resizeSensor(targetElement, callback);
        }
    };
})(typeof window !== 'undefined' ? window : this);

module.exports = resizeSensorFactory;


text:
#include "tensorflow/lite/experimental/micro/examples/micro_speech/audio_provider.h"
#include "tensorflow/lite/experimental/micro/examples/micro_speech/command_responder.h"
#include "tensorflow/lite/experimental/micro/examples/micro_speech/feature_provider.h"
#include "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/micro_model_settings.h"
#include "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/tiny_conv_micro_features_model_data.h"
#include "tensorflow/lite/experimental/micro/examples/micro_speech/recognize_commands.h"
#include "tensorflow/lite/experimental/micro/micro_error_reporter.h"
#include "tensorflow/lite/experimental/micro/micro_interpreter.h"
#include "tensorflow/lite/experimental/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/version.h"

namespace tflite {
namespace ops {
namespace micro {
TfLiteRegistration* Register_DEPTHWISE_CONV_2D();
TfLiteRegistration* Register_FULLY_CONNECTED();
TfLiteRegistration* Register_SOFTMAX();
}  // namespace micro
}  // namespace ops
}  // namespace tflite

// Globals, used for compatibility with Arduino-style sketches.
namespace {
tflite::ErrorReporter* error_reporter = nullptr;
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* model_input = nullptr;
FeatureProvider* feature_provider = nullptr;
RecognizeCommands* recognizer = nullptr;
int32_t previous_time = 0;

// Create an area of memory to use for input, output, and intermediate arrays.
// The size of this will depend on the model you're using, and may need to be
// determined by experimentation.
constexpr int kTensorArenaSize = 10 * 1024;
uint8_t tensor_arena[kTensorArenaSize];
}  // namespace

// The name of this function is important for Arduino compatibility.
void setup() {
  // Set up logging. Google style is to avoid globals or statics because of
  // lifetime uncertainty, but since this has a trivial destructor it's okay.
  // NOLINTNEXTLINE(runtime-global-variables)
  static tflite::MicroErrorReporter micro_error_reporter;
  error_reporter = &micro_error_reporter;

  // Map the model into a usable data structure. This doesn't involve any
  // copying or parsing, it's a very lightweight operation.
  model = tflite::GetModel(g_tiny_conv_micro_features_model_data);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    error_reporter->Report(
        "Model provided is schema version %d not equal "
        "to supported version %d.",
        model->version(), TFLITE_SCHEMA_VERSION);
    return;
  }

  // Pull in only the operation implementations we need.
  // This relies on a complete list of all the ops needed by this graph.
  // An easier approach is to just use the AllOpsResolver, but this will
  // incur some penalty in code space for op implementations that are not
  // needed by this graph.
  //
  // tflite::ops::micro::AllOpsResolver resolver;
  // NOLINTNEXTLINE(runtime-global-variables)
  static tflite::MicroMutableOpResolver micro_mutable_op_resolver;
  micro_mutable_op_resolver.AddBuiltin(
      tflite::BuiltinOperator_DEPTHWISE_CONV_2D,
      tflite::ops::micro::Register_DEPTHWISE_CONV_2D());
  micro_mutable_op_resolver.AddBuiltin(
      tflite::BuiltinOperator_FULLY_CONNECTED,
      tflite::ops::micro::Register_FULLY_CONNECTED());
  micro_mutable_op_resolver.AddBuiltin(tflite::BuiltinOperator_SOFTMAX,
                                       tflite::ops::micro::Register_SOFTMAX());

  // Build an interpreter to run the model with.
  static tflite::MicroInterpreter static_interpreter(
      model, micro_mutable_op_resolver, tensor_arena, kTensorArenaSize,
      error_reporter);
  interpreter = &static_interpreter;

  // Allocate memory from the tensor_arena for the model's tensors.
  TfLiteStatus allocate_status = interpreter->AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    error_reporter->Report("AllocateTensors() failed");
    return;
  }

  // Get information about the memory area to use for the model's input.
  model_input = interpreter->input(0);
  if ((model_input->dims->size != 4) || (model_input->dims->data[0] != 1) ||
      (model_input->dims->data[1] != kFeatureSliceCount) ||
      (model_input->dims->data[2] != kFeatureSliceSize) ||
      (model_input->type != kTfLiteUInt8)) {
    error_reporter->Report("Bad input tensor parameters in model");
    return;
  }

  // Prepare to access the audio spectrograms from a microphone or other source
  // that will provide the inputs to the neural network.
  // NOLINTNEXTLINE(runtime-global-variables)
  static FeatureProvider static_feature_provider(kFeatureElementCount,
                                                 model_input->data.uint8);
  feature_provider = &static_feature_provider;

  static RecognizeCommands static_recognizer(error_reporter);
  recognizer = &static_recognizer;

  previous_time = 0;
}

// The name of this function is important for Arduino compatibility.
void loop() {
  // Fetch the spectrogram for the current time.
  const int32_t current_time = LatestAudioTimestamp();
  int how_many_new_slices = 0;
  TfLiteStatus feature_status = feature_provider->PopulateFeatureData(
      error_reporter, previous_time, current_time, &how_many_new_slices);
  if (feature_status != kTfLiteOk) {
    error_reporter->Report("Feature generation failed");
    return;
  }
  previous_time = current_time;
  // If no new audio samples have been received since last time, don't bother
  // running the network model.
  if (how_many_new_slices == 0) {
    return;
  }

  // Run the model on the spectrogram input and make sure it succeeds.
  TfLiteStatus invoke_status = interpreter->Invoke();
  if (invoke_status != kTfLiteOk) {
    error_reporter->Report("Invoke failed");
    return;
  }

  // The output from the model is a vector containing the scores for each
  // kind of prediction, so figure out what the highest scoring category was.
  TfLiteTensor* output = interpreter->output(0);
  uint8_t top_category_score = 0;
  for (int category_index = 0; category_index < kCategoryCount;
       ++category_index) {
    const uint8_t category_score = output->data.uint8[category_index];
    if (category_score > top_category_score) {
      top_category_score = category_score;
    }
  }

  const char* found_command = nullptr;
  uint8_t score = 0;
  bool is_new_command = false;
  TfLiteStatus process_status = recognizer->ProcessLatestResults(
      output, current_time, &found_command, &score, &is_new_command);
  if (process_status != kTfLiteOk) {
    error_reporter->Report("RecognizeCommands::ProcessLatestResults() failed");
    return;
  }
  // Do something based on the recognized command. The default implementation
  // just prints to the error console, but you should replace this with your
  // own function for a real application.
  RespondToCommand(error_reporter, current_time, found_command, score,
                   is_new_command);
}

int main(int argc, char* argv[]) {
  setup();
  while (true) {
    loop();
  }
}


text:
/* Based on the original Style Sheet for the fisubsilver v2 Theme for phpBB version 2+
Edited by Daz  - http://www.forumimages.com - last updated 13-03-03 */

/* The content of the posts (body of text) */
body{background:#2e2e2e;color:#e7e7e7;font:12px Verdana,Arial,Helvetica,sans-serif;margin:6px;padding:0;
scrollbar-3dlight-color: #6a6a6a;
scrollbar-arrow-color: #fc9b00;
scrollbar-darkshadow-color: #000000;
scrollbar-face-color: #444444;
scrollbar-highlight-color: #444444;
scrollbar-shadow-color: #000000;
scrollbar-track-color: #2e2e2e}

/* General font families for common tags */
font,th,td,p{font:12px Verdana,Arial,Helvetica,sans-serif}
p{margin-top:2px;margin-bottom:3px}

/* General text */
.gensmall{font-size:10px}
td.genmed,.genmed{font-size:11px}
.explaintitle{font-size:11px;font-weight:bold;color:#727272}

/* General page style */
a:link,a:active,a:visited,a.postlink{color:#dd6900;text-decoration:none}
a:hover{color:#767676}

/* titles for the topics:could specify viewed link colour too */
.topictitle{font-size:11px;font-weight:bold}
a.topictitle:visited{color:#ca6000}
a.topictitle:hover{color:#767676}

/* Name of poster in viewmsg.php and viewtopic.php and other places */
.name{font-size:11px;font-weight: bold}

hr{border: 0px solid #000000;border-top-width:1px;height:0px}

/* Category gradients*/
td.cat{font-weight:bold;letter-spacing:1px;background:#191919 url(images/cellpic1.gif);
height:29px;text-indent:4px}

a.cattitle,a.cattitle:visited{color:#767676}
a.cattitle:hover{color:#dd6900}

/* Main table cell colours and backgrounds */
.row1{background:#272727}
.row2,.helpline{background:#303030}
.row3{background:#414141}
td.spacerow{background:#464646}

/* This is for the table cell above the Topics,Post & Last posts on the index.php */
td.rowpic{background: #343434 url(images/cellpic2.jpg) repeat-y}

/* Table Header cells */
th{background: #171717 url(images/cellpic3.gif);color: #8e8e8e;font-size:11px;
font-weight:bold;height:27px;white-space:nowrap;text-align:center;padding-left:8px;padding-right:8px}

/* This is the border line & background colour round the entire page */
.bodyline{background:#303030;border:1px solid #ff8c00}

/* This is the outline round the main forum tables */
.forumline{background:#010101;border:1px solid #d2a900}

/* The largest text used in the index page title and toptic title etc. */
.maintitle,h1{
font:bold 20px/120% "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;text-decoration:none;color:#767676}

.subtitle,h2{font:bold 18px/180% "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;
text-decoration:none}

/* Used for the navigation text,(Page 1,2,3 etc) and the navigation bar when in a forum */
.nav{font-size:11px;font-weight:bold}
.postbody{font-size:12px;line-height:125%}

/* Location,number of posts,post date etc */
.postdetails{font-size:10px;color:#8a8a8a}

/* Quote blocks */
.quote{background:#525252;border:1px solid #000000;color:#e7e7e7;
font-size:11px;line-height:125%}

/* Code blocks */
.code{background:#545454;border:1px solid #000000;color:#fff8dc;
font:12px Courier,"Courier New",sans-serif;padding:5px}

/* This is for the error messages that pop up */
.errorline{background:#ff8c00;border:1px solid #000000}

/* Form elements */
form{display:inline}

input{font:11px Verdana,Arial,Helvetica,sans-serif;color:#e7e7e7}

select{background:#303030;color:#e7e7e7;font:11px Verdana,Arial,Helvetica,sans-serif}

input.post,textarea.post{background:#303030;border:1px solid #000000;color:#e7e7e7;
font:11px Verdana,Arial,Helvetica,sans-serif;padding-bottom:2px;padding-left:2px}

input.button,input.liteoption,.fakebut{border:1px solid #d77700;background:#303030;font-size:11px;color:#dd6900}
input.catbutton{border:1px solid #d77700;background:#303030;font-size:10px}
input.mainoption{border:1px solid #d77700;background:#303030;font-size:11px;font-weight:bold}

a.but,a.but:hover,a.but:visited{color:#dd6900;text-decoration:none}

/* This is the line in the posting page which shows the rollover
help line. Colour value in row2 */
.helpline{border-style:none}

/* This is the gradient background at the top of the page */
.topbkg{background: #1a1a1a url(images/cellpic_bkg.jpg) repeat-x}
.topnav{font-size:10px;background: #1d1c19 url(images/cellpic_nav.gif) repeat-x;color:#dd6900;
height:21px;white-space:nowrap;border: 0px solid #d77700;border-width: 1px 0px 1px 0px}

/* Admin & Moderator Colours MODification */
.admin,.mod{font-size:11px;font-weight:bold}
.admin,a.admin,a.admin:visited{color:#ffa34f}
.mod,a.mod,a.mod:visited{color:#006699}
a.admin:hover,a.mod:hover{color:#767676}

/* Specify the space around images */
.imgtopic,.imgicon{margin-left:3px}
.imgspace{margin-left:1px;margin-right:2px}
.imgfolder{margin:1px;margin-left:4px;margin-right:4px}

/* Gets rid of the need for border="0" on hyperlinked images */
img{border:0}